file_name
stringlengths 71
779k
| comments
stringlengths 20
182k
| code_string
stringlengths 20
36.9M
| __index_level_0__
int64 0
17.2M
| input_ids
sequence | attention_mask
sequence | labels
sequence |
---|---|---|---|---|---|---|
./full_match/43113/0x6b9c8c5ac8161a932FF63308D0dF500a76c069AF/sources/src/Comptroller/IronControllerV2.sol | hypothetical account shortfall below collateral requirements)/ For each asset the account is in Read the balances and exchange rate from the rToken Calculate effects of interacting with rTokenModify redeem effect sumBorrowPlusEffects += tokensToDenom * redeemTokens borrow effect sumBorrowPlusEffects += oraclePrice * borrowAmount | function getHypotheticalAccountLiquidityInternal(
address account,
RToken rTokenModify,
uint redeemTokens,
uint borrowAmount) internal view returns (Error, uint, uint) {
uint oErr;
RToken[] memory assets = accountAssets[account];
for (uint i = 0; i < assets.length; i++) {
RToken asset = assets[i];
(oErr, vars.rTokenBalance, vars.borrowBalance, vars.exchangeRateMantissa) = asset.getAccountSnapshot(account);
return (Error.SNAPSHOT_ERROR, 0, 0);
}
if (vars.oraclePriceMantissa == 0) {
return (Error.PRICE_ERROR, 0, 0);
}
if (asset == rTokenModify) {
vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt(vars.tokensToDenom, redeemTokens, vars.sumBorrowPlusEffects);
vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt(vars.oraclePrice, borrowAmount, vars.sumBorrowPlusEffects);
}
}
| 7,113,062 | [
1,
76,
879,
10370,
278,
1706,
2236,
3025,
25602,
5712,
4508,
2045,
287,
8433,
13176,
2457,
1517,
3310,
326,
2236,
353,
316,
2720,
326,
324,
26488,
471,
7829,
4993,
628,
326,
436,
1345,
9029,
16605,
434,
16592,
310,
598,
436,
1345,
11047,
283,
24903,
5426,
2142,
38,
15318,
13207,
29013,
1011,
2430,
774,
8517,
362,
225,
283,
24903,
5157,
29759,
5426,
2142,
38,
15318,
13207,
29013,
1011,
20865,
5147,
225,
29759,
6275,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
7628,
879,
10370,
278,
1706,
3032,
48,
18988,
24237,
3061,
12,
203,
3639,
1758,
2236,
16,
203,
3639,
534,
1345,
436,
1345,
11047,
16,
203,
3639,
2254,
283,
24903,
5157,
16,
203,
3639,
2254,
29759,
6275,
13,
2713,
1476,
1135,
261,
668,
16,
2254,
16,
2254,
13,
288,
203,
203,
3639,
2254,
320,
2524,
31,
203,
203,
3639,
534,
1345,
8526,
3778,
7176,
273,
2236,
10726,
63,
4631,
15533,
203,
3639,
364,
261,
11890,
277,
273,
374,
31,
277,
411,
7176,
18,
2469,
31,
277,
27245,
288,
203,
5411,
534,
1345,
3310,
273,
7176,
63,
77,
15533,
203,
203,
5411,
261,
83,
2524,
16,
4153,
18,
86,
1345,
13937,
16,
4153,
18,
70,
15318,
13937,
16,
4153,
18,
16641,
4727,
49,
970,
21269,
13,
273,
3310,
18,
588,
3032,
4568,
12,
4631,
1769,
203,
7734,
327,
261,
668,
18,
13653,
31667,
67,
3589,
16,
374,
16,
374,
1769,
203,
5411,
289,
203,
203,
5411,
309,
261,
4699,
18,
280,
16066,
5147,
49,
970,
21269,
422,
374,
13,
288,
203,
7734,
327,
261,
668,
18,
7698,
1441,
67,
3589,
16,
374,
16,
374,
1769,
203,
5411,
289,
203,
203,
203,
203,
203,
5411,
309,
261,
9406,
422,
436,
1345,
11047,
13,
288,
203,
7734,
4153,
18,
1364,
38,
15318,
13207,
29013,
273,
14064,
67,
13639,
25871,
986,
14342,
12,
4699,
18,
7860,
774,
8517,
362,
16,
283,
24903,
5157,
16,
4153,
18,
1364,
38,
15318,
13207,
29013,
1769,
203,
203,
7734,
4153,
18,
1364,
38,
15318,
13207,
29013,
273,
14064,
67,
13639,
25871,
2
] |
./full_match/1/0xD7EA1B7f45508cEd22aD2C39cd0CaA48CCB0E3D2/sources/contracts/Rmlq.sol | Replace with the UniswapSwap router address
| address private constant UNISWAP_ROUTER_ADDRESS = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; | 3,024,138 | [
1,
5729,
598,
326,
1351,
291,
91,
438,
12521,
4633,
1758,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
1758,
3238,
5381,
5019,
5127,
59,
2203,
67,
1457,
1693,
654,
67,
15140,
273,
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,
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
] |
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.11;
import './Bet.sol';
import "@chainlink/contracts/src/v0.8/KeeperCompatible.sol";
/// @title Bet factory contract.
/// @author Fermin Carranza
/// @notice Basic contract to create bets. Only ETH/USD currently supported.
/// @dev Chainlink Keeper not currently working. Not production ready.
contract BetFactory is KeeperCompatible {
/*
/ Events - Publicize events to external listeners.
*/
event LogBetCreatedFromFactory(string symbol, int line, int spread);
/// Storage variables
address private owner = msg.sender;
Bet[] public bets;
uint public numberOfBets;
mapping(uint256 => Bet) public betsMap;
/// Receive Ether function.
receive() external payable {}
/// @notice Create a new bet for users to participate in. (Only ETH/USD currently supported)
/// @param _symbol Ticker symbol of the security to bet on.
/// @param _line The price at which contract settles at expiration.
/// @param _spread Spread price can move from line.
/// @param _maxBetSize The maximum amount a user can bet (in ETH).
/// @param _multiplier The payout multiplier for winning bets.
/// @param _expiration The expiration date of the bet.
function createBet(string memory _symbol, int _line, int _spread, int _maxBetSize, int _multiplier, uint _expiration) public {
Bet _bet = new Bet(_symbol, _line, _spread, _maxBetSize, _multiplier, _expiration);
bets.push(_bet);
betsMap[numberOfBets] = _bet;
numberOfBets++;
emit LogBetCreatedFromFactory(_symbol, _line, _spread);
}
/// @return Returns all outstanding bets.
function getAllBets() public view returns (Bet[] memory) {
return bets;
}
/// @notice Returns a specific bet's details.
/// @param index The ID of the bet.
/// @return Array containing: symbol, line, spread and expiration of bet.
function getBetDetails(uint index) public view returns (string memory, int, int, uint, address) {
Bet bet = betsMap[index];
return bet.getBetDetails();
}
/// @notice Resolves outstanding bets if current time is greater than expiration.
function resolveExistingBets() public {
uint _betsLength = bets.length;
for (uint8 _i = 0; _i < _betsLength; _i++) {
Bet currentBet = bets[_i];
if (block.timestamp > currentBet.expiration()) {
(bool success, ) = address(currentBet).call(abi.encodeWithSignature("resolveBet()"));
require(success, "It failed to resolve bet.");
removeFromBets(_i);
numberOfBets--;
_betsLength--;
_i--;
}
}
}
/// @notice Resolves a bet by ID
/// @dev Used to resolve a bet and bypass the Chainlink Keeper
function resolveBet(uint index) public {
Bet currentBet = bets[index];
removeFromBets(index);
numberOfBets--;
(bool success, ) = address(currentBet).call(abi.encodeWithSignature("resolveBet()"));
require(success, "It failed to resolve bet.");
}
/// @notice Chainlink function to check if outside data should make it into the contract.
/// @dev Currently not working.
function checkUpkeep(
bytes calldata /*checkData */
) external override view returns (bool upkeepNeeded, bytes memory) {
upkeepNeeded = bets.length > 0;
}
/// @notice Method to run if Chainlink determines the contract needs to perform an action.
function performUpkeep(bytes calldata) external override {
resolveExistingBets();
}
/// @notice Removes old bet from current bets array.
/// @param index The ID of the bet to remove.
/// @dev Utility method to remove old bet from current bets array.
function removeFromBets(uint index) internal {
bets[index] = bets[bets.length - 1];
bets.pop();
}
}
| @notice Resolves a bet by ID @dev Used to resolve a bet and bypass the Chainlink Keeper | function resolveBet(uint index) public {
Bet currentBet = bets[index];
removeFromBets(index);
numberOfBets--;
(bool success, ) = address(currentBet).call(abi.encodeWithSignature("resolveBet()"));
require(success, "It failed to resolve bet.");
}
| 15,863,257 | [
1,
17453,
279,
2701,
635,
1599,
225,
10286,
358,
2245,
279,
2701,
471,
17587,
326,
7824,
1232,
1475,
9868,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
2245,
38,
278,
12,
11890,
770,
13,
1071,
288,
203,
3639,
605,
278,
783,
38,
278,
273,
324,
2413,
63,
1615,
15533,
203,
3639,
22386,
38,
2413,
12,
1615,
1769,
203,
3639,
7922,
38,
2413,
413,
31,
203,
3639,
261,
6430,
2216,
16,
262,
273,
1758,
12,
2972,
38,
278,
2934,
1991,
12,
21457,
18,
3015,
1190,
5374,
2932,
10828,
38,
278,
1435,
7923,
1769,
203,
3639,
2583,
12,
4768,
16,
315,
7193,
2535,
358,
2245,
2701,
1199,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity 0.5.16;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "./InstrumentManagerInterface.sol";
import "./InstrumentInterface.sol";
import "../InstrumentConfig.sol";
import "../escrow/InstrumentEscrowInterface.sol";
import "../escrow/IssuanceEscrowInterface.sol";
import "../escrow/EscrowFactoryInterface.sol";
import "../lib/access/WhitelistAccess.sol";
import "../lib/token/IBurnable.sol";
import "../lib/protobuf/InstrumentData.sol";
import "../lib/protobuf/TokenTransfer.sol";
import "../lib/proxy/AdminOnlyUpgradeabilityProxy.sol";
import "../lib/util/Constants.sol";
/**
* Base instrument manager for instrument v1, v2 and v3.
*/
contract InstrumentManager is InstrumentManagerInterface {
using SafeERC20 for IERC20;
using WhitelistAccess for WhitelistAccess.Whitelist;
/**
* @dev Common property of issuance.
*/
struct IssuanceProperty {
// Address of issuance creator
address makerAddress;
// Address of issuance taker
address takerAddress;
// Amount of NUTS token deposited in creating this issuance
uint256 deposit;
// Address of instrument proxy
address proxyAddress;
// Address of Issuance Escrow
address escrowAddress;
// Whether the issuance is terminated
bool terminated;
}
// Instrument expiration
bool internal _active;
uint256 internal _instrumentTerminationTimestamp;
uint256 internal _instrumentOverrideTimestamp;
// Maker whitelist
WhitelistAccess.Whitelist internal _makerWhitelist;
// Taker whitelist
WhitelistAccess.Whitelist internal _takerWhitelist;
uint256 internal _instrumentId;
address internal _fspAddress;
address internal _brokerAddress;
address internal _instrumentAddress;
uint256 internal _lastIssuanceId;
// Amount of NUTS token deposited in creating this Instrument Manager.
// As instrument deposit might change over time, Instrument Manager should remember the amount
// of NUTS token deposited.
uint256 internal _depositAmount;
InstrumentConfig internal _instrumentConfig;
// Instrument Escrow is singleton per each Instrument Manager.
InstrumentEscrowInterface internal _instrumentEscrow;
// We can derive the list of issuance id as [1, 2, 3, ..., _lastIssuanceId - 1]
// so we don't need a separate array to store the issuance id list.
mapping(uint256 => IssuanceProperty) internal _issuanceProperties;
/**
* @dev The instrument is deactivated.
*/
event InstrumentDeactivated(uint256 indexed instrumentId);
/**
* @dev A new issuance is created.
*/
event IssuanceCreated(
uint256 indexed issuanceId,
address indexed makerAddress,
address issuanceProxyAddress,
address issuanceEscrowAddress
);
/**
* @dev An issuance is terminated.
*/
event IssuanceTerminated(uint256 indexed issuanceId);
/**
* @dev Token is transferred.
*/
event TokenTransferred(
uint256 indexed issuanceId,
Transfer.Type transferType,
address fromAddress,
address toAddress,
address tokenAddress,
uint256 amount,
bytes32 action
);
/**
* @param instrumentId ID of the instrument.
* @param fspAddress Address of FSP that activates this financial instrument.
* @param instrumentAddress Address of the financial instrument contract.
* @param instrumentConfigAddress Address of the Instrument Config contract.
* @param instrumentParameters Custom parameters for the Instrument Manager.
*/
constructor(
uint256 instrumentId,
address fspAddress,
address instrumentAddress,
address instrumentConfigAddress,
bytes memory instrumentParameters
) public {
require(_instrumentAddress == address(0x0), "Already initialized");
require(fspAddress != address(0x0), "FSP not set");
require(instrumentAddress != address(0x0), "Instrument not set");
require(
instrumentConfigAddress != address(0x0),
"Instrument config not set"
);
require(
instrumentParameters.length > 0,
"Instrument parameters not set"
);
InstrumentParameters.Data memory parameters = InstrumentParameters
.decode(instrumentParameters);
// Termination must be set, otherwise the instrument is auto-terminated.
require(
parameters.instrumentTerminationTimestamp != 0,
"Termination not set"
);
// Override can be optional, if not provided the instrument can be deactivated any time.
_active = true;
_instrumentTerminationTimestamp = parameters
.instrumentTerminationTimestamp;
_instrumentOverrideTimestamp = parameters.instrumentOverrideTimestamp;
_makerWhitelist.enabled = parameters.supportMakerWhitelist;
_takerWhitelist.enabled = parameters.supportTakerWhitelist;
_instrumentConfig = InstrumentConfig(instrumentConfigAddress);
_instrumentId = instrumentId;
_fspAddress = fspAddress;
// If broker address is not provided, default to fsp address.
_brokerAddress = parameters.brokerAddress == address(0x0)
? fspAddress
: parameters.brokerAddress;
_instrumentAddress = instrumentAddress;
// Deposit amount for Instrument activation might change. Need to record the amount deposited.
_depositAmount = _instrumentConfig.instrumentDeposit();
// Create Instrument Escrow
_instrumentEscrow = EscrowFactoryInterface(
_instrumentConfig.escrowFactoryAddress()
)
.createInstrumentEscrow();
}
/**
* @dev Get the Instrument Escrow.
*/
function getInstrumentEscrowAddress() public view returns (address) {
return address(_instrumentEscrow);
}
/**
* @dev Get the ID of the last created issuance.
*/
function getLastIssuanceId() public view returns (uint256) {
return _lastIssuanceId;
}
/**
* @dev Deactivates the instrument.
*/
function deactivate() public {
require(_active, "Instrument deactivated");
require(
(now >= _instrumentOverrideTimestamp &&
msg.sender == _fspAddress) ||
now >= _instrumentTerminationTimestamp,
"Cannot deactivate"
);
// Return the deposited NUTS token
if (_depositAmount > 0) {
// Burn NUTS token from Deposit Escrow
IBurnable(_instrumentConfig.depositTokenAddress()).burn(
_depositAmount
);
}
_active = false;
emit InstrumentDeactivated(_instrumentId);
}
/**
* @dev Updates the maker whitelist. The maker whitelist only affects new issuances.
* @param makerAddress The maker address to update in whitelist
* @param allowed Whether this maker is allowed to create new issuance.
*/
function setMakerWhitelist(address makerAddress, bool allowed) public {
require(msg.sender == _fspAddress, "Only FSP can whitelist");
_makerWhitelist.setAllowed(makerAddress, allowed);
}
/**
* @dev Updates the taker whitelist. The taker whitelist only affects new engagement.
* @param takerAddress The taker address to update in whitelist
* @param allowed Whether this taker is allowed to engage issuance.
*/
function setTakerWhitelist(address takerAddress, bool allowed) public {
require(msg.sender == _fspAddress, "Only FSP can whitelist");
_takerWhitelist.setAllowed(takerAddress, allowed);
}
/**
* @dev Create a new issuance of the financial instrument
* @param makerParameters The custom parameters to the newly created issuance
* @return The id of the newly created issuance.
*/
function createIssuance(bytes memory makerParameters)
public
returns (uint256)
{
// Makers can create new issuance if:
// 1. The instrument is active, i.e. is not deactivated by FSP,
// 2. And the instrument has not reached its termination timestamp.
require(
_active && (now <= _instrumentTerminationTimestamp),
"Instrument deactivated"
);
// Maker is allowed if:
// 1. Maker whitelist is not enabled;
// 2. Or maker whitelist is enabled, and this maker is allowed.
require(_makerWhitelist.isAllowed(msg.sender), "Maker not allowed");
// Deposit NUTS token
if (_instrumentConfig.issuanceDeposit() > 0) {
// Transfers NUTS token from Instrument Escrow to Instrument Manager.
_instrumentEscrow.withdrawTokenByAdmin(
msg.sender,
_instrumentConfig.depositTokenAddress(),
_instrumentConfig.issuanceDeposit()
);
}
// Get issuance Id
_lastIssuanceId++;
// Create Issuance Escrow.
IssuanceEscrowInterface issuanceEscrow = EscrowFactoryInterface(
_instrumentConfig.escrowFactoryAddress()
)
.createIssuanceEscrow();
// Create an AdminOnlyUpgradeabilityProxy for the new issuance
// Current Instrument Manager is the proxy admin for this proxy, and only the current
// Instrument Manager can call fallback on the proxy.
AdminOnlyUpgradeabilityProxy issuanceProxy = new AdminOnlyUpgradeabilityProxy(
_instrumentAddress,
address(this)
);
// Create Issuance Property
_issuanceProperties[_lastIssuanceId] = IssuanceProperty({
makerAddress: msg.sender,
takerAddress: address(0x0),
deposit: _instrumentConfig.issuanceDeposit(),
escrowAddress: address(issuanceEscrow),
proxyAddress: address(issuanceProxy),
terminated: false
});
// Invoke Instrument
InstrumentInterface instrument = InstrumentInterface(
address(issuanceProxy)
);
instrument.initialize(
_lastIssuanceId,
_fspAddress,
_brokerAddress,
address(_instrumentEscrow),
address(issuanceEscrow),
_instrumentConfig.priceOracleAddress()
);
bytes memory transfersData = instrument.createIssuance(
msg.sender,
makerParameters
);
_postProcessing(
_lastIssuanceId,
instrument.isTerminated(),
transfersData
);
emit IssuanceCreated(
_lastIssuanceId,
msg.sender,
address(issuanceProxy),
address(issuanceEscrow)
);
}
/**
* @dev A taker engages to the issuance
* @param issuanceId The id of the issuance
* @param takerParameters The custom parameters to the new engagement
*/
function engageIssuance(uint256 issuanceId, bytes memory takerParameters)
public
{
// Taker is allowed if:
// 1. Taker whitelist is not enabled;
// 2. Or taker whitelist is enabled, and this taker is allowed.
require(_takerWhitelist.isAllowed(msg.sender), "Taker not allowed");
IssuanceProperty storage issuanceProperty = _issuanceProperties[issuanceId];
require(!issuanceProperty.terminated, "Issuance terminated");
require(
issuanceProperty.makerAddress != address(0x0),
"Issuance not exist"
);
issuanceProperty.takerAddress = msg.sender;
// Invoke Instrument
InstrumentInterface instrument = InstrumentInterface(
issuanceProperty.proxyAddress
);
bytes memory transfersData = instrument.engageIssuance(
msg.sender,
takerParameters
);
_postProcessing(issuanceId, instrument.isTerminated(), transfersData);
}
/**
* @dev The caller deposits token from Instrument Escrow into issuance.
* @param issuanceId The id of the issuance
* @param tokenAddress The address of the token. The address for ETH is Contants.getEthAddress().
* @param amount The amount of ERC20 token transfered
*/
function depositToIssuance(
uint256 issuanceId,
address tokenAddress,
uint256 amount
) public {
IssuanceProperty storage issuanceProperty = _issuanceProperties[issuanceId];
require(amount > 0, "Amount not set");
require(
issuanceProperty.makerAddress != address(0x0),
"Issuance not exist"
);
require(!issuanceProperty.terminated, "Issuance terminated");
Transfer.Data memory transfer = Transfer.Data({
transferType: Transfer.Type.Inbound,
fromAddress: msg.sender,
toAddress: msg.sender,
tokenAddress: tokenAddress,
amount: amount,
action: 'Deposit to Issuance'
});
_processTransfer(issuanceId, transfer);
// Invoke Instrument
InstrumentInterface instrument = InstrumentInterface(
issuanceProperty.proxyAddress
);
bytes memory transfersData = instrument.processTokenDeposit(
msg.sender,
tokenAddress,
amount
);
_postProcessing(issuanceId, instrument.isTerminated(), transfersData);
}
/**
* @dev The caller withdraws tokens from Issuance Escrow to Instrument Escrow.
* @param issuanceId The id of the issuance
* @param tokenAddress The address of the token. The address for ETH is Contants.getEthAddress().
* @param amount The amount of ERC20 token transfered
*/
function withdrawFromIssuance(
uint256 issuanceId,
address tokenAddress,
uint256 amount
) public {
IssuanceProperty storage issuanceProperty = _issuanceProperties[issuanceId];
require(amount > 0, "Amount not set");
require(
issuanceProperty.makerAddress != address(0x0),
"Issuance not exist"
);
require(!issuanceProperty.terminated, "Issuance terminated");
Transfer.Data memory transfer = Transfer.Data({
transferType: Transfer.Type.Outbound,
fromAddress: msg.sender,
toAddress: msg.sender,
tokenAddress: tokenAddress,
amount: amount,
action: "Withdraw from Issuance"
});
_processTransfer(issuanceId, transfer);
// Invoke Instrument
InstrumentInterface instrument = InstrumentInterface(
issuanceProperty.proxyAddress
);
bytes memory transfersData = instrument.processTokenWithdraw(
msg.sender,
tokenAddress,
amount
);
_postProcessing(issuanceId, instrument.isTerminated(), transfersData);
}
/**
* @dev Notify custom events to issuance. This could be invoked by any caller.
* @param issuanceId The id of the issuance
* @param eventName Name of the custom event
* @param eventPayload Payload of the custom event
*/
function notifyCustomEvent(
uint256 issuanceId,
bytes32 eventName,
bytes memory eventPayload
) public {
IssuanceProperty storage issuanceProperty = _issuanceProperties[issuanceId];
require(
issuanceProperty.makerAddress != address(0x0),
"Issuance not exist"
);
require(!issuanceProperty.terminated, "Issuance terminated");
// Invoke Instrument
InstrumentInterface instrument = InstrumentInterface(
issuanceProperty.proxyAddress
);
bytes memory transfersData = instrument.processCustomEvent(
msg.sender,
eventName,
eventPayload
);
_postProcessing(issuanceId, instrument.isTerminated(), transfersData);
}
/**
* @dev Get custom datas from issuance. This could be invoked by any caller.
* @param issuanceId The id of the issuance
* @param dataName Name of the custom data
*/
function getCustomData(uint256 issuanceId, bytes32 dataName)
public
view
returns (bytes memory)
{
IssuanceProperty storage issuanceProperty = _issuanceProperties[issuanceId];
require(
issuanceProperty.makerAddress != address(0x0),
"Issuance not exist"
);
// Invoke Instrument
InstrumentInterface instrument = InstrumentInterface(
issuanceProperty.proxyAddress
);
return instrument.getCustomData(msg.sender, dataName);
}
/**
* @dev Determines whether the target address can take part in a transfer action.
* For one issuance, only the issuance maker, issuance taker and instrument broker can
* deposit to or withdraw from the issuance.
*/
function _isTransferAllowed(uint256 issuanceId, address account)
internal
view
returns (bool)
{
IssuanceProperty storage property = _issuanceProperties[issuanceId];
return
property.makerAddress == account ||
property.takerAddress == account ||
_brokerAddress == account ||
Constants.getCustodianAddress() == account;
}
/**
* @dev Process updated state and transfers after instrument invocation.
*/
function _postProcessing(
uint256 issuanceId,
bool terminated,
bytes memory transfersData
) internal {
IssuanceProperty storage property = _issuanceProperties[issuanceId];
if (!property.terminated && terminated) {
property.terminated = true;
emit IssuanceTerminated(issuanceId);
if (property.deposit > 0) {
// Burns NUTS token
IBurnable(_instrumentConfig.depositTokenAddress()).burn(
property.deposit
);
}
}
// Processes transfers.
Transfers.Data memory transfers = Transfers.decode(transfersData);
for (uint256 i = 0; i < transfers.actions.length; i++) {
_processTransfer(issuanceId, transfers.actions[i]);
}
}
/**
* @dev Process a single token transfer action.
*/
function _processTransfer(uint256 issuanceId, Transfer.Data memory transfer)
private
{
// The transfer can only come from issuance maker, issuance taker and instrument broker.
require(
_isTransferAllowed(issuanceId, transfer.fromAddress) &&
_isTransferAllowed(issuanceId, transfer.toAddress),
"Transfer not allowed"
);
emit TokenTransferred(
issuanceId,
transfer.transferType,
transfer.fromAddress,
transfer.toAddress,
transfer.tokenAddress,
transfer.amount,
transfer.action
);
IssuanceProperty storage property = _issuanceProperties[issuanceId];
IssuanceEscrowInterface issuanceEscrow = IssuanceEscrowInterface(
property.escrowAddress
);
// Check whether it's outbound, inbound, or transfer within the escrow.
if (transfer.transferType == Transfer.Type.Outbound) {
// IMPORTANT: transfer.toAddress is not valid in outbound transfer.
if (transfer.tokenAddress == Constants.getEthAddress()) {
// First withdraw ETH from Issuance Escrow to owner
issuanceEscrow.withdrawByAdmin(
transfer.fromAddress,
transfer.amount
);
// Then deposit the ETH from owner to Instrument Escrow
_instrumentEscrow.depositByAdmin.value(transfer.amount)(
transfer.fromAddress
);
} else {
// First withdraw ERC20 token from Issuance Escrow to owner
issuanceEscrow.withdrawTokenByAdmin(
transfer.fromAddress,
transfer.tokenAddress,
transfer.amount
);
// (Important!!!)Then set allowance for Instrument Escrow
IERC20(transfer.tokenAddress).safeApprove(
address(_instrumentEscrow),
transfer.amount
);
// Then deposit the ERC20 token from owner to Instrument Escrow
_instrumentEscrow.depositTokenByAdmin(
transfer.fromAddress,
transfer.tokenAddress,
transfer.amount
);
}
} else if (transfer.transferType == Transfer.Type.Inbound) {
// IMPORTANT: transfer.toAddress is not valid in inbound transfer.
if (transfer.tokenAddress == Constants.getEthAddress()) {
// First withdraw ETH from Instrument Escrow
_instrumentEscrow.withdrawByAdmin(
transfer.fromAddress,
transfer.amount
);
// Then deposit ETH to Issuance Escrow
issuanceEscrow.depositByAdmin.value(transfer.amount)(
transfer.fromAddress
);
} else {
// Withdraw ERC20 token from Instrument Escrow
_instrumentEscrow.withdrawTokenByAdmin(
transfer.fromAddress,
transfer.tokenAddress,
transfer.amount
);
// IMPORTANT: Set allowance before deposit
IERC20(transfer.tokenAddress).safeApprove(
property.escrowAddress,
transfer.amount
);
// Deposit ERC20 token to Issuance Escrow
issuanceEscrow.depositTokenByAdmin(
transfer.fromAddress,
transfer.tokenAddress,
transfer.amount
);
}
} else {
// It's a transfer inside the issuance escrow
issuanceEscrow.transferToken(
transfer.fromAddress,
transfer.toAddress,
transfer.tokenAddress,
transfer.amount
);
}
}
function() external payable {}
}
| * @dev Updates the maker whitelist. The maker whitelist only affects new issuances. @param makerAddress The maker address to update in whitelist @param allowed Whether this maker is allowed to create new issuance./ | function setMakerWhitelist(address makerAddress, bool allowed) public {
require(msg.sender == _fspAddress, "Only FSP can whitelist");
_makerWhitelist.setAllowed(makerAddress, allowed);
}
| 12,990,542 | [
1,
5121,
326,
312,
6388,
10734,
18,
1021,
312,
6388,
10734,
1338,
30058,
394,
3385,
89,
6872,
18,
225,
312,
6388,
1887,
1021,
312,
6388,
1758,
358,
1089,
316,
10734,
225,
2935,
17403,
333,
312,
6388,
353,
2935,
358,
752,
394,
3385,
89,
1359,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
444,
12373,
18927,
12,
2867,
312,
6388,
1887,
16,
1426,
2935,
13,
1071,
288,
203,
3639,
2583,
12,
3576,
18,
15330,
422,
389,
10749,
1887,
16,
315,
3386,
478,
3118,
848,
10734,
8863,
203,
3639,
389,
29261,
18927,
18,
542,
5042,
12,
29261,
1887,
16,
2935,
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
] |
/**
*Submitted for verification at Etherscan.io on 2021-10-27
*/
// File: contracts/common/Initializable.sol
pragma solidity ^0.8.0;
contract Initializable {
bool inited = false;
modifier initializer() {
require(!inited, "already inited");
_;
inited = true;
}
}
// File: contracts/common/EIP712Base.sol
pragma solidity ^0.8.0;
contract EIP712Base is Initializable {
struct EIP712Domain {
string name;
string version;
address verifyingContract;
bytes32 salt;
}
string constant public ERC712_VERSION = "1";
bytes32 internal constant EIP712_DOMAIN_TYPEHASH = keccak256(
bytes(
"EIP712Domain(string name,string version,address verifyingContract,bytes32 salt)"
)
);
bytes32 internal domainSeperator;
// supposed to be called once while initializing.
// one of the contracts that inherits this contract follows proxy pattern
// so it is not possible to do this in a constructor
function _initializeEIP712(
string memory name
)
internal
initializer
{
_setDomainSeperator(name);
}
function _setDomainSeperator(string memory name) internal {
domainSeperator = keccak256(
abi.encode(
EIP712_DOMAIN_TYPEHASH,
keccak256(bytes(name)),
keccak256(bytes(ERC712_VERSION)),
address(this),
bytes32(getChainId())
)
);
}
function getDomainSeperator() public view returns (bytes32) {
return domainSeperator;
}
function getChainId() public view returns (uint256) {
uint256 id;
assembly {
id := chainid()
}
return id;
}
/**
* Accept message hash and returns hash message in EIP712 compatible form
* So that it can be used to recover signer from signature signed using EIP712 formatted data
* https://eips.ethereum.org/EIPS/eip-712
* "\\x19" makes the encoding deterministic
* "\\x01" is the version byte to make it compatible to EIP-191
*/
function toTypedMessageHash(bytes32 messageHash)
internal
view
returns (bytes32)
{
return
keccak256(
abi.encodePacked("\x19\x01", getDomainSeperator(), messageHash)
);
}
}
// File: contracts/common/ContextMixin.sol
pragma solidity ^0.8.0;
abstract contract ContextMixin {
function msgSender()
internal
view
returns (address payable sender)
{
if (msg.sender == address(this)) {
bytes memory array = msg.data;
uint256 index = msg.data.length;
assembly {
// Load the 32 bytes word from memory with the address on the lower 20 bytes, and mask those.
sender := and(
mload(add(array, index)),
0xffffffffffffffffffffffffffffffffffffffff
)
}
} else {
sender = payable(msg.sender);
}
return sender;
}
}
// File: @openzeppelin/contracts/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 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. 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/common/NativeMetaTransaction.sol
pragma solidity ^0.8.0;
contract NativeMetaTransaction is EIP712Base {
using SafeMath for uint256;
bytes32 private constant META_TRANSACTION_TYPEHASH = keccak256(
bytes(
"MetaTransaction(uint256 nonce,address from,bytes functionSignature)"
)
);
event MetaTransactionExecuted(
address userAddress,
address payable relayerAddress,
bytes functionSignature
);
mapping(address => uint256) nonces;
/*
* Meta transaction structure.
* No point of including value field here as if user is doing value transfer then he has the funds to pay for gas
* He should call the desired function directly in that case.
*/
struct MetaTransaction {
uint256 nonce;
address from;
bytes functionSignature;
}
function executeMetaTransaction(
address userAddress,
bytes memory functionSignature,
bytes32 sigR,
bytes32 sigS,
uint8 sigV
) public payable returns (bytes memory) {
MetaTransaction memory metaTx = MetaTransaction({
nonce: nonces[userAddress],
from: userAddress,
functionSignature: functionSignature
});
require(
verify(userAddress, metaTx, sigR, sigS, sigV),
"Signer and signature do not match"
);
// increase nonce for user (to avoid re-use)
nonces[userAddress] = nonces[userAddress].add(1);
emit MetaTransactionExecuted(
userAddress,
payable(msg.sender),
functionSignature
);
// Append userAddress and relayer address at the end to extract it from calling context
(bool success, bytes memory returnData) = address(this).call(
abi.encodePacked(functionSignature, userAddress)
);
require(success, "Function call not successful");
return returnData;
}
function hashMetaTransaction(MetaTransaction memory metaTx)
internal
pure
returns (bytes32)
{
return
keccak256(
abi.encode(
META_TRANSACTION_TYPEHASH,
metaTx.nonce,
metaTx.from,
keccak256(metaTx.functionSignature)
)
);
}
function getNonce(address user) public view returns (uint256 nonce) {
nonce = nonces[user];
}
function verify(
address signer,
MetaTransaction memory metaTx,
bytes32 sigR,
bytes32 sigS,
uint8 sigV
) internal view returns (bool) {
require(signer != address(0), "NativeMetaTransaction: INVALID_SIGNER");
return
signer ==
ecrecover(
toTypedMessageHash(hashMetaTransaction(metaTx)),
sigV,
sigR,
sigS
);
}
}
// 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;
}
}
// 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: contracts/ERC721Tradable.sol
pragma solidity ^0.8.0;
contract OwnableDelegateProxy {}
contract ProxyRegistry {
mapping(address => OwnableDelegateProxy) public proxies;
}
/**
* @title ERC721Tradable
* ERC721Tradable - ERC721 contract that whitelists a trading address, and has minting functionality.
*/
abstract contract ERC721Tradable is ContextMixin, ERC721Enumerable, NativeMetaTransaction, Ownable {
using SafeMath for uint256;
address proxyRegistryAddress;
uint256 private _currentTokenId = 0;
constructor(
string memory _name,
string memory _symbol,
address _proxyRegistryAddress
) ERC721(_name, _symbol) {
proxyRegistryAddress = _proxyRegistryAddress;
_initializeEIP712(_name);
}
/**
* Override isApprovedForAll to whitelist user's OpenSea proxy accounts to enable gas-less listings.
*/
function isApprovedForAll(address owner, address operator)
override
public
view
returns (bool)
{
// Whitelist OpenSea proxy contract for easy trading.
ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress);
if (address(proxyRegistry.proxies(owner)) == operator) {
return true;
}
return super.isApprovedForAll(owner, operator);
}
/**
* This is used instead of msg.sender as transactions won't be sent by the original token owner, but by OpenSea.
*/
function _msgSender()
internal
override
view
returns (address sender)
{
return ContextMixin.msgSender();
}
}
// File: contracts/BitKoi.sol
pragma solidity ^0.8.0;
/**
* @title BitKoi
* BitKoi - a blockchain game at scale
*/
/// @title mix up two fish and find out which traits they should have
abstract contract BitKoiTraitInterface {
/// @dev simply a boolean to indicate this is the contract we expect to be
function isBitKoiTraits() virtual public pure returns (bool);
///mix up the "genes" of the fish to see which genes our new fish will have
function smooshFish(uint256 genes1, uint256 genes2, uint256 targetBlock) virtual public returns (uint256);
}
/// @title A facet of BitKoiCore that manages special access privileges.
/// Based on work from Axiom Zen (https://www.axiomzen.co)
contract BitKoiAccessControl {
// 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.
bool public paused = false;
modifier onlyCEO() {
require(msg.sender == ceoAddress);
_;
}
modifier onlyCFO() {
require(msg.sender == cfoAddress);
_;
}
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 payable _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() virtual public onlyCEO whenPaused {
// can't unpause if contract was upgraded
paused = false;
}
}
/// @title Base contract for KoiPond. Holds all common structs, events and base variables.
/// based on code written for CK by Axiom Zen (https://www.axiomzen.co)
abstract contract BitKoiBase is BitKoiAccessControl, ERC721Tradable {
/*** EVENTS ***/
/// @dev The Spawn event is fired whenever a new fish comes into existence. This obviously
/// includes any time a fish is created through the spawnFish method, but it is also called
/// when a new gen0 fish is created.
event Spawn(address owner, uint256 koiFishId, uint256 parent1Id, uint256 parent2Id, uint256 genes, uint16 generation, uint64 timestamp);
event BreedingSuccessful(address owner, uint256 newFishId, uint256 parent1Id, uint256 parent2Id, uint64 cooldownEndBlock);
/*** DATA TYPES ***/
struct BitKoi {
// The fish's genetic code - this will never change for any fish.
uint256 genes;
// The timestamp from the block when this fish came into existence.
uint64 spawnTime;
// The minimum timestamp after which this fish can engage in spawning
// activities again.
uint64 cooldownEndBlock;
// The ID of the parents of this fish, set to 0 for gen0 fish.
// With uint32 there's a limit of 4 billion fish
uint32 parent1Id;
uint32 parent2Id;
// Set to the index in the cooldown array (see below) that represents
// the current cooldown duration for this fish. This starts at zero
// for gen0 fish, and is initialized to floor(generation/2) for others.
// Incremented by one for each successful breeding action.
uint16 cooldownIndex;
// The "generation number" of this fish. Fish minted by the KP contract
// for sale are called "gen0" and have a generation number of 0. The
// generation number of all other fish is the larger of the two generation
// numbers of their parents, plus one.
uint16 generation;
}
/*** CONSTANTS ***/
/// @dev A lookup table indicating the cooldown duration after any successful
/// breeding action, called "cooldown" Designed such that the cooldown roughly
/// doubles each time a fish is bred, encouraging owners not to just keep breeding the same fish over
/// and over again. Caps out at one week (a fish 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(1 days),
uint32(2 days),
uint32(4 days),
uint32(7 days)
];
// An approximation of currently how many seconds are in between blocks.
uint256 public secondsPerBlock = 15;
/*** STORAGE ***/
/// @dev An array containing the KoiFish struct for all KoiFish in existence. The ID
/// of each fish is actually an index into this array. Fish 0 has an invalid genetic
/// code and can't be used to produce offspring.
BitKoi[] bitKoi;
/// @dev A mapping from fish IDs to the address that owns them. All fish have
/// some valid owner address, even gen0 fish are created with a non-zero owner.
mapping (uint256 => address) bitKoiIndexToOwner;
// @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 KoiFishIDs to an address that has been approved to call
/// transferFrom(). Each KoiFish can only have one approved address for transfer
/// at any time. A zero value means no approval is outstanding.
mapping (uint256 => address) bitKoiIndexToApproved;
// /// @dev Assigns ownership of a specific KoiFish to an address.
function _transfer(address _from, address _to, uint256 _tokenId) override internal {
require(ownerOf(_tokenId) == _from, "ERC721: transfer of token that is not own");
require(_to != address(0), "ERC721: transfer to the zero address");
// Since the number of fish is capped to 2^32 we can't overflow this
ownershipTokenCount[_to]++;
ownershipTokenCount[_from]--;
_beforeTokenTransfer(_from, _to, _tokenId);
// actually transfer ownership
bitKoiIndexToOwner[_tokenId] = _to;
// Clear approvals from the previous owner
_approve(address(0), _tokenId);
emit Transfer(_from, _to, _tokenId);
}
/// @notice Returns the address currently assigned ownership of a given BitKoi.
/// @dev Required for ERC-721 compliance.
function ownerOf(uint256 _tokenId)
override
public
view
returns (address owner)
{
owner = bitKoiIndexToOwner[_tokenId];
require(owner != address(0));
}
function balanceOf(address owner) public view override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return ownershipTokenCount[owner];
}
/// @notice Returns a list of all KoiFish IDs assigned to an address.
/// @param _owner The owner whose KoiFish we are interested in.
/// @dev This method MUST NEVER be called by smart contract code. First, it's fairly
/// expensive (it walks the entire KoiFish array looking for fish 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[] memory ownerTokens) {
uint256 tokenCount = balanceOf(_owner);
if (tokenCount == 0) {
// Return an empty array
return new uint256[](0);
} else {
uint256[] memory result = new uint256[](tokenCount);
uint256 totalBitKoi = totalSupply();
uint256 resultIndex = 0;
// We count on the fact that all fish have IDs starting at 1 and increasing
// sequentially up to the totalKoi count.
uint256 bitKoiId;
for (bitKoiId = 1; bitKoiId <= totalBitKoi; bitKoiId++) {
if (bitKoiIndexToOwner[bitKoiId] == _owner) {
result[resultIndex] = bitKoiId;
resultIndex++;
}
}
return result;
}
}
function _mintNewKoi(address _to, uint256 _tokenId) internal {
_mint(_to, _tokenId);
// Since the number of fish is capped to 2^32 we can't overflow this
ownershipTokenCount[_to]++;
// transfer ownership
bitKoiIndexToOwner[_tokenId] = _to;
}
// 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;
}
}
abstract contract BitKoiOwnership is BitKoiBase {
/// @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 (ownerOf(_tokenId) == _claimant);
}
/// @dev Checks if a given address currently has transferApproval for a particular KoiFish.
/// @param _claimant the address we are confirming fish is approved for.
/// @param _tokenId fish id, only valid when > 0
function _approvedFor(
address _claimant,
uint256 _tokenId
)
internal
view
returns (bool) {
return bitKoiIndexToApproved[_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 KoiFish on sale, and
/// there is no value in spamming the log with Approval events in that case.
function _approve(
uint256 _tokenId,
address _approved
)
internal {
bitKoiIndexToApproved[_tokenId] = _approved;
}
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 fish (except very briefly
// after a gen0 fish is created and before it goes on sale).
require(_to != address(this));
// Disallow transfers to the sale contracts to prevent accidental
// misuse. Sale contracts should only take ownership of fish
// through the allow + transferFrom flow.
// You can only send your own fish
require(_owns(msg.sender, _tokenId));
// Reassign ownership, clear pending approvals, emit Transfer event.
_transfer(msg.sender, _to, _tokenId);
}
}
abstract contract BitKoiBreeding is BitKoiOwnership {
event Hatch(address owner, uint256 fishId, uint256 genes);
uint256 public breedFee = 0 wei;
uint256 public hatchFee = 0 wei;
/// @dev The address of the sibling contract that is used to implement the genetic combination algorithm.
BitKoiTraitInterface public bitKoiTraits;
/// @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 setBitKoiTraitAddress(address _address) external onlyCEO {
BitKoiTraitInterface candidateContract = BitKoiTraitInterface(_address);
// NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117
require(candidateContract.isBitKoiTraits());
// Set the new contract address
bitKoiTraits = candidateContract;
}
/// @dev Checks to see if a given fish is ready to hatch after the gestation period has passed.
function _isReadyToHatch(uint256 _fishId) private view returns (bool) {
BitKoi storage fishToHatch = bitKoi[_fishId];
return fishToHatch.cooldownEndBlock <= uint64(block.number);
}
/// @dev Checks that a given fish is able to breed. Requires that the
/// current cooldown is finished
function _isReadyToBreed(BitKoi storage _fish) internal view returns (bool) {
// In addition to checking the cooldownEndBlock, we also need to check to see if
// the fish has a pending birth; there can be some period of time between the end
// of the pregnacy timer and the spawn event.
return _fish.cooldownEndBlock <= uint64(block.number);
}
/// @dev Set the cooldownEndTime for the given fish based on its current cooldownIndex.
/// Also increments the cooldownIndex (unless it has hit the cap).
/// @param _koiFish A reference to the KoiFish in storage which needs its timer started.
function _triggerCooldown(BitKoi storage _koiFish) internal {
// Compute an estimation of the cooldown time in blocks (based on current cooldownIndex).
_koiFish.cooldownEndBlock = uint64((cooldowns[_koiFish.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 (_koiFish.cooldownIndex < 13) {
_koiFish.cooldownIndex += 1;
}
}
// @dev Updates the minimum payment required for calling breedWith(). Can only
/// be called by the COO address. (This fee is used to offset the gas cost incurred
/// by the autobirth daemon).
function setBreedFee(uint256 val) external onlyCEO {
breedFee = val;
}
// @dev Updates the minimum payment required for calling hatchFish(). Can only
/// be called by the COO address. (This fee is used to offset the gas cost incurred
/// by the autobirth daemon).
function setHatchFee(uint256 val) external onlyCEO {
hatchFee = val;
}
/// @notice Checks that a given fish is able to hatch (i.e. it is not
/// in the middle of a cooldown).
/// @param _koiId reference the id of the fish, any user can inquire about it
function isReadyToHatch(uint256 _koiId)
public
view
returns (bool)
{
require(_koiId > 0);
return _isReadyToHatch(_koiId);
}
/// @notice Checks that a given fish is able to breed (i.e. it is not
/// in the middle of a cooldown).
/// @param _koiId reference the id of the fish, any user can inquire about it
function isReadyToBreed(uint256 _koiId)
public
view
returns (bool)
{
require(_koiId > 0);
BitKoi storage fish = bitKoi[_koiId];
return _isReadyToBreed(fish);
}
/// @dev Internal check to see if a the parents are a valid mating pair. DOES NOT
/// check ownership permissions (that is up to the caller).
/// @param _parent1 A reference to the Fish struct of the potential first parent
/// @param _parent1Id The first parent's ID.
/// @param _parent2 A reference to the Fish struct of the potential second parent
/// @param _parent2Id The second parent's ID.
function _isValidMatingPair(
BitKoi storage _parent1,
uint256 _parent1Id,
BitKoi storage _parent2,
uint256 _parent2Id
)
private
view
returns(bool)
{
// A Fish can't breed with itself!
if (_parent1Id == _parent2Id) {
return false;
}
//the fish have to have genes
if (_parent1.genes == 0 || _parent2.genes == 0) {
return false;
}
// Fish can't breed with their parents.
if (_parent1.parent1Id == _parent2Id || _parent1.parent2Id == _parent2Id) {
return false;
}
if (_parent2.parent1Id == _parent1Id || _parent2.parent2Id == _parent1Id) {
return false;
}
// OK the tx if either fish is gen zero (no parent found).
if (_parent2.parent1Id == 0 || _parent1.parent1Id == 0) {
return true;
}
// Fish can't breed with full or half siblings.
if (_parent2.parent1Id == _parent1.parent1Id || _parent2.parent1Id == _parent1.parent2Id) {
return false;
}
if (_parent2.parent2Id == _parent1.parent1Id || _parent2.parent2Id == _parent1.parent2Id) {
return false;
}
// gtg
return true;
}
/// @notice Checks to see if two BitKoi can breed together, including checks for
/// ownership. Doesn't check that both BitKoi are ready for
/// breeding (i.e. breedWith could still fail until the cooldowns are finished).
/// @param _parent1Id The ID of the proposed first parent.
/// @param _parent2Id The ID of the proposed second parent.
function canBreedWith(uint256 _parent1Id, uint256 _parent2Id)
external
view
returns(bool)
{
require(_parent1Id > 0);
require(_parent2Id > 0);
BitKoi storage parent1 = bitKoi[_parent1Id];
BitKoi storage parent2 = bitKoi[_parent2Id];
return _isValidMatingPair(parent1, _parent1Id, parent2, _parent2Id);
}
/// @dev Internal utility function to initiate breeding, assumes that all breeding
/// requirements have been checked.
function _breedWith(uint256 _parent1Id, uint256 _parent2Id) internal returns(uint256) {
// Grab a reference to the Koi from storage.
BitKoi storage parent1 = bitKoi[_parent1Id];
BitKoi storage parent2 = bitKoi[_parent2Id];
// Determine the higher generation number of the two parents
uint16 parentGen = parent1.generation;
if (parent2.generation > parent1.generation) {
parentGen = parent2.generation;
}
uint256 bitKoiCoProceeds = msg.value;
//transfer the breed fee less the pond cut to the CFO contract
payable(address(cfoAddress)).transfer(bitKoiCoProceeds);
// Make the new fish!
address owner = bitKoiIndexToOwner[_parent1Id];
uint256 newFishId = _createBitKoi(_parent1Id, _parent2Id, parentGen + 1, 0, owner);
// Trigger the cooldown for both parents.
_triggerCooldown(parent1);
_triggerCooldown(parent2);
// Emit the breeding event.
emit BreedingSuccessful(bitKoiIndexToOwner[_parent1Id], newFishId, _parent1Id, _parent2Id, parent1.cooldownEndBlock);
return newFishId;
}
function breedWith(uint256 _parent1Id, uint256 _parent2Id)
external
payable
whenNotPaused
{
// Checks for payment.
require(msg.value >= breedFee);
///check to see if the caller owns both fish
require(_owns(msg.sender, _parent1Id));
require(_owns(msg.sender, _parent2Id));
// Grab a reference to the first parent
BitKoi storage parent1 = bitKoi[_parent1Id];
// Make sure enough time has passed since the last time this fish was bred
require(_isReadyToBreed(parent1));
// Grab a reference to the second parent
BitKoi storage parent2 = bitKoi[_parent2Id];
// Make sure enough time has passed since the last time this fish was bred
require(_isReadyToBreed(parent2));
// Test that these fish are a valid mating pair.
require(_isValidMatingPair(
parent1,
_parent1Id,
parent2,
_parent2Id
));
// All checks passed, make a new fish!!
_breedWith(_parent1Id, _parent2Id);
}
/// @dev An internal method that creates a new fish 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 _parent1Id The fish ID of the first parent (zero for gen0)
/// @param _parent2Id The fish ID of the second parent (zero for gen0)
/// @param _generation The generation number of this fish, must be computed by caller.
/// @param _genes The fish's genetic code.
/// @param _owner The inital owner of this fish, must be non-zero (except for fish ID 0)
function _createBitKoi(
uint256 _parent1Id,
uint256 _parent2Id,
uint256 _generation,
uint256 _genes,
address _owner
)
internal
returns (uint)
{
// These requires are not strictly necessary, our calling code should make
// sure that these conditions are never broken. However! _createKoiFish() 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(_parent1Id == uint256(uint32(_parent1Id)));
require(_parent2Id == uint256(uint32(_parent2Id)));
require(_generation == uint256(uint16(_generation)));
// New fish starts with the same cooldown as parent gen/2
uint16 cooldownIndex = uint16(_generation / 2);
if (cooldownIndex > 13) {
cooldownIndex = 13;
}
BitKoi memory _bitKoi = BitKoi({
genes: _genes,
spawnTime: uint64(block.timestamp),
cooldownEndBlock: 0,
parent1Id: uint32(_parent1Id),
parent2Id: uint32(_parent2Id),
cooldownIndex: cooldownIndex,
generation: uint16(_generation)
});
uint256 newBitKoiId = bitKoi.length;
bitKoi.push(_bitKoi);
// It's probably never going to happen, 4 billion fish is A LOT, but
// let's just be 100% sure we never let this happen.
require(newBitKoiId == uint256(uint32(newBitKoiId)));
// This will assign ownership, and also emit the Transfer event as
// per ERC721 draft
_mintNewKoi(_owner, newBitKoiId);
BitKoi storage brandNewKoi = bitKoi[newBitKoiId];
_triggerCooldown(brandNewKoi);
// emit the spawn event
emit Spawn(
_owner,
newBitKoiId,
uint256(_bitKoi.parent1Id),
uint256(_bitKoi.parent2Id),
_bitKoi.genes,
uint16(_generation),
uint64(block.timestamp)
);
return newBitKoiId;
}
function hatchFish(uint256 _fishId, uint256 _geneSet1, uint256 _geneSet2)
external
payable
whenNotPaused
{
// Checks for payment.
require(msg.value >= hatchFee);
//ensure the caller owns the egg they want to hatch
require(_owns(msg.sender, _fishId));
_hatchFish(_fishId, _geneSet1, _geneSet2);
}
function _hatchFish(uint256 _fishId, uint256 _geneSet1, uint256 _geneSet2) internal {
BitKoi storage fishToHatch = bitKoi[_fishId];
BitKoi storage parent1 = bitKoi[fishToHatch.parent1Id];
BitKoi storage parent2 = bitKoi[fishToHatch.parent2Id];
uint256 genes1 = 0;
uint256 genes2 = 0;
if (fishToHatch.parent1Id > 0){
genes1 = parent1.genes;
} else {
genes1 = _geneSet1;
}
if (fishToHatch.parent2Id > 0){
genes2 = parent2.genes;
} else {
genes2 = _geneSet2;
}
// Check that the parent is a valid fish
require(parent1.spawnTime != 0 && parent2.spawnTime != 0);
// Make sure this fish doesn't already have genes
require(fishToHatch.genes == 0);
// next, let's get new genes for the fish we're about to hatch
uint256 newFishGenes = bitKoiTraits.smooshFish(genes1, genes2, fishToHatch.cooldownEndBlock - 1);
fishToHatch.genes = uint256(newFishGenes);
//transfer the hatch fee less the pond cut to the CFO contract
payable(address(cfoAddress)).transfer(msg.value);
emit Hatch(msg.sender, _fishId, newFishGenes);
}
}
abstract contract BitKoiSale is BitKoiBreeding {
struct Sale {
// Current owner of NFT
address seller;
// Price (in wei) at beginning of sale
uint128 price;
// timestamp
uint256 startedAt;
}
// Cut contract owner takes on each sale, measured in basis points (1/100 of a percent).
// Values 0-10,000 map to 0%-100%
uint256 public ownerCut = 250;
/// @param _ownerCut - update the percent cut the contract owner takes on each breed or hatch event, must be
/// between 0-10,000.
function setOwnerCut(uint256 _ownerCut) external onlyCLevel {
require(_ownerCut <= 10000);
ownerCut = _ownerCut;
}
// Map from token ID to their corresponding sale.
mapping (uint256 => Sale) tokenIdToSale;
event SaleCreated(address sellerId, uint256 tokenId, uint256 price, uint256 startedAt);
event SaleSuccessful(uint256 tokenId, uint256 price, address buyer);
event SaleCancelled(uint256 tokenId);
/// @dev adds a sale to the list of open sales. Also fires the SaleCreated event.
/// @param _tokenId The ID of the token to be put on sale.
/// @param _sale Sale to add.
function _addSale(address _sellerId, uint256 _tokenId, Sale memory _sale, uint256 _saleStarted) internal {
tokenIdToSale[_tokenId] = _sale;
emit SaleCreated(
address(_sellerId),
uint256(_tokenId),
uint256(_sale.price),
uint256(_saleStarted)
);
}
/// @dev Cancels a sale unconditionally.
function _cancelSale(uint256 _tokenId) internal {
_removeSale(_tokenId);
emit SaleCancelled(_tokenId);
}
/// @dev Computes the price and transfers winnings.
/// Does NOT transfer ownership of token.
function _bid(uint256 _tokenId, uint256 _offerAmount)
internal
returns (uint256)
{
// Get a reference to the sale struct
Sale storage sale = tokenIdToSale[_tokenId];
// Explicitly check that this sale 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 sale object that is all zeros.)
require(_isOnSale(sale));
address seller = address(uint160(sale.seller));
uint160 price = sale.price;
// Check that the bid is greater than or equal to the current price
require(_offerAmount >= price);
// The bid is good! Remove the auction before sending the fees
// to the sender so we can't have a reentrancy attack.
_removeSale(_tokenId);
// Transfer proceeds to seller (if there are any!)
if (price > 0) {
// Calculate the contract's cut.
// (NOTE: _computeCut() is guaranteed to return a
// value <= price, so this subtraction can't go negative.)
uint256 contractCut = _computeCut(price);
uint256 sellerProceeds = price - contractCut;
// 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 sale
// 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 cancelSale(). )
payable(cfoAddress).transfer(contractCut);
payable(seller).transfer(sellerProceeds);
}
// Calculate any excess funds included with the bid. If the excess
// is anything worth worrying about, transfer it back to bidder.
// NOTE: We checked above that the bid amount is greater than or
// equal to the price so this cannot underflow.
uint256 bidExcess = _offerAmount - price;
// Return the funds. Similar to the previous transfer, this is
// not susceptible to a re-entry attack because the sale is
// removed before any transfers occur.
payable(msg.sender).transfer(bidExcess);
// Tell the world!
emit SaleSuccessful(_tokenId, price, msg.sender);
return price;
}
/// @dev Removes a sale from the list of open sales
/// @param _tokenId - ID of NFT on sale.
function _removeSale(uint256 _tokenId) internal {
delete tokenIdToSale[_tokenId];
}
/// @dev Returns true if the NFT is on sale.
/// @param _sale - Sale to check.
function _isOnSale(Sale storage _sale) internal view returns (bool) {
return (_sale.startedAt > 0);
}
/// @dev Computes owner's cut of a sale.
/// @param _price - Sale price of NFT.
function _computeCut(uint256 _price) internal view returns (uint256) {
// NOTE: We don't use SafeMath (or similar) in this function because
// all of our entry functions carefully cap the maximum values for
// currency (at 128-bits), and ownerCut <= 10000. The result of this
// function is always guaranteed to be <= _price.
return _price * ownerCut / 10000;
}
/// @dev Creates and begins a new sale.
/// @param _tokenId - ID of token to sale, sender must be owner.
/// @param _price - Price of item (in wei)
/// @param _seller - Seller, if not the message sender
function createSale(
uint256 _tokenId,
uint256 _price,
address _seller
)
external
whenNotPaused
{
// Sanity check that no inputs overflow how many bits we've allocated
// to store them in the sale struct.
require(_price == uint256(uint128(_price)));
require(msg.sender == bitKoiIndexToOwner[_tokenId]);
Sale memory sale = Sale(
address(_seller),
uint128(_price),
uint64(block.timestamp)
);
_addSale(_seller, _tokenId, sale, block.timestamp);
}
function bid(uint256 _tokenId)
external
payable
whenNotPaused
{
// _bid will throw if the bid or funds transfer fails
// _bid verifies token ID size
address seller = tokenIdToSale[_tokenId].seller;
_bid(_tokenId, msg.value);
_transfer(seller, msg.sender, _tokenId);
}
/// @dev Cancels a sale that hasn't been completed.
/// 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 sale
function cancelSale(uint256 _tokenId)
external
{
Sale storage sale = tokenIdToSale[_tokenId];
require(_isOnSale(sale));
address seller = sale.seller;
require(msg.sender == seller);
_cancelSale(_tokenId);
}
/// @dev Cancels a sale 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 sale to cancel.
function cancelSaleWhenPaused(uint256 _tokenId)
whenPaused
onlyOwner
external
{
Sale storage sale = tokenIdToSale[_tokenId];
require(_isOnSale(sale));
_cancelSale(_tokenId);
}
/// @dev Returns sale info for an NFT on sale.
/// @param _tokenId - ID of NFT on sale.
function getSale(uint256 _tokenId)
external
view
returns
(
address seller,
uint256 price,
uint256 startedAt
) {
Sale storage sale = tokenIdToSale[_tokenId];
require(_isOnSale(sale));
return (
sale.seller,
sale.price,
sale.startedAt
);
}
/// @dev Returns the current price of a sale.
/// @param _tokenId - ID of the token price we are checking.
function getCurrentPrice(uint256 _tokenId)
external
view
returns (uint256)
{
Sale storage sale = tokenIdToSale[_tokenId];
require(_isOnSale(sale));
return sale.price;
}
}
/// @title all functions related to creating fish (and their eggs)
abstract contract BitKoiMinting is BitKoiSale {
// Limits the number of fish the contract owner can ever create.
uint256 public constant PROMO_CREATION_LIMIT = 5000;
uint256 public constant GEN0_EGG_CREATION_LIMIT = 45000;
// Counts the number of fish the contract owner has created.
uint256 public promoCreatedCount;
uint256 public gen0CreatedCount;
// Direct sale is not live to start
bool public directSalePaused = true;
//determine the price for minting a new BitKoi gen0 egg
uint256 public gen0PromoPrice = 0 wei;
//number we're currently allowing to be minted
uint256 public currentGen0Cap = 100;
uint16 public currentMintCap = 2;
mapping (address => uint16) tokensMinted;
// allow direct sales of gen0 eggs
function pauseDirectSale() external onlyCLevel {
directSalePaused = true;
}
// stop direct sales of gen0 eggs
function unpauseDirectSale() external onlyCLevel {
directSalePaused = false;
}
// set current cap for sale - this can be raised later so new sales can be started w/ limits
function setCurrentGen0Cap(uint256 val) external onlyCEO {
currentGen0Cap = val;
}
// @dev Updates the minimum payment required for calling mintGen0Egg(). Can only
/// be called by the CEO address.
function setGen0PromoPrice(uint256 val) external onlyCEO {
gen0PromoPrice = val;
}
// @dev Updates the max number of items an address can mint in the given period. Can only
/// be called by the CEO address.
function setMintCap(uint16 val) external onlyCEO {
currentMintCap = val;
}
function mintGen0Egg() external payable {
require (!directSalePaused);
require (msg.value >= gen0PromoPrice);
require (gen0CreatedCount < currentGen0Cap);
require (gen0CreatedCount < GEN0_EGG_CREATION_LIMIT);
require (tokensMinted[msg.sender] < currentMintCap);
//transfer the sale price less the pond cut to the CFO contract
payable(address(cfoAddress)).transfer(msg.value);
gen0CreatedCount++;
tokensMinted[msg.sender]++;
_createBitKoi(0, 0, 0, 0, msg.sender);
}
/// @dev we can create promo fish, up to a limit. Only callable by COO
/// @param _genes the encoded genes of the fish to be created, any value is accepted
/// @param _owner the future owner of the created fish. Default to contract COO
function createPromoFish(uint256 _genes, address _owner) external onlyCOO {
address bitKoiOwner = _owner;
if (bitKoiOwner == address(0)) {
bitKoiOwner = cooAddress;
}
require(promoCreatedCount < PROMO_CREATION_LIMIT);
promoCreatedCount++;
_createBitKoi(0, 0, 0, _genes, bitKoiOwner);
}
}
contract BitKoiCore is BitKoiMinting {
constructor(address _proxyRegistryAddress) ERC721Tradable("BitKoi", "BITKOI", _proxyRegistryAddress) {
// 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;
// the creator of the contract is also the initial COO
cfoAddress = msg.sender;
//start with an initial fish
_createBitKoi(0, 0, 0, type(uint256).max, address(msg.sender));
}
string baseURI = "https://www.bitkoi.co/api/nft/";
string contractMainURI = "https://www.bitkoi.co";
function baseTokenURI() public view returns (string memory) {
return baseURI;
}
function setBaseTokenURI(string memory _newBaseURI) public onlyCEO {
baseURI = _newBaseURI;
}
function setContractURI(string memory _newContractURI) public onlyCEO {
contractMainURI = _newContractURI;
}
function tokenURI(uint256 _tokenId) override public view returns (string memory) {
return string(abi.encodePacked(baseTokenURI(), Strings.toString(_tokenId)));
}
function contractURI() public view returns (string memory) {
return contractMainURI;
}
function unpause() override public onlyCEO whenPaused {
require(address(bitKoiTraits) != address(0));
// Actually unpause the contract.
super.unpause();
}
function withdrawBalance() external onlyCFO {
payable(cfoAddress).transfer(address(this).balance);
}
/// @notice Returns all the relevant information about a specific fish.
/// @param _id The ID of the fish we're looking up
function getBitKoi(uint256 _id)
external
view
returns (
bool isReady,
uint256 cooldownIndex,
uint256 nextActionAt,
uint256 spawnTime,
uint256 parent1Id,
uint256 parent2Id,
uint256 generation,
uint256 cooldownEndBlock,
uint256 genes
) {
BitKoi storage fish = bitKoi[_id];
isReady = (fish.cooldownEndBlock <= block.number);
cooldownIndex = uint256(fish.cooldownIndex);
nextActionAt = uint256(fish.cooldownEndBlock);
spawnTime = uint256(fish.spawnTime);
parent1Id = uint256(fish.parent1Id);
parent2Id = uint256(fish.parent2Id);
generation = uint256(fish.generation);
cooldownEndBlock = uint256(fish.cooldownEndBlock);
genes = fish.genes;
}
} | @dev Removes a sale from the list of open sales @param _tokenId - ID of NFT on sale. | function _removeSale(uint256 _tokenId) internal {
delete tokenIdToSale[_tokenId];
}
| 6,768,927 | [
1,
6220,
279,
272,
5349,
628,
326,
666,
434,
1696,
272,
5408,
225,
389,
2316,
548,
300,
1599,
434,
423,
4464,
603,
272,
5349,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
445,
389,
4479,
30746,
12,
11890,
5034,
389,
2316,
548,
13,
2713,
288,
203,
5411,
1430,
1147,
28803,
30746,
63,
67,
2316,
548,
15533,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/0x42801294b70e298f05A5B83EDe052d39684E96CF/sources/contracts/rewards/BaseRewardPoolV2.sol | if a reward stopped queuing, no need to recalculate to save gas fee | modifier updateRewards(address _account, address[] memory _rewards) {
uint256 length = _rewards.length;
uint256 userShare = balanceOf(_account);
for (uint256 index = 0; index < length; ++index) {
address rewardToken = _rewards[index];
UserInfo storage userInfo = userInfos[rewardToken][_account];
if (userInfo.userRewardPerTokenPaid == rewardPerToken(rewardToken))
continue;
userInfo.userRewards = _earned(_account, rewardToken, userShare);
userInfo.userRewardPerTokenPaid = rewardPerToken(rewardToken);
}
_;
}
| 2,728,682 | [
1,
430,
279,
19890,
9627,
6597,
22370,
16,
1158,
1608,
358,
26657,
358,
1923,
16189,
14036,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
9606,
1089,
17631,
14727,
12,
2867,
389,
4631,
16,
1758,
8526,
3778,
389,
266,
6397,
13,
288,
203,
3639,
2254,
5034,
769,
273,
389,
266,
6397,
18,
2469,
31,
203,
3639,
2254,
5034,
729,
9535,
273,
11013,
951,
24899,
4631,
1769,
203,
540,
203,
3639,
364,
261,
11890,
5034,
770,
273,
374,
31,
770,
411,
769,
31,
965,
1615,
13,
288,
203,
5411,
1758,
19890,
1345,
273,
389,
266,
6397,
63,
1615,
15533,
203,
5411,
25003,
2502,
16753,
273,
729,
7655,
63,
266,
2913,
1345,
6362,
67,
4631,
15533,
203,
5411,
309,
261,
1355,
966,
18,
1355,
17631,
1060,
2173,
1345,
16507,
350,
422,
19890,
2173,
1345,
12,
266,
2913,
1345,
3719,
203,
7734,
1324,
31,
203,
5411,
16753,
18,
1355,
17631,
14727,
273,
389,
73,
1303,
329,
24899,
4631,
16,
19890,
1345,
16,
729,
9535,
1769,
203,
5411,
16753,
18,
1355,
17631,
1060,
2173,
1345,
16507,
350,
273,
19890,
2173,
1345,
12,
266,
2913,
1345,
1769,
203,
3639,
289,
203,
3639,
389,
31,
203,
565,
289,
377,
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
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
//implementation of ERC721 Non-Fungible Token Standard
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
//implementation of ERC721 where tokens can be irreversibly burned (destroyed).
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Burnable.sol";
//implementation of ERC721 where transers can be paused
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Pausable.sol";
//For verifying messages in lazyMint
import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
//Abstract that allows tokens to be listed and exchanged considering royalty fees
import "./abstractions/ERC721Exchange.sol";
contract CollectableTime is ERC721, ERC721Burnable, ERC721Pausable, ERC721Exchange {
//in only the contract owner can add a fee
address private _admin;
modifier onlyAdmin {
require(
_msgSender() == _admin,
"Time: Restricted method access to only the admin"
);
_;
}
/**
* @dev Constructor function
*/
constructor (string memory _name, string memory _symbol)
ERC721(_name, _symbol)
{
_admin = _msgSender();
}
/**
* @dev Sets a fee that will be collected during the exchange method
*/
function allocate(address recipient, uint256 fee)
external virtual onlyAdmin
{
_allocateFee(recipient, fee);
}
/**
* @dev Mints now and transfers to `recipient`
*/
function autoMint(address recipient)
external virtual onlyAdmin
{
uint256 timestamp = block.timestamp;
_safeMint(recipient, timestamp);
}
/**
* @dev Removes a fee
*/
function deallocate(address recipient)
external virtual onlyAdmin
{
_deallocateFee(recipient);
}
/**
* @dev Allows anyone to self mint a token
*/
function lazyMint(uint256 tokenId, address recipient, bytes calldata proof)
public virtual
{
//make sure the admin signed this off
require(
ECDSA.recover(
ECDSA.toEthSignedMessageHash(
keccak256(
abi.encodePacked(tokenId, recipient)
)
),
proof
) == _admin,
"Time: Invalid proof."
);
_safeMint(recipient, tokenId);
}
/**
* @dev Mints `tokenId` and transfers to `recipient`
*/
function mint(uint256 tokenId, address recipient)
external virtual onlyAdmin
{
_safeMint(recipient, tokenId);
}
/**
* @dev Lists `tokenId` on the order book for `amount` in wei.
*/
function list(uint256 tokenId, uint256 amount) external virtual {
_list(tokenId, amount);
}
/**
* @dev Removes `tokenId` from the order book.
*/
function delist(uint256 tokenId) external virtual {
_delist(tokenId);
}
/**
* @dev Allows for a sender to exchange `tokenId` for the listed amount
*/
function exchange(uint256 tokenId) external virtual override payable {
_exchange(tokenId, msg.value);
}
/**
* @dev Pauses all token transfers.
*
* See {ERC721Pausable} and {Pausable-_pause}.
*
* Requirements:
*
* - the caller must have the `PAUSER_ROLE`.
*/
function pause() public virtual onlyAdmin {
_pause();
}
/**
* @dev Returns the total supply of time
*/
function totalSupply() external view returns(uint256) {
return block.timestamp;
}
/**
* @dev Unpauses all token transfers.
*
* See {ERC721Pausable} and {Pausable-_unpause}.
*
* Requirements:
*
* - the caller must have the `PAUSER_ROLE`.
*/
function unpause() public virtual onlyAdmin {
_unpause();
}
/**
* @dev Resolves duplicate _beforeTokenTransfer method definition
* between ERC721 and ERC721Pausable
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override(ERC721, ERC721Pausable) {
super._beforeTokenTransfer(from, to, tokenId);
}
}
| * @dev Removes a fee/ | function deallocate(address recipient)
external virtual onlyAdmin
{
_deallocateFee(recipient);
}
| 1,017,641 | [
1,
6220,
279,
14036,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
443,
16247,
12,
2867,
8027,
13,
203,
565,
3903,
5024,
1338,
4446,
203,
225,
288,
203,
565,
389,
323,
16247,
14667,
12,
20367,
1769,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.3;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "./StakingRewards.sol";
abstract contract StakingRewardsWithFarming is StakingRewards {
using SafeMath for uint256;
using SafeERC20 for IERC20;
address public yieldRecipient;
constructor(
address _owner,
address _yieldRecipient,
address _rewardsToken,
address _stakingToken,
address[] memory _nonRecoverableTokens
) StakingRewards(_owner, _rewardsToken, _stakingToken, _nonRecoverableTokens) {
yieldRecipient = _yieldRecipient;
}
// **** Overrides **** //
// Withdraw from StakingRewards -> User (NOT FARM)
function withdraw(uint256 _amount) public override nonReentrant updateReward(msg.sender) {
// If user wants to withdraw and there isn't enough in the contract
// we need to withdraw some stuff from the farm
uint256 _depositable = getDepositableToFarm();
if (_depositable < _amount) {
withdrawFromFarm(_amount.sub(_depositable));
}
super.withdraw(_amount);
}
// **** Views **** //
// Get total balance of our staking token (both in farm and outside farm)
function getBalanceOfStaking() public view returns (uint256) {
return getDepositedToFarm().add(getDepositableToFarm());
}
// How much can we deposit into the farm
function getDepositableToFarm() public view returns (uint256) {
return stakingToken.balanceOf(address(this));
}
// How much have we deposited into the farm
function getDepositedToFarm() public view virtual returns (uint256) {}
// **** State Changing **** //
// Harvests the farm
function harvestFarm() public virtual {}
// Deposits depositable into the farm
function depositToFarm() public virtual {}
// Withdraws _amount from the farm
function withdrawFromFarm(uint256 _amount) public virtual {}
}
| Get total balance of our staking token (both in farm and outside farm) | function getBalanceOfStaking() public view returns (uint256) {
return getDepositedToFarm().add(getDepositableToFarm());
}
| 6,398,755 | [
1,
967,
2078,
11013,
434,
3134,
384,
6159,
1147,
261,
18237,
316,
284,
4610,
471,
8220,
284,
4610,
13,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
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,
2882,
6112,
951,
510,
6159,
1435,
1071,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
327,
336,
758,
1724,
329,
774,
42,
4610,
7675,
1289,
12,
588,
758,
1724,
429,
774,
42,
4610,
10663,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity 0.7.2;
// SPDX-License-Identifier: JPLv1.2-NRS Public License; Special Conditions with IVT being the Token, ItoVault the copyright holder
import "./SafeMath.sol";
import "./GeneralToken.sol";
contract VaultSystem {
using SafeMath for uint256;
event loguint(string name, uint value);
GeneralToken public vSPYToken;
GeneralToken public ivtToken;
// NB: None of the storage variables below should store numbers greater than 1E36. uint256 overflow above 1E73.
// So it is safe to mul two numbers always. But to mul more than 2 requires decimal counting.
uint public weiPervSPY = 10 ** 18;
uint public maxvSPYE18 = 1000 * 10 ** 18; // Upper Bound on Number of vSPY tokens
uint public outstandingvSPYE18 = 0; // Current outstanding vSPY tokens
// Forward (not counter) Vault System
uint public initialLTVE10 = 7 * 10 ** 9; // Maximum starting loan to value of a vault [Integer / 1E10]
uint public maintLTVE10 = 8 * 10 ** 9; // Maximum maintnenance loan to value of a vault [Integer / 1E10]
uint public liqPenaltyE10 = 1 * 10 ** 9; // Bonus paid to any address for liquidating non-compliant
// contract [Integer / 1E10]
// In this system, individual vaults *are* addresses. Instances of vaults then are mapped by bare address
// Each vault has an "asset" side and a "debt" side
mapping(address => uint) public weiAsset; // Weis the Vault owns -- the asset side
mapping(address => uint) public vSPYDebtE18; // vSPY -- the debt side of the balance sheet of each Vault
// Counter Vault Contract
uint public initialLTVCounterVaultE10 = 7 * 10 ** 9; // Maximum starting loan to value of a vault [Integer / 1E10]
uint public maintLTVCounterVaultE10 = 8 * 10 ** 9; // Maximum maintnenance loan to value of a vault [Integer / 1E10]
uint public liqPenaltyCounterVaultE10 = 1 * 10 ** 9; // Bonus paid to any address for liquidating non-compliant
// contract [Integer / 1E10]
mapping(address => uint) public vSPYAssetCounterVaultE18; // vSPY deposited in inverse vault
mapping(address => uint) public weiDebtCounterVault; // weiDebtCounterVault
// The following variables track all Vaults. Not strictly needed, but helps liquidate non-compliant vaults
mapping(address => bool) public isAddressRegistered; // Forward map to emulate a "set" struct
address[] public registeredAddresses; // Backward map for "set" struct
address payable public owner; // owner is also governor here. to be passed to WATDAO in the future
address payable public oracle; //
bool public inGlobalSettlement = false;
uint public globalSettlementStartTime;
uint public settledWeiPervSPY;
bool public isGloballySettled = false;
uint public lastOracleTime;
bool public oracleChallenged = false; // Is the whitelisted oracle (system) in challenge?
uint public lastChallengeValue; // The weiPervSPY value of the last challenge [Integer atomic weis per 1 unit SPX (e.g. SPX ~ $3300 in Oct 2020)]
uint public lastChallengeIVT; // The WATs staked in the last challenge [WAT atomic units]
uint public lastChallengeTime; // The time of the last challenge, used for challenge expiry[Seconds since Epoch]
uint[] public challengeIVTokens; // Dynamic array of all challenges, integer indexed to match analagous arrays, used like a stack in code
uint[] public challengeValues; // Dynamic array of all challenges, integer indexed, used like a stack in code
address[] public challengers; // Dynamic array of all challengers, integer indexed, used like a stack in code
constructor() {
owner = msg.sender;
oracle = msg.sender;
vSPYToken = new GeneralToken(10 ** 30, address(this), "vSPY Token V_1_0_0", "vSPY V1_0"); // 18 decimals after the point, 12 before
ivtToken = new GeneralToken(10 ** 30, msg.sender, "ItoVault Token V_1_0_0", "IVT V1_0");
}
// Oracle Functions
function oracleUpdateweiPervSPY(uint _weiPervSPY) public {
require(msg.sender == oracle, "Disallowed: You are not oracle");
weiPervSPY = _weiPervSPY;
lastOracleTime = block.timestamp;
}
// Governance Functions
function govUpdateinitialLTVE10(uint _initialLTVE10) public {
require(msg.sender == owner, "Disallowed: You are not governance");
initialLTVE10 = _initialLTVE10;
}
function govUpdatemaintLTVE10(uint _maintLTVE10) public {
require(msg.sender == owner, "Disallowed: You are not governance");
maintLTVE10 = _maintLTVE10;
}
function govUpdateliqPenaltyE10(uint _liqPenaltyE10) public {
require(msg.sender == owner, "Disallowed: You are not governance");
liqPenaltyE10 = _liqPenaltyE10;
}
function govUpdateinitialLTVCounterVaultE10(uint _initialLTVCounterVaultE10) public {
require(msg.sender == owner, "Disallowed: You are not governance");
initialLTVCounterVaultE10 = _initialLTVCounterVaultE10;
}
function govUpdatemaintLTVCounterVaultE10(uint _maintLTVCounterVaultE10) public {
require(msg.sender == owner, "Disallowed: You are not governance");
maintLTVCounterVaultE10 = _maintLTVCounterVaultE10;
}
function govUpdateliqPenaltyCounterVaultE10(uint _liqPenaltyCounterVaultE10) public {
require(msg.sender == owner, "Disallowed: You are not governance");
liqPenaltyCounterVaultE10 = _liqPenaltyCounterVaultE10;
}
function govChangeOwner(address payable _owner) public {
require(msg.sender == owner, "Disallowed: You are not governance");
owner = _owner;
}
function govChangeOracle(address payable _oracle) public {
require(msg.sender == owner, "Disallowed: You are not governance");
oracle = _oracle;
}
function govChangeMaxvSPYE18(uint _maxvSPYE18) public {
require(msg.sender == owner, "Disallowed: You are not governance");
maxvSPYE18 = _maxvSPYE18;
}
function govStartGlobalSettlement() public {
require(msg.sender == owner, "Disallowed: You are not governance");
inGlobalSettlement = true;
globalSettlementStartTime = block.timestamp;
}
// Vault Functions
function depositWEI() public payable { // same as receive fallback; but explictily declared for symmetry
require(msg.value > 0, "Must Deposit Nonzero Wei");
weiAsset[msg.sender] = weiAsset[msg.sender].add( msg.value );
if(isAddressRegistered[msg.sender] != true) { // if user was not registered before
isAddressRegistered[msg.sender] = true;
registeredAddresses.push(msg.sender);
}
}
receive() external payable { // same as receive fallback; but explictily declared for symmetry
require(msg.value > 0, "Must Deposit Nonzero Wei");
// Receiving is automatic so double entry accounting not possible here
weiAsset[msg.sender] = weiAsset[msg.sender].add( msg.value );
if(isAddressRegistered[msg.sender] != true) { // if user was not registered before
isAddressRegistered[msg.sender] = true;
registeredAddresses.push(msg.sender);
}
}
function withdrawWEI(uint _weiWithdraw) public { // NB: Security model is against msg.sender
// presuming contract withdrawal is from own vault
require( _weiWithdraw < 10 ** 30, "Protective max bound for uint argument");
// Maintenence Equation: (vSPYDebtE18/1E18) * weiPervSPY <= (weiAsset) * (initialLTVE10/1E10)
// I need: (vSPYDebtE18)/1E18 * weiPervSPY <= (weiAsset - _weiWithdraw) * (initialLTVE10/1E10)
uint LHS = vSPYDebtE18[msg.sender].mul( weiPervSPY ).mul( 10 ** 10 );
uint RHS = (weiAsset[msg.sender].sub( _weiWithdraw )).mul( initialLTVE10 ).mul( 10 ** 18 );
require ( LHS <= RHS, "Your initial margin is insufficient for withdrawing.");
// Double Entry Accounting
weiAsset[msg.sender] = weiAsset[msg.sender].sub( _weiWithdraw ); // penalize wei deposited before sending money out
msg.sender.transfer(_weiWithdraw);
}
function lendvSPY(uint _vSPYLendE18) public {
//presuming message sender is using his own vault
require(_vSPYLendE18 < 10 ** 30, "Protective max bound for uint argument");
require(outstandingvSPYE18.add( _vSPYLendE18 ) <= maxvSPYE18, "Current version limits max amount of vSPY possible");
// Maintenence Equation: (vSPYDebtE18/1E18) * weiPervSPY <= (weiAsset) * (initialLTVE10/1E10)
// I need: (_vSPYLendE18 + vSPYDebtE18)/1E18 * weiPervSPY < weiAsset * (initialLTVE10/1E10)
uint LHS = vSPYDebtE18[msg.sender].add( _vSPYLendE18 ).mul( weiPervSPY ).mul( 10 ** 10 );
uint RHS = weiAsset[msg.sender].mul( initialLTVE10 ).mul( 10 ** 18 );
require(LHS < RHS, "Your initial margin is insufficient for lending");
// Double Entry Accounting
vSPYDebtE18[msg.sender] = vSPYDebtE18[msg.sender].add( _vSPYLendE18 ); // penalize debt first.
outstandingvSPYE18 = outstandingvSPYE18.add(_vSPYLendE18);
vSPYToken.transfer(msg.sender, _vSPYLendE18);
}
function repayvSPY(uint _vSPYRepayE18) public {
require(_vSPYRepayE18 < 10 ** 30, "Protective max bound for uint argument");
vSPYToken.ownerApprove(msg.sender, _vSPYRepayE18);
// Double Entry Accounting
vSPYToken.transferFrom(msg.sender, address(this), _vSPYRepayE18); // the actual deduction from the token contract
vSPYDebtE18[msg.sender] = vSPYDebtE18[msg.sender].sub( _vSPYRepayE18 );
outstandingvSPYE18 = outstandingvSPYE18.sub(_vSPYRepayE18);
}
function liquidateNonCompliant(uint _vSPYProvidedE18, address payable target_address) public { // liquidates a portion of the contract for non-compliance
// While it possible to have a more complex liquidation system, since liqudations are off-equilibrium, for the MVP
// We have decided we want overly aggressive liqudiations
// Maintenence Equation: (vSPYDebtE18/1E18) * weiPervSPY <= (weiAsset) * (maintLTVE10/1E10)
// For a violation, the above will be flipped: (vSPYDebtE18/1E18) * weiPervSPY > (weiAsset) * (maintLTVE10/1E10)
require( _vSPYProvidedE18 <= vSPYDebtE18[target_address], "You cannot provide more vSPY than vSPYDebt outstanding");
uint LHS = vSPYDebtE18[target_address].mul( weiPervSPY ).mul( 10 ** 10);
uint RHS = weiAsset[target_address].mul( maintLTVE10 ).mul( 10 ** 18);
require(LHS > RHS, "Current contract is within maintainance margin, so you cannot run this");
// If this vault is underwater-with-respect-to-rewards (different than noncompliant), liquidation is pro-rata
// underater iff: weiAsset[target_address] < vSPYDebtE18[target_address]/1E18 * weiPervSPY * (liqPenaltyE10+1E10)/1E10
uint LHS2 = weiAsset[target_address].mul( 10 ** 18 ).mul( 10 ** 10);
uint RHS2 = vSPYDebtE18[target_address].mul( weiPervSPY ).mul( liqPenaltyE10.add( 10 ** 10 ));
uint weiClaim;
if( LHS2 < RHS2 ) { // pro-rata claim
// weiClaim = ( _vSPYProvidedE18 / vSPYDebtE18[target_address]) * weiAsset[target_address];
weiClaim = _vSPYProvidedE18.mul( weiAsset[target_address] ).div( vSPYDebtE18[target_address] );
} else {
// maxWeiClaim = _vSPYProvidedE18/1E18 * weiPervSPY * (1+liqPenaltyE10/1E10)
weiClaim = _vSPYProvidedE18.mul( weiPervSPY ).mul( liqPenaltyE10.add( 10 ** 10 )).div( 10 ** 18 ).div( 10 ** 10 );
}
require(weiClaim <= weiAsset[target_address], "Code Error if you reached this point");
// Double Entry Accounting for returning vSPY Debt back
vSPYToken.ownerApprove(msg.sender, _vSPYProvidedE18);
vSPYToken.transferFrom(msg.sender, address(this), _vSPYProvidedE18); // the actual deduction from the token contract
vSPYDebtE18[target_address] = vSPYDebtE18[target_address].sub( _vSPYProvidedE18 );
outstandingvSPYE18 = outstandingvSPYE18.sub( _vSPYProvidedE18 );
// Double Entry Accounting for deducting the vault's assets
weiAsset[target_address] = weiAsset[target_address].sub( weiClaim );
msg.sender.transfer( weiClaim );
}
// Counter Vault Functions
function depositvSPYCounterVault(uint _vSPYDepositE18) public {
require( _vSPYDepositE18 < 10 ** 30, "Protective max bound for uint argument");
// Transfer Tokens from sender, then double-entry account for it
vSPYToken.ownerApprove(msg.sender, _vSPYDepositE18);
vSPYToken.transferFrom(msg.sender, address(this), _vSPYDepositE18);
vSPYAssetCounterVaultE18[msg.sender] = vSPYAssetCounterVaultE18[msg.sender].add(_vSPYDepositE18);
if(isAddressRegistered[msg.sender] != true) { // if user was not registered before
isAddressRegistered[msg.sender] = true;
registeredAddresses.push(msg.sender);
}
}
function withdrawvSPYCounterVault(uint _vSPYWithdrawE18) public {
require( _vSPYWithdrawE18 < 10 ** 30, "Protective max bound for uint argument");
// Master equation for countervault: (weiDebtCounterVault ) < (vSPYAssetCounterVaultE18)/1E18 * weiPervSPY * (initialLTVCounterVaultE10/1E10)
// I need: (weiDebtCounterVault ) < (vSPYAssetCounterVaultE18 - _vSPYLendE18)/1E18 * weiPervSPY * (initialLTVCounterVaultE10/1E10)
uint LHS = weiDebtCounterVault[msg.sender].mul( 10 ** 10 ).mul( 10 ** 18 );
uint RHS = vSPYAssetCounterVaultE18[msg.sender].sub( _vSPYWithdrawE18 ).mul( weiPervSPY ).mul( initialLTVCounterVaultE10 );
require ( LHS <= RHS, 'Your initial margin is insufficient for withdrawing.' );
vSPYAssetCounterVaultE18[msg.sender] = vSPYAssetCounterVaultE18[msg.sender].sub( _vSPYWithdrawE18 ); // Penalize Account First
vSPYToken.transfer(msg.sender, _vSPYWithdrawE18);
}
function lendWeiCounterVault(uint _weiLend) public {
//presuming message sender is using his own vault
require(_weiLend < 10 ** 30, "Protective Max Bound for Input Hit");
// Master equation for countervault: (weiDebtCounterVault ) < (vSPYAssetCounterVaultE18)/1E18 * weiPervSPY * (initialLTVCounterVaultE10/1E10)
// I need: (weiDebtCounterVault + _weiWithdraw ) < weiPervSPY * (vSPYAssetCounterVaultE18/1E18) * (initialLTVCounterVaultE10/1E10)
uint LHS = weiDebtCounterVault[msg.sender].add( _weiLend ).mul( 10** 18 ).mul( 10 ** 10 );
uint RHS = weiPervSPY.mul( vSPYAssetCounterVaultE18[msg.sender] ).mul( initialLTVCounterVaultE10 );
require(LHS <= RHS, "Your initial margin is insufficient for lending.");
// Double-entry accounting
weiDebtCounterVault[msg.sender] = weiDebtCounterVault[msg.sender].add( _weiLend ); // penalize debt first.
msg.sender.transfer(_weiLend);
}
function repayWeiCounterVault() public payable {
require(msg.value < 10 ** 30, "Protective Max Bound for Input Hit");
require(msg.value <= weiDebtCounterVault[msg.sender], "You cannot pay down more Wei debt than exists in this counterVault");
// Single entry accounting
weiDebtCounterVault[msg.sender] = weiDebtCounterVault[msg.sender].sub( msg.value );
}
function liquidateNonCompliantCounterVault(address payable _targetCounterVault) payable public { // liquidates a portion of the counterVault for non-compliance
// Security Presumption here is against favor of the runner of this function
require( msg.value < 10 ** 30 , "Protective Max Bound for WEI Hit");
require( msg.value <= weiDebtCounterVault[_targetCounterVault], "You cannot provide more Wei than Wei debt outstanding");
// Vault Needs to be in Violation: (weiDebtCounterVault ) > (vSPYAssetCounterVaultE18)/1E18 * weiPervSPY * (maintLTVE10InverseVault/1E10)
uint LHS = weiDebtCounterVault[_targetCounterVault].mul( 10 ** 18 ).mul( 10 ** 10 );
uint RHS = vSPYAssetCounterVaultE18[_targetCounterVault].mul( weiPervSPY ).mul( maintLTVCounterVaultE10 );
emit loguint("RHS", RHS);
emit loguint("LHS", LHS);
require(LHS > RHS, "Current contract is within maintenence margin");
// If this Counter Vault is underwater-with-respect-to-rewards (different than noncompliant), liquidation is pro-rata
// underater iff: vSPYAssetCounterVaultE18[_targetCounterVault] < (weiDebtCounterVault[_targetCounterVault]/ weiPervSPY) * 1E18 * (liqPenaltyCounterVaultE10+1E10)/1E10
uint LHS2 = vSPYAssetCounterVaultE18[_targetCounterVault];
uint RHS2 = weiDebtCounterVault[_targetCounterVault].mul( liqPenaltyCounterVaultE10.add( 10 ** 10 )).mul( 10 ** 8 ).div( weiPervSPY );
emit loguint("RHS2", RHS2);
emit loguint("LHS2", LHS2);
uint vSPYClaimE18;
if( LHS2 < RHS2 ) { // if vault is rewards-underwater, pro-rate
// vSPYClaimE18 = ( msg.value / weiDebtCounterVault[_targetCounterVault]) * vSPYAssetCounterVaultE18[_targetCounterVault];
vSPYClaimE18 = msg.value.mul( vSPYAssetCounterVaultE18[_targetCounterVault] ).div( weiDebtCounterVault[_targetCounterVault] );
require(vSPYClaimE18 <= vSPYAssetCounterVaultE18[_targetCounterVault], "Code Error Branch 1 if you reached this point");
} else { // if we have more than enough assets in this countervault
// vSPYClaimE18 = (msg.value / weiPervSPY) * 1E18 * (1E10+liqPenaltyE10) /1E10
vSPYClaimE18 = msg.value.mul( liqPenaltyCounterVaultE10.add( 10 ** 10 )).mul( 10 ** 8 ).div(weiPervSPY) ;
require(vSPYClaimE18 <= vSPYAssetCounterVaultE18[_targetCounterVault], "Code Error Branch 2 if you reached this point");
}
// Single Entry Accounting for Returning the wei Debt
weiDebtCounterVault[_targetCounterVault] = weiDebtCounterVault[_targetCounterVault].sub( msg.value );
// Double Entry Accounting
vSPYAssetCounterVaultE18[_targetCounterVault] = vSPYAssetCounterVaultE18[_targetCounterVault].sub( vSPYClaimE18 ); // Amount of Assets to Transfer override
vSPYToken.transfer( msg.sender , vSPYClaimE18 );
}
function partial1LiquidateNonCompliantCounterVault(address payable _targetCounterVault) payable public returns(uint, uint) { // liquidates a portion of the counterVault for non-compliance
// Security Presumption here is against favor of the runner of this function
require( msg.value < 10 ** 30 , "Protective Max Bound for WEI Hit");
require( msg.value <= weiDebtCounterVault[_targetCounterVault], "You cannot provide more Wei than Wei debt outstanding");
// Vault Needs to be in Violation: (weiDebtCounterVault ) > (vSPYAssetCounterVaultE18)/1E18 * weiPervSPY * (maintLTVE10InverseVault/1E10)
uint LHS = weiDebtCounterVault[_targetCounterVault].mul( 10 ** 18 ).mul( 10 ** 10 );
uint RHS = vSPYAssetCounterVaultE18[_targetCounterVault].mul( weiPervSPY ).mul( maintLTVCounterVaultE10 );
require(LHS > RHS, "Current contract is within maintenence margin");
return(LHS, RHS);
}
function partial2LiquidateNonCompliantCounterVault(address payable _targetCounterVault) payable public returns(uint, uint) { // liquidates a portion of the counterVault for non-compliance
// Security Presumption here is against favor of the runner of this function
require( msg.value < 10 ** 30 , "Protective Max Bound for WEI Hit");
require( msg.value <= weiDebtCounterVault[_targetCounterVault], "You cannot provide more Wei than Wei debt outstanding");
// Vault Needs to be in Violation: (weiDebtCounterVault ) > (vSPYAssetCounterVaultE18)/1E18 * weiPervSPY * (maintLTVE10InverseVault/1E10)
// If this Counter Vault is underwater-with-respect-to-rewards (different than noncompliant), liquidation is pro-rata
// underater iff: vSPYAssetCounterVaultE18[_targetCounterVault] < (weiDebtCounterVault[_targetCounterVault]/ weiPervSPY) * 1E18 * (liqPenaltyCounterVaultE10+1E10)/1E10
uint LHS2 = vSPYAssetCounterVaultE18[_targetCounterVault];
uint RHS2 = weiDebtCounterVault[_targetCounterVault].mul( liqPenaltyCounterVaultE10.add( 10 ** 10 )).mul( 10 ** 8 ).div( weiPervSPY );
return(LHS2, RHS2);
}
function findNoncompliantVaults(uint _limitNum) public view returns(address[] memory, uint[] memory, uint[] memory, uint[] memory, uint[] memory, uint) { // Return the first N noncompliant vaults
require(_limitNum > 0, 'Must run this on a positive integer');
address[] memory noncompliantAddresses = new address[](_limitNum);
uint[] memory LHSs_vault = new uint[](_limitNum);
uint[] memory RHSs_vault = new uint[](_limitNum);
uint[] memory LHSs_counterVault = new uint[](_limitNum);
uint[] memory RHSs_counterVault = new uint[](_limitNum);
uint j = 0; // Iterator up to _limitNum
for (uint i=0; i<registeredAddresses.length; i++) {
if(j>= _limitNum) {
break;
}
// Vault maintainance margin violation: (vSPYDebtE18)/1E18 * weiPervSPY > weiAsset * (maintLTVE10)/1E10 for a violation
uint LHS_vault = vSPYDebtE18[registeredAddresses[i]].mul(weiPervSPY);
uint RHS_vault = weiAsset[registeredAddresses[i]].mul( maintLTVE10 ).mul( 10 ** 8);
// Countervault maintenance margin violation: (weiDebtCounterVault ) > (vSPYAssetCounterVaultE18)/1E18 * weiPervSPY * (maintLTVE10InverseVault/1E10)
uint LHS_counterVault = weiDebtCounterVault[registeredAddresses[i]].mul( 10 ** 18 ).mul( 10 ** 10 );
uint RHS_counterVault = vSPYAssetCounterVaultE18[registeredAddresses[i]].mul( weiPervSPY ).mul( maintLTVCounterVaultE10 );
if( (LHS_vault > RHS_vault) || (LHS_counterVault > RHS_counterVault) ) {
noncompliantAddresses[j] = registeredAddresses[i];
LHSs_vault[j] = LHS_vault;
RHSs_vault[j] = RHS_vault;
LHSs_counterVault[j] = LHS_counterVault;
RHSs_counterVault[j] = RHS_counterVault;
j = j + 1;
}
}
return(noncompliantAddresses, LHSs_vault, RHSs_vault, LHSs_counterVault, RHSs_counterVault, j);
}
// The following functions are off off-equilibrium. Thus they are vetted to be safe, but not necessarily efficient/optimal.
// Global Settlement Functions
function registerGloballySettled() public { // Anyone can run this closing function
require(inGlobalSettlement, "Register function can only be run if governance has declared global settlement");
require(block.timestamp > (globalSettlementStartTime + 14 days), "Need to wait 14 days to finalize global settlement");
require(!isGloballySettled, "This function has already be run; can only be run once.");
settledWeiPervSPY = weiPervSPY;
isGloballySettled = true;
}
function settledConvertvSPYtoWei(uint _vSPYTokenToConvertE18) public {
require(isGloballySettled);
require(_vSPYTokenToConvertE18 < 10 ** 30, "Protective max bound for input hit");
uint weiToReturn = _vSPYTokenToConvertE18.mul( settledWeiPervSPY ).div( 10 ** 18); // Rounds down
// vSPY accounting is no longer double entry. Destroy vSPY to get wei
vSPYToken.ownerApprove(msg.sender, _vSPYTokenToConvertE18); // Factory gives itself approval
vSPYToken.transferFrom(msg.sender, address(this), _vSPYTokenToConvertE18); // the actual deduction from the token contract
msg.sender.transfer(weiToReturn); // return wei
}
function settledConvertVaulttoWei() public {
require(isGloballySettled);
uint weiDebt = vSPYDebtE18[msg.sender].mul( settledWeiPervSPY ).div( 10 ** 18).add( 1 ); // Round up value of debt
require(weiAsset[msg.sender] > weiDebt, "This CTV is not above water, cannot convert");
uint weiEquity = weiAsset[msg.sender] - weiDebt;
// Zero out CTV and transfer equity remaining
vSPYDebtE18[msg.sender] = 0;
weiAsset[msg.sender] = 0;
msg.sender.transfer(weiEquity);
}
// Challenge Functions -- non-optimized
function startChallengeWeiPervSPY(uint _proposedWeiPervSPY, uint _ivtStaked) public {
// Checking we're in the right state
require(lastOracleTime > 0, "Cannot challenge a newly created smart contract");
require(block.timestamp.sub( lastOracleTime ) > 14 days, "You must wait for the whitelist oracle to not respond for 14 days" );
require(_ivtStaked >= 10 * 10 ** 18, 'You must challenge with at least ten IVT');
require(_proposedWeiPervSPY != weiPervSPY, 'You do not disagree with current value of weiPervSPY');
require(oracleChallenged == false);
// Deducting tokens and crediting
uint256 allowance = ivtToken.allowance(msg.sender, address(this));
require(allowance >= _ivtStaked, 'You have not allowed this contract access to the number of IVTs you claim');
ivtToken.transferFrom(msg.sender, address(this), _ivtStaked); // the actual deduction from the token contract
// Credit this challenger
challengers.push(msg.sender);
// Start the challenge
oracleChallenged = true;
challengeValues.push(_proposedWeiPervSPY);
challengeIVTokens.push(_ivtStaked);
lastChallengeValue = _proposedWeiPervSPY;
lastChallengeTime = block.timestamp;
}
function rechallengeWeiPervSPY(uint _proposedWeiPervSPY, uint _ivtStaked) public {
require(oracleChallenged == true, "rechallenge cannot be run if challenge has not started. consider startChallengeWeiPervSPY()");
require(_ivtStaked >= lastChallengeIVT * 2, "You must double the IVT from the last challenge");
require(_proposedWeiPervSPY != lastChallengeValue, "You do not disagree with last challenge of weiPervSPY");
// Deducting tokens and crediting
uint256 allowance = ivtToken.allowance(msg.sender, address(this));
require(allowance >= _ivtStaked, 'You have not allowed this contract access to the number of WATs you claim');
ivtToken.transferFrom(msg.sender, address(this), _ivtStaked); // the actual deduction from the token contract
// Credit this challenger
challengers.push(msg.sender);
// Actually do the challenge
challengeValues.push(_proposedWeiPervSPY);
challengeIVTokens.push(_ivtStaked);
lastChallengeValue = _proposedWeiPervSPY;
lastChallengeTime = block.timestamp;
lastChallengeIVT = _ivtStaked;
}
function endChallegeWeiPerSPX() public {
require(oracleChallenged == true, "Consider startChallengeWeiPervSPY()");
require(block.timestamp.sub( lastChallengeTime ) > 2 days, "You must wait 2 days since the last challenge to end the challenge");
// This now makes effective the challenge oracle
weiPervSPY = lastChallengeValue;
// initialize cumulative counter of correct vs incorrect wats
uint incorrectIvts = 0;
uint correctIvts = 0;
// calculate the payback ratio
for(uint i = 0; i < challengeIVTokens.length; i++) {
if(challengeValues[i] == weiPervSPY) {
correctIvts += challengeIVTokens[i];
} else {
incorrectIvts += challengeIVTokens[i];
}
}
// Distribute the tokens
for(uint i = 0; i < challengeIVTokens.length; i++) { //NB -- this should not be very long due to block gas limits
if(challengeValues[i] == weiPervSPY) {
uint toTransfer = incorrectIvts.add(correctIvts).mul( challengeIVTokens[i] ).div( correctIvts );
// best practice: remove this person's credit first
challengeIVTokens[i] = 0;
vSPYToken.transfer(challengers[i], toTransfer);
} else {
// erase the challengeIVTokens
challengeIVTokens[i] = 0;
}
}
// reset arrays to zero type
delete challengeIVTokens;
delete challengeValues;
delete challengers;
lastChallengeValue = 0;
lastChallengeIVT = 0;
lastChallengeTime = 0;
// end challenge
oracleChallenged = false;
}
function detachOwner() public { // an emergency function to commitally shut off the owner account while retaining residual functionality of tokens
require(msg.sender == owner);
initialLTVE10 = 4 * 10 ** 9; // 40% LTV at start
maintLTVE10 = 5 * 10 ** 9; // 50% LTV to maintain
liqPenaltyE10 = 15 * 10 ** 8; // 15% liquidation penalty
oracle = address(0);
owner = address(0);
}
}
| Counter Vault Functions Transfer Tokens from sender, then double-entry account for it | function depositvSPYCounterVault(uint _vSPYDepositE18) public {
require( _vSPYDepositE18 < 10 ** 30, "Protective max bound for uint argument");
vSPYToken.ownerApprove(msg.sender, _vSPYDepositE18);
vSPYToken.transferFrom(msg.sender, address(this), _vSPYDepositE18);
vSPYAssetCounterVaultE18[msg.sender] = vSPYAssetCounterVaultE18[msg.sender].add(_vSPYDepositE18);
isAddressRegistered[msg.sender] = true;
registeredAddresses.push(msg.sender);
uint LHS2 = weiAsset[target_address].mul( 10 ** 18 ).mul( 10 ** 10);
weiClaim = _vSPYProvidedE18.mul( weiAsset[target_address] ).div( vSPYDebtE18[target_address] );
} else {
weiClaim = _vSPYProvidedE18.mul( weiPervSPY ).mul( liqPenaltyE10.add( 10 ** 10 )).div( 10 ** 18 ).div( 10 ** 10 );
vSPYToken.ownerApprove(msg.sender, _vSPYProvidedE18);
weiAsset[target_address] = weiAsset[target_address].sub( weiClaim );
}
| 1,523,038 | [
1,
4789,
17329,
15486,
12279,
13899,
628,
5793,
16,
1508,
1645,
17,
4099,
2236,
364,
518,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
443,
1724,
90,
3118,
61,
4789,
12003,
12,
11890,
389,
90,
3118,
61,
758,
1724,
41,
2643,
13,
1071,
288,
7010,
3639,
2583,
12,
389,
90,
3118,
61,
758,
1724,
41,
2643,
411,
1728,
2826,
5196,
16,
315,
29599,
688,
943,
2489,
364,
2254,
1237,
8863,
203,
540,
203,
3639,
331,
3118,
61,
1345,
18,
8443,
12053,
537,
12,
3576,
18,
15330,
16,
389,
90,
3118,
61,
758,
1724,
41,
2643,
1769,
7010,
3639,
331,
3118,
61,
1345,
18,
13866,
1265,
12,
3576,
18,
15330,
16,
1758,
12,
2211,
3631,
389,
90,
3118,
61,
758,
1724,
41,
2643,
1769,
203,
3639,
331,
3118,
61,
6672,
4789,
12003,
41,
2643,
63,
3576,
18,
15330,
65,
273,
331,
3118,
61,
6672,
4789,
12003,
41,
2643,
63,
3576,
18,
15330,
8009,
1289,
24899,
90,
3118,
61,
758,
1724,
41,
2643,
1769,
203,
540,
203,
5411,
353,
1887,
10868,
63,
3576,
18,
15330,
65,
273,
638,
31,
203,
5411,
4104,
7148,
18,
6206,
12,
3576,
18,
15330,
1769,
203,
540,
203,
540,
203,
3639,
2254,
511,
13173,
22,
273,
732,
77,
6672,
63,
3299,
67,
2867,
8009,
16411,
12,
1728,
2826,
6549,
262,
18,
16411,
12,
1728,
2826,
1728,
1769,
203,
5411,
732,
77,
9762,
273,
389,
90,
3118,
61,
19254,
41,
2643,
18,
16411,
12,
732,
77,
6672,
63,
3299,
67,
2867,
65,
262,
18,
2892,
12,
331,
3118,
61,
758,
23602,
41,
2643,
63,
3299,
67,
2867,
65,
11272,
203,
3639,
289,
469,
288,
203,
5411,
732,
77,
9762,
273,
389,
90,
3118,
61,
2
] |
./full_match/3/0x2F4459080cb108C23DAa285ABE093401a152C6ea/sources/contracts/Octopus/KiboAdmin.sol | KToken has 4 decimals and WBTC has 4 decimals
| seller.notional = _uniswapInitialUSDT * 1e4; | 8,225,443 | [
1,
47,
1345,
711,
1059,
15105,
471,
678,
38,
15988,
711,
1059,
15105,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
5411,
29804,
18,
902,
285,
287,
273,
389,
318,
291,
91,
438,
4435,
3378,
9081,
380,
404,
73,
24,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: --GRISE--
pragma solidity =0.7.6;
import './Interfaces.sol';
import './Randomness.sol';
contract LiquidityTransformer {
using SafeMathLT for uint256;
using SafeMathLT for uint128;
Randomness public randomness;
IGriseToken public GRISE_CONTRACT;
RefundSponsorI public REFUND_SPONSOR;
UniswapRouterV2 public constant UNISWAP_ROUTER = UniswapRouterV2(
0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D // mainnet
);
address payable constant TEAM_ADDRESS = 0xa377433831E83C7a4Fa10fB75C33217cD7CABec2;
address payable constant DEV_ADDRESS = 0xcD8DcbA8e4791B19719934886A8bA77EA3fad447;
address public TOKEN_DEFINER;
address constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; // mainnet
uint8 constant INVESTMENT_DAYS = 50;
uint8 constant MAX_DAY_SLOT = 147;
uint128 constant THRESHOLD_LIMIT_MIN = 100000000000000000 wei;
uint128 constant THRESHOLD_LIMIT_MAX = 20 ether;
uint256 public TEAM_ETHER;
uint128 constant MIN_INVEST = 100000000000000000 wei;
uint128 constant DAILY_MAX_SUPPLY = 12000;
uint256 constant REI_PER_GRISE = 10 ** uint256(18);
struct Globals {
uint64 generatedDays;
uint64 preparedReferrals;
uint256 totalTransferTokens;
uint256 totalWeiContributed;
uint256 totalReferralTokens;
}
Globals public g;
mapping(uint256 => uint256) dailyMinSupply;
mapping(uint256 => uint256) dailyMaxSupply;
mapping(uint256 => uint256) public dailyTotalSupply;
mapping(uint256 => uint256) public dailyTotalInvestment;
mapping(uint256 => uint256) public dailySlots;
uint256 public totalInvestment;
uint8 public totalTransactions;
uint8 constant GAS_REFUND_THRESHOLD = 200;
mapping(uint256 => uint256) public investorAccountCount;
mapping(uint256 => mapping(uint256 => address)) public investorAccounts;
mapping(address => mapping(uint256 => uint256)) public investorBalances;
mapping(address => mapping(uint256 => uint256)) public investorBalancesRecord;
mapping(address => uint256) public referralAmount;
mapping(address => uint256) public referralTokens;
mapping(address => uint256) public investorTotalBalance;
mapping(address => uint256) originalInvestment;
uint256 public referralAccountCount;
uint256 public uniqueInvestorCount;
mapping (uint256 => address) public uniqueInvestors;
mapping (uint256 => address) public referralAccounts;
event GeneratedRandomSupply(
uint256 indexed investmentDay,
uint256 randomSupply
);
event GeneratedStaticSupply(
uint256 indexed investmentDay,
uint256 staticSupply
);
event ReferralAdded(
address indexed referral,
address indexed referee,
uint256 amount
);
event UniSwapResult(
uint256 amountToken,
uint256 amountETH,
uint256 liquidity
);
event GriseReservation(
address indexed sender,
uint256 indexed investmentDay,
uint256 amount
);
modifier afterInvestmentPhase() {
require(
_currentLPDay() > INVESTMENT_DAYS,
'GRISE: ongoing investment phase'
);
_;
}
modifier afterUniswapTransfer() {
require (
g.generatedDays > 0 &&
g.totalWeiContributed == 0,
'GRISE: forward liquidity first'
);
_;
}
modifier investmentDaysRange(uint256 _investmentDay) {
require(
_investmentDay > 0 &&
_investmentDay <= INVESTMENT_DAYS,
'GRISE: not in initial investment days range'
);
_;
}
modifier onlyFundedDays(uint256 _investmentDay) {
require(
dailyTotalInvestment[_investmentDay] > 0,
'GRISE: no investments on that day'
);
_;
}
modifier refundSponsorDynamic() {
uint256 gasStart = gasleft();
_;
uint256 gasSpent = (21000 + gasStart - gasleft()).mul(tx.gasprice);
gasSpent = msg.value.div(10) > gasSpent ? gasSpent : msg.value.div(10);
if(totalTransactions <= GAS_REFUND_THRESHOLD){
REFUND_SPONSOR.addGasRefund(msg.sender, gasSpent);
}
}
modifier refundSponsorFixed() {
uint256 gasStart = gasleft();
_;
uint256 gasSpent = (21000 + gasStart - gasleft()).mul(tx.gasprice);
gasSpent = gasSpent > 5000000000000000 ? 5000000000000000 : gasSpent;
if(totalTransactions <= GAS_REFUND_THRESHOLD){
REFUND_SPONSOR.addGasRefund(msg.sender, gasSpent);
}
}
modifier onlyTokenDefiner() {
require(
msg.sender == TOKEN_DEFINER,
'GRISE: wrong sender'
);
_;
}
receive() external payable {
require (
msg.sender == address(UNISWAP_ROUTER) ||
msg.sender == TEAM_ADDRESS ||
msg.sender == DEV_ADDRESS ||
msg.sender == TOKEN_DEFINER,
'GRISE: direct deposits disabled'
);
}
function defineToken(
address _griseToken
)
external
onlyTokenDefiner
{
GRISE_CONTRACT = IGriseToken(_griseToken);
}
function revokeAccess()
external
onlyTokenDefiner
{
TOKEN_DEFINER = address(0x0);
}
constructor(address _griseToken, Randomness _randomness, address _refundSponsor) {
randomness=_randomness;
GRISE_CONTRACT = IGriseToken(_griseToken);
REFUND_SPONSOR = RefundSponsorI(_refundSponsor);
TOKEN_DEFINER = msg.sender;
dailyMinSupply[1] = 6000;
dailyMinSupply[2] = 6000;
dailyMinSupply[3] = 6000;
dailyMinSupply[4] = 6000;
dailyMinSupply[5] = 2150;
dailyMinSupply[6] = 6000;
dailyMinSupply[7] = 3650;
dailyMinSupply[8] = 6000;
dailyMinSupply[9] = 3650;
dailyMinSupply[10] = 6000;
dailyMinSupply[11] = 3650;
dailyMinSupply[12] = 6000;
dailyMinSupply[13] = 6000;
dailyMinSupply[14] = 2150;
dailyMinSupply[15] = 6000;
dailyMinSupply[16] = 3650;
dailyMinSupply[17] = 6000;
dailyMinSupply[18] = 3650;
dailyMinSupply[19] = 6000;
dailyMinSupply[20] = 2150;
dailyMinSupply[21] = 6000;
dailyMinSupply[22] = 2150;
dailyMinSupply[23] = 6000;
dailyMinSupply[24] = 2150;
dailyMinSupply[25] = 6000;
dailyMinSupply[26] = 2150;
dailyMinSupply[27] = 6000;
dailyMinSupply[28] = 6000;
dailyMinSupply[29] = 3650;
dailyMinSupply[30] = 6000;
dailyMinSupply[31] = 6000;
dailyMinSupply[32] = 2150;
dailyMinSupply[33] = 6000;
dailyMinSupply[34] = 3650;
dailyMinSupply[35] = 6000;
dailyMinSupply[36] = 3650;
dailyMinSupply[37] = 6000;
dailyMinSupply[38] = 2150;
dailyMinSupply[39] = 2150;
dailyMinSupply[40] = 6000;
dailyMinSupply[41] = 3650;
dailyMinSupply[42] = 6000;
dailyMinSupply[43] = 6000;
dailyMinSupply[44] = 2150;
dailyMinSupply[45] = 6000;
dailyMinSupply[46] = 3650;
dailyMinSupply[47] = 2150;
dailyMinSupply[48] = 3650;
dailyMinSupply[49] = 6000;
dailyMinSupply[50] = 6000;
dailyMaxSupply[5] = 16850;
dailyMaxSupply[14] = 16850;
dailyMaxSupply[20] = 16850;
dailyMaxSupply[22] = 16850;
dailyMaxSupply[24] = 16850;
dailyMaxSupply[26] = 16850;
dailyMaxSupply[32] = 16850;
dailyMaxSupply[38] = 16850;
dailyMaxSupply[39] = 16850;
dailyMaxSupply[44] = 16850;
dailyMaxSupply[47] = 16850;
dailyMaxSupply[7] = 11850;
dailyMaxSupply[9] = 11850;
dailyMaxSupply[11] = 11850;
dailyMaxSupply[16] = 11850;
dailyMaxSupply[18] = 11850;
dailyMaxSupply[29] = 11850;
dailyMaxSupply[34] = 11850;
dailyMaxSupply[36] = 11850;
dailyMaxSupply[41] = 11850;
dailyMaxSupply[46] = 11850;
dailyMaxSupply[48] = 11850;
}
// GRISE RESERVATION (EXTERNAL FUNCTIONS) //
// ------------------------------------- //
/** @dev Performs reservation of GRISE tokens with ETH
* @param _investmentDays array of reservation days.
* @param _referralAddress referral address for bonus.
*/
function reserveGrise(
uint8[] calldata _investmentDays,
address _referralAddress
)
external
payable
refundSponsorDynamic
{
checkInvestmentDays(
_investmentDays,
_currentLPDay(),
msg.sender,
msg.value
);
_reserveGrise(
_investmentDays,
_referralAddress,
msg.sender,
msg.value
);
}
/** @notice Allows reservation of GRISE tokens with other ERC20 tokens
* @dev this will require LT contract to be approved as spender
* @param _tokenAddress address of an ERC20 token to use
* @param _tokenAmount amount of tokens to use for reservation
* @param _investmentDays array of reservation days
* @param _referralAddress referral address for bonus
*/
function reserveGriseWithToken(
address _tokenAddress,
uint256 _tokenAmount,
uint8[] calldata _investmentDays,
address _referralAddress
)
external
refundSponsorFixed
{
IERC20Token _token = IERC20Token(
_tokenAddress
);
_token.transferFrom(
msg.sender,
address(this),
_tokenAmount
);
_token.approve(
address(UNISWAP_ROUTER),
_tokenAmount
);
address[] memory _path = preparePath(
_tokenAddress
);
uint256[] memory amounts =
UNISWAP_ROUTER.swapExactTokensForETH(
_tokenAmount,
0,
_path,
address(this),
block.timestamp.add(2 hours)
);
checkInvestmentDays(
_investmentDays,
_currentLPDay(),
msg.sender,
amounts[1]
);
_reserveGrise(
_investmentDays,
_referralAddress,
msg.sender,
amounts[1]
);
}
// GRISE RESERVATION (INTERNAL FUNCTIONS) //
// ------------------------------------- //
/** @notice Distributes ETH equaly between selected reservation days
* @dev this will require LT contract to be approved as a spender
* @param _investmentDays array of selected reservation days
* @param _referralAddress referral address for bonus
* @param _senderAddress address of the investor
* @param _senderValue amount of ETH contributed
*/
function _reserveGrise(
uint8[] memory _investmentDays,
address _referralAddress,
address _senderAddress,
uint256 _senderValue
)
internal
{
require(
_senderAddress != _referralAddress,
'GRISE: must be a different address'
);
require(
notContract(_referralAddress),
'GRISE: invalid referral address'
);
uint256 _investmentBalance = _referralAddress == address(0x0)
? _senderValue
: referralAmount[_referralAddress].add(_senderValue) > THRESHOLD_LIMIT_MAX
?_senderValue.mul(1100).div(1000)
:_senderValue.mul(10500).div(10000);
uint256 _totalDays = _investmentDays.length;
uint256 _dailyAmount = _investmentBalance.div(_totalDays);
uint256 _leftOver = _investmentBalance.mod(_totalDays);
_addBalance(
_senderAddress,
_investmentDays[0],
_dailyAmount.add(_leftOver)
);
for (uint8 _i = 1; _i < _totalDays; _i++) {
_addBalance(
_senderAddress,
_investmentDays[_i],
_dailyAmount
);
}
_trackInvestors(
_senderAddress,
_investmentBalance
);
if (_referralAddress != address(0x0)) {
_trackReferrals(_referralAddress, _senderValue);
emit ReferralAdded(
_referralAddress,
_senderAddress,
_senderValue
);
}
originalInvestment[_senderAddress] += _senderValue;
g.totalWeiContributed += _senderValue;
}
/** @notice Allocates investors balance to specific day
* @param _senderAddress investors wallet address
* @param _investmentDay selected investment day
* @param _investmentBalance amount invested (with bonus)
*/
function _addBalance(
address _senderAddress,
uint256 _investmentDay,
uint256 _investmentBalance
)
internal
{
if (investorBalances[_senderAddress][_investmentDay] == 0) {
investorAccounts[_investmentDay][investorAccountCount[_investmentDay]] = _senderAddress;
investorAccountCount[_investmentDay]++;
}
investorBalances[_senderAddress][_investmentDay] += _investmentBalance;
investorBalancesRecord[_senderAddress][_investmentDay] += _investmentBalance;
dailyTotalInvestment[_investmentDay] += _investmentBalance;
totalInvestment += _investmentBalance;
totalTransactions++;
emit GriseReservation(
_senderAddress,
_investmentDay,
_investmentBalance
);
}
// GRISE RESERVATION (PRIVATE FUNCTIONS) //
// ------------------------------------ //
/** @notice Tracks investorTotalBalance and uniqueInvestors
* @dev used in _reserveGrise() internal function
* @param _investorAddress address of the investor
* @param _value ETH amount invested (with bonus)
*/
function _trackInvestors(address _investorAddress, uint256 _value) private {
if (investorTotalBalance[_investorAddress] == 0) {
uniqueInvestors[uniqueInvestorCount] = _investorAddress;
uniqueInvestorCount++;
}
investorTotalBalance[_investorAddress] += _value;
}
/** @notice Tracks referralAmount and referralAccounts
* @dev used in _reserveGrise() internal function
* @param _referralAddress address of the referrer
* @param _value ETH amount referred during reservation
*/
function _trackReferrals(address _referralAddress, uint256 _value) private {
if (referralAmount[_referralAddress] == 0) {
referralAccounts[
referralAccountCount] = _referralAddress;
referralAccountCount++;
}
referralAmount[_referralAddress] += _value;
}
// SUPPLY GENERATION (EXTERNAL FUNCTION) //
// ------------------------------------- //
/** @notice Allows to generate supply for past funded days
* @param _investmentDay investemnt day index (1-50)
*/
function generateSupply(
uint64 _investmentDay
)
external
investmentDaysRange(_investmentDay)
onlyFundedDays(_investmentDay)
{
require(
_investmentDay < _currentLPDay(),
'GRISE: investment day must be in past'
);
require(
dailyTotalSupply[_investmentDay] == 0,
'GRISE: supply already generated'
);
DAILY_MAX_SUPPLY - dailyMinSupply[_investmentDay] == dailyMinSupply[_investmentDay]
? _generateStaticSupply(_investmentDay)
: _generateRandomSupply(_investmentDay);
}
// SUPPLY GENERATION (INTERNAL FUNCTIONS) //
// -------------------------------------- //
/** @notice Generates supply for days with static supply
* @param _investmentDay investemnt day index (1-50)
*/
function _generateStaticSupply(
uint256 _investmentDay
)
internal
{
dailyTotalSupply[_investmentDay] = dailyMinSupply[_investmentDay] * REI_PER_GRISE;
g.totalTransferTokens += dailyTotalSupply[_investmentDay];
g.generatedDays++;
emit GeneratedStaticSupply(
_investmentDay,
dailyTotalSupply[_investmentDay]
);
}
/** @notice Generates supply for days with random supply
* @dev uses nreAPI to request random number
* @param _investmentDay investemnt day index (1-50)
*/
function _generateRandomSupply(
uint256 _investmentDay
)
internal
{
uint256 ceilingDayMaxSupply = dailyMaxSupply[_investmentDay].sub(dailyMinSupply[_investmentDay]);
uint256 randomSupply = randomness.stateRandomNumber() % ceilingDayMaxSupply;
g.generatedDays = g.generatedDays + 1;
dailyTotalSupply[_investmentDay] = dailyMinSupply[_investmentDay]
.add(randomSupply)
.mul(REI_PER_GRISE);
g.totalTransferTokens = g.totalTransferTokens
.add(dailyTotalSupply[_investmentDay]);
emit GeneratedRandomSupply(
_investmentDay,
dailyTotalSupply[_investmentDay]
);
}
// PRE-LIQUIDITY GENERATION FUNCTION //
// --------------------------------- //
/** @notice Pre-calculates amount of tokens each referrer will get
* @dev must run this for all referrer addresses in batches
* converts _referralAmount to _referralTokens based on dailyRatio
*/
function prepareReferralBonuses(
uint256 _referralBatchFrom,
uint256 _referralBatchTo
)
external
afterInvestmentPhase
{
require(
_referralBatchFrom < _referralBatchTo,
'GRISE: incorrect referral batch'
);
require (
g.preparedReferrals < referralAccountCount,
'GRISE: all referrals already prepared'
);
uint256 _totalRatio = g.totalTransferTokens.div(g.totalWeiContributed);
for (uint256 i = _referralBatchFrom; i < _referralBatchTo; i++) {
address _referralAddress = referralAccounts[i];
uint256 _referralAmount = referralAmount[_referralAddress];
if (referralAmount[_referralAddress] > 0) {
referralAmount[_referralAddress] = 0;
if (_referralAmount >= THRESHOLD_LIMIT_MIN) {
_referralAmount >= THRESHOLD_LIMIT_MAX
? _fullReferralBonus(_referralAddress, _referralAmount, _totalRatio)
: _familyReferralBonus(_referralAddress, _referralAmount, _totalRatio);
g.totalReferralTokens = g.totalReferralTokens.add(
referralTokens[_referralAddress]
);
}
g.preparedReferrals++;
}
}
}
/** @notice performs token allocation for 10% of referral amount
* @dev after liquidity is formed referrer can withdraw this amount
*/
function _fullReferralBonus(address _referralAddress, uint256 _referralAmount, uint256 _ratio) internal {
referralTokens[_referralAddress] = _referralAmount.div(10).mul(_ratio);
}
/** @notice performs token allocation for 5% of referral amount
* @dev after liquidity is formed referrer can withdraw this amount
*/
function _familyReferralBonus(address _referralAddress, uint256 _referralAmount, uint256 _ratio) internal {
referralTokens[_referralAddress] = _referralAmount.div(20).mul(_ratio);
}
// LIQUIDITY GENERATION FUNCTION //
// ----------------------------- //
/** @notice Creates initial liquidity on Uniswap by forwarding
* reserved tokens equivalent to ETH contributed to the contract
* @dev check addLiquidityETH documentation
*/
function forwardLiquidity(/*🦄*/)
external
afterInvestmentPhase
{
require(
g.generatedDays == fundedDays(),
'GRISE: must generate supply for all days'
);
require (
g.preparedReferrals == referralAccountCount,
'GRISE: must prepare all referrals'
);
require (
g.totalTransferTokens > 0,
'GRISE: must have tokens to transfer'
);
uint256 _balance = g.totalWeiContributed;
uint256 _buffer = g.totalTransferTokens + g.totalReferralTokens;
uint256 _bounty = _buffer.mul(8).div(100);
_balance = _balance.sub(
_teamContribution(
_balance.mul(15).div(100)
)
);
_buffer = _buffer.mul(_balance).div(
g.totalWeiContributed
);
_bounty = _bounty.add(_buffer.mul(8).div(100));
GRISE_CONTRACT.mintSupply(
address(this), _buffer
);
GRISE_CONTRACT.mintSupply(
TEAM_ADDRESS, _bounty
);
GRISE_CONTRACT.approve(
address(UNISWAP_ROUTER), _buffer
);
(
uint256 amountToken,
uint256 amountETH,
uint256 liquidity
) =
UNISWAP_ROUTER.addLiquidityETH{value: _balance}(
address(GRISE_CONTRACT),
_buffer,
0,
0,
address(0x0),
block.timestamp.add(2 hours)
);
g.totalTransferTokens = 0;
g.totalReferralTokens = 0;
g.totalWeiContributed = 0;
emit UniSwapResult(
amountToken, amountETH, liquidity
);
}
// GRISE TOKEN PAYOUT FUNCTIONS (INDIVIDUAL) //
// ---------------------------------------- //
/** @notice Allows to mint all the tokens
* from investor and referrer perspectives
* @dev can be called after forwardLiquidity()
*/
function getMyTokens(/*💰*/)
external
afterUniswapTransfer
{
payoutInvestorAddress(msg.sender);
payoutReferralAddress(msg.sender);
}
/** @notice Allows to mint tokens for specific investor address
* @dev aggregades investors tokens across all investment days
* and uses GRISE_CONTRACT instance to mint all the GRISE tokens
* @param _investorAddress requested investor calculation address
* @return _payout amount minted to the investors address
*/
function payoutInvestorAddress(
address _investorAddress
)
public
afterUniswapTransfer
returns (uint256 _payout)
{
for (uint8 i = 1; i <= INVESTMENT_DAYS; i++) {
if (investorBalances[_investorAddress][i] > 0) {
_payout += investorBalances[_investorAddress][i].mul(
_calculateDailyRatio(i)
).div(100E18);
investorBalances[_investorAddress][i] = 0;
}
}
if (_payout > 0) {
GRISE_CONTRACT.mintSupply(
_investorAddress,
_payout
);
}
}
/** @notice Allows to mint tokens for specific referrer address
* @dev must be pre-calculated in prepareReferralBonuses()
* @param _referralAddress referrer payout address
* @return _referralTokens amount minted to the referrer address
*/
function payoutReferralAddress(
address _referralAddress
) public
afterUniswapTransfer
returns (uint256 _referralTokens)
{
_referralTokens = referralTokens[_referralAddress];
if (referralTokens[_referralAddress] > 0) {
referralTokens[_referralAddress] = 0;
GRISE_CONTRACT.mintSupply(
_referralAddress,
_referralTokens
);
}
}
// GRISE TOKEN PAYOUT FUNCTIONS (BATCHES) //
// ------------------------------------- //
/** @notice Allows to mint tokens for specific investment day
* recommended batch size is up to 50 addresses per call
* @param _investmentDay processing investment day
* @param _investorBatchFrom batch starting index
* @param _investorBatchTo bach finishing index
*/
function payoutInvestmentDayBatch(
uint256 _investmentDay,
uint256 _investorBatchFrom,
uint256 _investorBatchTo
)
external
afterUniswapTransfer
onlyFundedDays(_investmentDay)
{
require(
_investorBatchFrom < _investorBatchTo,
'GRISE: incorrect investment batch'
);
uint256 _dailyRatio = _calculateDailyRatio(_investmentDay);
for (uint256 i = _investorBatchFrom; i < _investorBatchTo; i++) {
address _investor = investorAccounts[_investmentDay][i];
uint256 _balance = investorBalances[_investor][_investmentDay];
uint256 _payout = _balance.mul(_dailyRatio).div(100E18);
if (investorBalances[_investor][_investmentDay] > 0) {
investorBalances[_investor][_investmentDay] = 0;
GRISE_CONTRACT.mintSupply(
_investor,
_payout
);
}
}
}
/** @notice Allows to mint tokens for referrers in batches
* @dev can be called right after forwardLiquidity()
* recommended batch size is up to 50 addresses per call
* @param _referralBatchFrom batch starting index
* @param _referralBatchTo bach finishing index
*/
function payoutReferralBatch(
uint256 _referralBatchFrom,
uint256 _referralBatchTo
)
external
afterUniswapTransfer
{
require(
_referralBatchFrom < _referralBatchTo,
'GRISE: incorrect referral batch'
);
for (uint256 i = _referralBatchFrom; i < _referralBatchTo; i++) {
address _referralAddress = referralAccounts[i];
uint256 _referralTokens = referralTokens[_referralAddress];
if (referralTokens[_referralAddress] > 0) {
referralTokens[_referralAddress] = 0;
GRISE_CONTRACT.mintSupply(
_referralAddress,
_referralTokens
);
}
}
}
// INFO VIEW FUNCTIONS (PERSONAL) //
// ------------------------------ //
/** @notice checks for callers investment amount on specific day (with bonus)
* @return total amount invested across specific investment day (with bonus)
*/
function myInvestmentAmount(uint256 _investmentDay) external view returns (uint256) {
return investorBalances[msg.sender][_investmentDay];
}
/** @notice checks for callers claimable amount on specific day (with bonus)
* @return total amount claimable across specific investment day (with bonus)
*/
function myClaimAmount(uint256 _investmentDay) external view returns (uint256) {
if (investorBalances[msg.sender][_investmentDay] > 0) {
return investorBalances[msg.sender][_investmentDay].mul(
_calculateDailyRatio(_investmentDay)).div(100E18);
}else{
return 0;
}
}
/** @notice checks for callers investment amount on each day (with bonus)
* @return _myAllDays total amount invested across all days (with bonus)
*/
function myInvestmentAmountAllDays() external view returns (uint256[51] memory _myAllDays) {
for (uint256 i = 1; i <= INVESTMENT_DAYS; i++) {
_myAllDays[i] = investorBalances[msg.sender][i];
}
}
/** @notice checks for callers total investment amount (with bonus)
* @return total amount invested across all investment days (with bonus)
*/
function myTotalInvestmentAmount() external view returns (uint256) {
return investorTotalBalance[msg.sender];
}
/** @notice checks for callers total claimable amount (with refferal bonus)
* @return total claimable amount across all investment days (with refferal bonus)
*/
function myClaimAmountAllDays() external view returns (uint256) {
uint256 _payout;
for (uint256 i = 1; i <= INVESTMENT_DAYS; i++) {
if (investorBalances[msg.sender][i] > 0) {
_payout += investorBalances[msg.sender][i].mul(
_calculateDailyRatio(i)
).div(100E18);
}
}
return _payout + referralTokens[msg.sender];
}
// INFO VIEW FUNCTIONS (GLOBAL) //
// ---------------------------- //
/** @notice checks for investors count on specific day
* @return investors count for specific day
*/
function investorsOnDay(uint256 _investmentDay) public view returns (uint256) {
return dailyTotalInvestment[_investmentDay] > 0 ? investorAccountCount[_investmentDay] : 0;
}
/** @notice checks for investors count on each day
* @return _allInvestors array with investors count for each day
*/
function investorsOnAllDays() external view returns (uint256[51] memory _allInvestors) {
for (uint256 i = 1; i <= INVESTMENT_DAYS; i++) {
_allInvestors[i] = investorsOnDay(i);
}
}
/** @notice checks for investment amount on each day
* @return _allInvestments array with investment amount for each day
*/
function investmentsOnAllDays() external view returns (uint256[51] memory _allInvestments) {
for (uint256 i = 1; i <= INVESTMENT_DAYS; i++) {
_allInvestments[i] = dailyTotalInvestment[i];
}
}
/** @notice checks for supply amount on each day
* @return _allSupply array with supply amount for each day
*/
function supplyOnAllDays() external view returns (uint256[51] memory _allSupply) {
for (uint256 i = 1; i <= INVESTMENT_DAYS; i++) {
_allSupply[i] = dailyTotalSupply[i];
}
}
// HELPER FUNCTIONS (PURE) //
// ----------------------- //
/** @notice checks that provided days are valid for investemnt
* @dev used in reserveGrise() and reserveGriseWithToken()
*/
function checkInvestmentDays(
uint8[] memory _investmentDays,
uint64 _griseDay,
address _senderAddress,
uint256 _senderValue
)
internal
{
uint256 _totalDays = _investmentDays.length;
uint256 _dailyAmount = _senderValue.div(_totalDays);
for (uint8 _i = 0; _i < _investmentDays.length; _i++) {
require(
(_dailyAmount >= MIN_INVEST) || (investorBalances[_senderAddress][_investmentDays[_i]] > 0),
'GRISE: investment below minimum'
);
require(
_investmentDays[_i] >= _griseDay,
'GRISE: investment day already passed'
);
require(
_investmentDays[_i] > 0 &&
_investmentDays[_i] <= INVESTMENT_DAYS,
'GRISE: incorrect investment day'
);
require(
(dailySlots[_investmentDays[_i]] < MAX_DAY_SLOT) ||
(investorBalances[_senderAddress][_investmentDays[_i]] > 0)
,
'GRISE: investment slots are not available'
);
if(investorBalances[_senderAddress][_investmentDays[_i]] == 0){
dailySlots[_investmentDays[_i]]++;
}
}
}
/** @notice prepares path variable for uniswap to exchange tokens
* @dev used in reserveGriseWithToken() swapExactTokensForETH call
* @param _tokenAddress ERC20 token address to be swapped for ETH
* @return _path that is used to swap tokens for ETH on uniswap
*/
function preparePath(
address _tokenAddress
) internal pure returns (
address[] memory _path
) {
_path = new address[](2);
_path[0] = _tokenAddress;
_path[1] = WETH;
}
/** @notice keeps team contribution
* @dev subtracts amount during forwardLiquidity()
* @return ETH amount the team is allowed to withdraw
*/
function _teamContribution(
uint256 _teamAmount
) internal returns (uint256) {
TEAM_ETHER = _teamAmount;
return _teamAmount;
}
/** @notice checks for invesments on all days
* @dev used in forwardLiquidity() requirements
* @return $fundedDays - amount of funded days 0-50
*/
function fundedDays() public view returns (
uint8 $fundedDays
) {
for (uint8 i = 1; i <= INVESTMENT_DAYS; i++) {
if (dailyTotalInvestment[i] > 0) $fundedDays++;
}
}
/** @notice GRISE equivalent in ETH price calculation
* @dev returned value has 100E18 precision - divided later on
* @return token price for specific day based on total investement
*/
function _calculateDailyRatio(
uint256 _investmentDay
) internal view returns (uint256) {
uint256 dailyRatio = dailyTotalSupply[_investmentDay].mul(100E18)
.div(dailyTotalInvestment[_investmentDay]);
uint256 remainderCheck = dailyTotalSupply[_investmentDay].mul(100E18)
.mod(dailyTotalInvestment[_investmentDay]);
return remainderCheck == 0 ? dailyRatio : dailyRatio.add(1);
}
// TIMING FUNCTIONS //
// ---------------- //
/** @notice shows current slot of GriseToken
* @dev value is fetched from GRISE_CONTRACT
* @return iteration day since GRISE inception
*/
function _currentLPDay() public view returns (uint64) {
return GRISE_CONTRACT.currentLPDay();
}
/** @notice allows to withdraw team funds for the work
* strictly only after the uniswap liquidity is formed
*/
function requestTeamFunds()
external
afterUniswapTransfer
{
TEAM_ADDRESS.transfer(TEAM_ETHER.mul(4).div(5));
DEV_ADDRESS.transfer(TEAM_ETHER.div(5));
}
function notContract(address _addr) internal view returns (bool) {
uint32 size;
assembly {
size := extcodesize(_addr)
}
return (size == 0);
}
}
library SafeMathLT {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, 'GRISE: addition overflow');
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, 'GRISE: subtraction overflow');
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, 'GRISE: multiplication overflow');
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, 'GRISE: division by zero');
uint256 c = a / b;
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, 'GRISE: modulo by zero');
return a % b;
}
} | * @notice checks for invesments on all days @dev used in forwardLiquidity() requirements @return $fundedDays - amount of funded days 0-50/ | function fundedDays() public view returns (
uint8 $fundedDays
) {
for (uint8 i = 1; i <= INVESTMENT_DAYS; i++) {
if (dailyTotalInvestment[i] > 0) $fundedDays++;
}
}
| 1,197,618 | [
1,
12366,
364,
2198,
281,
1346,
603,
777,
4681,
225,
1399,
316,
5104,
48,
18988,
24237,
1435,
8433,
327,
271,
12125,
785,
9384,
300,
3844,
434,
9831,
785,
4681,
374,
17,
3361,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
9831,
785,
9384,
1435,
1071,
1476,
1135,
261,
203,
3639,
2254,
28,
271,
12125,
785,
9384,
203,
565,
262,
288,
203,
3639,
364,
261,
11890,
28,
277,
273,
404,
31,
277,
1648,
2120,
3412,
882,
3212,
67,
31551,
31,
277,
27245,
288,
203,
5411,
309,
261,
26790,
5269,
3605,
395,
475,
63,
77,
65,
405,
374,
13,
271,
12125,
785,
9384,
9904,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0x9965cCd16803432C6a0842f1D5690f32E427aEDd/sources/contracts/DutchMarketplace.sol | Sale Currently Active
| return CurrentPrice; | 8,471,105 | [
1,
30746,
15212,
8857,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
327,
6562,
5147,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// 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(uint a, uint b) internal pure returns (uint) {
uint c = a + b;
require(c >= a, "add: +");
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(uint a, uint b, string memory errorMessage) internal pure returns (uint) {
uint 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(uint a, uint b) internal pure returns (uint) {
return sub(a, b, "sub: -");
}
/**
* @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(uint a, uint b, string memory errorMessage) internal pure returns (uint) {
require(b <= a, errorMessage);
uint 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(uint a, uint b) internal pure returns (uint) {
// 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;
}
uint c = a * b;
require(c / a == b, "mul: *");
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint a, uint b, string memory errorMessage) internal pure returns (uint) {
// 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;
}
uint 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(uint a, uint b) internal pure returns (uint) {
return div(a, b, "div: /");
}
/**
* @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(uint a, uint b, string memory errorMessage) internal pure returns (uint) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint 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(uint a, uint b) internal pure returns (uint) {
return mod(a, b, "mod: %");
}
/**
* @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(uint a, uint b, string memory errorMessage) internal pure returns (uint) {
require(b != 0, errorMessage);
return a % b;
}
}
/**
* @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].
*/
contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor () internal {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
/**
* @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 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");
// solhint-disable-next-line avoid-call-value
(bool success, ) = recipient.call{value:amount}("");
require(success, "Address: reverted");
}
}
/**
* @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: < 0");
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: !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: !succeed");
}
}
}
library Keep3rV1Library {
function getReserve(address pair, address reserve) external view returns (uint) {
(uint _r0, uint _r1,) = IUniswapV2Pair(pair).getReserves();
if (IUniswapV2Pair(pair).token0() == reserve) {
return _r0;
} else if (IUniswapV2Pair(pair).token1() == reserve) {
return _r1;
} else {
return 0;
}
}
}
interface IUniswapV2Pair {
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);
}
interface IGovernance {
function proposeJob(address job) external;
}
interface IKeep3rV1Helper {
function getQuoteLimit(uint gasUsed) external view returns (uint);
}
// File: contracts/Keep3r.sol
pragma solidity ^0.6.6;
contract Relay3rV1 is ReentrancyGuard {
using SafeMath for uint;
using SafeERC20 for IERC20;
/// @notice Keep3r Helper to set max prices for the ecosystem
IKeep3rV1Helper public KPRH;
/// @notice EIP-20 token name for this token
string public constant name = "Relay3rV1";
/// @notice EIP-20 token symbol for this token
string public constant symbol = "RL3R";
/// @notice EIP-20 token decimals for this token
uint8 public constant decimals = 18;
/// @notice Total number of tokens in circulation
uint public totalSupply = 0; // Initial 0
/// @notice A record of each accounts delegate
mapping (address => address) public delegates;
/// @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;
mapping (address => mapping (address => uint)) internal allowances;
mapping (address => uint) internal balances;
/// @notice The EIP-712 typehash for the contract's domain
bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint chainId,address verifyingContract)");
bytes32 public immutable DOMAINSEPARATOR;
/// @notice The EIP-712 typehash for the delegation struct used by the contract
bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint nonce,uint 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,uint value,uint nonce,uint deadline)");
/// @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 A checkpoint for marking number of votes from a given block
struct Checkpoint {
uint32 fromBlock;
uint votes;
}
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegatee The address to delegate votes to
*/
function delegate(address delegatee) public {
_delegate(msg.sender, delegatee);
}
/**
* @notice Delegates votes from signatory to `delegatee`
* @param delegatee The address to delegate votes to
* @param nonce The contract state required to match the signature
* @param expiry The time at which to expire the signature
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/
function delegateBySig(address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s) public {
bytes32 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), "delegateBySig: sig");
require(nonce == nonces[signatory]++, "delegateBySig: nonce");
require(now <= expiry, "delegateBySig: expired");
_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 (uint) {
uint32 nCheckpoints = numCheckpoints[account];
return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
}
/**
* @notice Determine the prior number of votes for an account as of a block number
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param account The address of the account to check
* @param blockNumber The block number to get the vote balance at
* @return The number of votes the account had as of the given block
*/
function getPriorVotes(address account, uint blockNumber) public view returns (uint) {
require(blockNumber < block.number, "getPriorVotes:");
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];
uint delegatorBalance = votes[delegator].add(bonds[delegator][address(this)]);
delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveDelegates(currentDelegate, delegatee, delegatorBalance);
}
function _moveDelegates(address srcRep, address dstRep, uint amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
uint32 srcRepNum = numCheckpoints[srcRep];
uint srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint srcRepNew = srcRepOld.sub(amount, "_moveVotes: underflows");
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
uint32 dstRepNum = numCheckpoints[dstRep];
uint dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint dstRepNew = dstRepOld.add(amount);
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _writeCheckpoint(address delegatee, uint32 nCheckpoints, uint oldVotes, uint newVotes) internal {
uint32 blockNumber = safe32(block.number, "_writeCheckpoint: 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);
}
/// @notice The standard EIP-20 transfer event
event Transfer(address indexed from, address indexed to, uint amount);
/// @notice The standard EIP-20 approval event
event Approval(address indexed owner, address indexed spender, uint amount);
/// @notice Submit a job
event SubmitJob(address indexed job, address indexed liquidity, address indexed provider, uint block, uint credit);
/// @notice Apply credit to a job
event ApplyCredit(address indexed job, address indexed liquidity, address indexed provider, uint block, uint credit);
/// @notice Remove credit for a job
event RemoveJob(address indexed job, address indexed liquidity, address indexed provider, uint block, uint credit);
/// @notice Unbond credit for a job
event UnbondJob(address indexed job, address indexed liquidity, address indexed provider, uint block, uint credit);
/// @notice Added a Job
event JobAdded(address indexed job, uint block, address governance);
/// @notice Removed a job
event JobRemoved(address indexed job, uint block, address governance);
/// @notice Worked a job
event KeeperWorked(address indexed credit, address indexed job, address indexed keeper, uint block);
/// @notice Keeper bonding
event KeeperBonding(address indexed keeper, uint block, uint active, uint bond);
/// @notice Keeper bonded
event KeeperBonded(address indexed keeper, uint block, uint activated, uint bond);
/// @notice Keeper unbonding
event KeeperUnbonding(address indexed keeper, uint block, uint deactive, uint bond);
/// @notice Keeper unbound
event KeeperUnbound(address indexed keeper, uint block, uint deactivated, uint bond);
/// @notice Keeper slashed
event KeeperSlashed(address indexed keeper, address indexed slasher, uint block, uint slash);
/// @notice Keeper disputed
event KeeperDispute(address indexed keeper, uint block);
/// @notice Keeper resolved
event KeeperResolved(address indexed keeper, uint block);
event AddCredit(address indexed credit, address indexed job, address indexed creditor, uint block, uint amount);
/// @notice Keeper rights approved to be spent by spender
event KeeperRightApproval(address indexed owner, address indexed spender, bool allowed);
/// @notice Keeper right transfered to a new address
event KeeperRightTransfered(address indexed from, address indexed to, address indexed bond);
/// @notice 3 days to bond to become a keeper
uint public BOND = 3 days;
/// @notice 14 days to unbond to remove funds from being a keeper
uint public UNBOND = 14 days;
/// @notice 3 days till liquidity can be bound
uint public LIQUIDITYBOND = 3 days;
/// @notice direct liquidity fee 0.3%,Can be modified by governance contract
uint public FEE = 30;
uint constant public BASE = 10000;
/// @notice address used for ETH transfers
address constant public ETH = address(0xE);
/// @notice tracks all current bondings (time)
mapping(address => mapping(address => uint)) public bondings;
/// @notice tracks all current unbondings (time)
mapping(address => mapping(address => uint)) public unbondings;
/// @notice allows for partial unbonding
mapping(address => mapping(address => uint)) public partialUnbonding;
/// @notice tracks all current pending bonds (amount)
mapping(address => mapping(address => uint)) public pendingbonds;
/// @notice tracks how much a keeper has bonded
mapping(address => mapping(address => uint)) public bonds;
/// @notice tracks underlying votes (that don't have bond)
mapping(address => uint) public votes;
/// @notice total bonded (totalSupply for bonds)
uint public totalBonded = 0;
/// @notice tracks when a keeper was first registered
mapping(address => uint) public firstSeen;
/// @notice tracks if a keeper has a pending dispute
mapping(address => bool) public disputes;
/// @notice tracks last job performed for a keeper
mapping(address => uint) public lastJob;
/// @notice tracks the total job executions for a keeper
mapping(address => uint) public workCompleted;
/// @notice list of all jobs registered for the keeper system
mapping(address => bool) public jobs;
/// @notice the current credit available for a job
mapping(address => mapping(address => uint)) public credits;
/// @notice the balances for the liquidity providers
mapping(address => mapping(address => mapping(address => uint))) public liquidityProvided;
/// @notice liquidity unbonding days
mapping(address => mapping(address => mapping(address => uint))) public liquidityUnbonding;
/// @notice liquidity unbonding amounts
mapping(address => mapping(address => mapping(address => uint))) public liquidityAmountsUnbonding;
/// @dev job proposal delay
mapping(address => uint) internal jobProposalDelayInternal;
/// @notice liquidity apply date
mapping(address => mapping(address => mapping(address => uint))) public liquidityApplied;
/// @notice liquidity amount to apply
mapping(address => mapping(address => mapping(address => uint))) public liquidityAmount;
/// @notice list of all current keepers
mapping(address => bool) public keepers;
/// @notice blacklist of keepers not allowed to participate
mapping(address => bool) public blacklist;
mapping(address => mapping (address => bool)) internal KeeperAllowances;
mapping(address => mapping (address => mapping(address => bool))) internal KeeperAllowancesPassed;
/// @notice traversable array of keepers to make external management easier
address[] public keeperList;
/// @notice traversable array of jobs to make external management easier
address[] public jobList;
/// @notice governance address for the governance contract
address public governance;
address public pendingGovernance;
/// @notice the liquidity token supplied by users paying for jobs
mapping(address => bool) public liquidityAccepted;
address[] public liquidityPairs;
uint internal _gasUsed;
constructor() public {
// Set governance for this token
governance = msg.sender;
DOMAINSEPARATOR = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), _getChainId(), address(this)));
}
modifier onlyGovernance(){
require(msg.sender == governance);
_;
}
/**
* @notice Add ETH credit to a job to be paid out for work
* @param job the job being credited
*/
function addCreditETH(address job) external payable {
require(jobs[job], "addCreditETH: !job");
uint _fee = msg.value.mul(FEE).div(BASE);
credits[job][ETH] = credits[job][ETH].add(msg.value.sub(_fee));
payable(governance).transfer(_fee);
emit AddCredit(ETH, job, msg.sender, block.number, msg.value);
}
/**
* @notice Add credit to a job to be paid out for work
* @param credit the credit being assigned to the job
* @param job the job being credited
* @param amount the amount of credit being added to the job
*/
function addCredit(address credit, address job, uint amount) external nonReentrant {
require(jobs[job], "addCreditETH: !job");
uint _before = IERC20(credit).balanceOf(address(this));
IERC20(credit).safeTransferFrom(msg.sender, address(this), amount);
uint _received = IERC20(credit).balanceOf(address(this)).sub(_before);
uint _fee = _received.mul(FEE).div(BASE);
credits[job][credit] = credits[job][credit].add(_received.sub(_fee));
IERC20(credit).safeTransfer(governance, _fee);
emit AddCredit(credit, job, msg.sender, block.number, _received);
}
/**
* @notice Add non transferable votes for governance
* @param voter to add the votes to
* @param amount of votes to add
*/
function addVotes(address voter, uint amount) external onlyGovernance{
votes[voter] = votes[voter].add(amount);
totalBonded = totalBonded.add(amount);
_moveDelegates(address(0), delegates[voter], amount);
}
/**
* @notice Remove non transferable votes for governance
* @param voter to subtract the votes
* @param amount of votes to remove
*/
function removeVotes(address voter, uint amount) external onlyGovernance{
votes[voter] = votes[voter].sub(amount);
totalBonded = totalBonded.sub(amount);
_moveDelegates(delegates[voter], address(0), amount);
}
/**
* @notice Add credit to a job to be paid out for work
* @param job the job being credited
* @param amount the amount of credit being added to the job
*/
function addRLRCredit(address job, uint amount) external onlyGovernance{
require(jobs[job], "addRLRCredit: !job");
credits[job][address(this)] = credits[job][address(this)].add(amount);
emit AddCredit(address(this), job, msg.sender, block.number, amount);
}
/**
* @notice Approve a liquidity pair for being accepted in future
* @param liquidity the liquidity no longer accepted
*/
function approveLiquidity(address liquidity) external onlyGovernance{
require(!liquidityAccepted[liquidity], "approveLiquidity: !pair");
liquidityAccepted[liquidity] = true;
liquidityPairs.push(liquidity);
}
/**
* @notice Revoke a liquidity pair from being accepted in future
* @param liquidity the liquidity no longer accepted
*/
function revokeLiquidity(address liquidity) external onlyGovernance{
liquidityAccepted[liquidity] = false;
}
/**
* @notice Set new liquidity fee from governance
* @param newFee the new fee for further liquidity adds
*/
function setLiquidityFee(uint newFee) external onlyGovernance{
FEE = newFee;
}
/**
* @notice Set bonding delay from governance
* @param newBond the new bonding delay
*/
function setBondingDelay(uint newBond) external onlyGovernance{
BOND = newBond;
}
/**
* @notice Set bonding delay from governance
* @param newUnbond the new unbonding delay
*/
function setUnbondingDelay(uint newUnbond) external onlyGovernance{
UNBOND = newUnbond;
}
/**
* @notice Set liquidity bonding delay from governance
* @param newLiqBond the new liquidity bonding delay
*/
function setLiquidityBondingDelay(uint newLiqBond) external onlyGovernance{
LIQUIDITYBOND = newLiqBond;
}
/**
* @notice Displays all accepted liquidity pairs
*/
function pairs() external view returns (address[] memory) {
return liquidityPairs;
}
/**
* @notice Gets the job proposal delay with the current unbound delay
*/
function jobProposalDelay(address job) public view returns (uint){
return jobProposalDelayInternal[job].add(UNBOND);
}
/**
* @notice Allows liquidity providers to submit jobs
* @param liquidity the liquidity being added
* @param job the job to assign credit to
* @param amount the amount of liquidity tokens to use
*/
function addLiquidityToJob(address liquidity, address job, uint amount) external nonReentrant {
require(liquidityAccepted[liquidity], "addLiquidityToJob: !pair");
IERC20(liquidity).safeTransferFrom(msg.sender, address(this), amount);
liquidityProvided[msg.sender][liquidity][job] = liquidityProvided[msg.sender][liquidity][job].add(amount);
liquidityApplied[msg.sender][liquidity][job] = now;
liquidityAmount[msg.sender][liquidity][job] = liquidityAmount[msg.sender][liquidity][job].add(amount);
if (!jobs[job] && jobProposalDelay(job) < now) {
IGovernance(governance).proposeJob(job);
jobProposalDelayInternal[job] = now;
}
emit SubmitJob(job, liquidity, msg.sender, block.number, amount);
}
/**
* @notice Applies the credit provided in addLiquidityToJob to the job
* @param provider the liquidity provider
* @param liquidity the pair being added as liquidity
* @param job the job that is receiving the credit
*/
function applyCreditToJob(address provider, address liquidity, address job) external {
require(liquidityAccepted[liquidity], "applyCreditToJob: !pair");
require(liquidityApplied[provider][liquidity][job] != 0, "credit: no bond");
require(block.timestamp.sub(liquidityApplied[provider][liquidity][job].add(LIQUIDITYBOND)) >= 0, "credit: bonding");
uint _liquidity = Keep3rV1Library.getReserve(liquidity, address(this));
uint _credit = _liquidity.mul(liquidityAmount[provider][liquidity][job]).div(IERC20(liquidity).totalSupply());
_mint(address(this), _credit);
credits[job][address(this)] = credits[job][address(this)].add(_credit);
liquidityAmount[provider][liquidity][job] = 0;
emit ApplyCredit(job, liquidity, provider, block.number, _credit);
}
/**
* @notice Unbond liquidity for a job
* @param liquidity the pair being unbound
* @param job the job being unbound from
* @param amount the amount of liquidity being removed
*/
function unbondLiquidityFromJob(address liquidity, address job, uint amount) external {
require(liquidityAmount[msg.sender][liquidity][job] == 0, "credit: pending credit");
liquidityUnbonding[msg.sender][liquidity][job] = now;
liquidityAmountsUnbonding[msg.sender][liquidity][job] = liquidityAmountsUnbonding[msg.sender][liquidity][job].add(amount);
require(liquidityAmountsUnbonding[msg.sender][liquidity][job] <= liquidityProvided[msg.sender][liquidity][job], "unbondLiquidityFromJob: insufficient funds");
uint _liquidity = Keep3rV1Library.getReserve(liquidity, address(this));
uint _credit = _liquidity.mul(amount).div(IERC20(liquidity).totalSupply());
if (_credit > credits[job][address(this)]) {
_burn(address(this), credits[job][address(this)]);
credits[job][address(this)] = 0;
} else {
_burn(address(this), _credit);
credits[job][address(this)] = credits[job][address(this)].sub(_credit);
}
emit UnbondJob(job, liquidity, msg.sender, block.number, amount);
}
/**
* @notice Allows liquidity providers to remove liquidity
* @param liquidity the pair being unbound
* @param job the job being unbound from
*/
function removeLiquidityFromJob(address liquidity, address job) external {
require(liquidityUnbonding[msg.sender][liquidity][job] != 0, "removeJob: unbond");
require(block.timestamp.sub(liquidityUnbonding[msg.sender][liquidity][job].add(UNBOND)) >= 0, "removeJob: unbonding");
uint _amount = liquidityAmountsUnbonding[msg.sender][liquidity][job];
liquidityProvided[msg.sender][liquidity][job] = liquidityProvided[msg.sender][liquidity][job].sub(_amount);
liquidityAmountsUnbonding[msg.sender][liquidity][job] = 0;
IERC20(liquidity).safeTransfer(msg.sender, _amount);
emit RemoveJob(job, liquidity, msg.sender, block.number, _amount);
}
/**
* @notice Allows governance to mint new tokens to treasury
* @param amount the amount of tokens to mint to treasury
*/
function mint(uint amount) external onlyGovernance{
_mint(governance, amount);
}
/**
* @notice burn owned tokens
* @param amount the amount of tokens to burn
*/
function burn(uint amount) external {
_burn(msg.sender, amount);
}
function _mint(address dst, uint amount) internal {
// mint the amount
totalSupply = totalSupply.add(amount);
// transfer the amount to the recipient
balances[dst] = balances[dst].add(amount);
emit Transfer(address(0), dst, amount);
}
function _burn(address dst, uint amount) internal {
require(dst != address(0), "_burn: zero address");
balances[dst] = balances[dst].sub(amount, "_burn: exceeds balance");
totalSupply = totalSupply.sub(amount);
emit Transfer(dst, address(0), amount);
}
/**
* @notice Implemented by jobs to show that a keeper performed work
* @param keeper address of the keeper that performed the work
*/
function worked(address keeper) external {
workReceipt(keeper, KPRH.getQuoteLimit(_gasUsed.sub(gasleft())));
}
/**
* @notice Implemented by jobs to show that a keeper performed work and get paid in ETH
* @param keeper address of the keeper that performed the work
*/
function workedETH(address keeper) external {
receiptETH(keeper, KPRH.getQuoteLimit(_gasUsed.sub(gasleft())));
}
/**
* @notice Implemented by jobs to show that a keeper performed work
* @param keeper address of the keeper that performed the work
* @param amount the reward that should be allocated
*/
function workReceipt(address keeper, uint amount) public {
require(jobs[msg.sender], "workReceipt: !job");
require(amount <= KPRH.getQuoteLimit(_gasUsed.sub(gasleft())), "workReceipt: max limit");
credits[msg.sender][address(this)] = credits[msg.sender][address(this)].sub(amount, "workReceipt: insuffcient funds");
lastJob[keeper] = now;
_bond(address(this), keeper, amount);
workCompleted[keeper] = workCompleted[keeper].add(amount);
emit KeeperWorked(address(this), msg.sender, keeper, block.number);
}
/**
* @notice Implemented by jobs to show that a keeper performed work
* @param credit the asset being awarded to the keeper
* @param keeper address of the keeper that performed the work
* @param amount the reward that should be allocated
*/
function receipt(address credit, address keeper, uint amount) external {
require(jobs[msg.sender], "receipt: !job");
credits[msg.sender][credit] = credits[msg.sender][credit].sub(amount, "workReceipt: insuffcient funds");
lastJob[keeper] = now;
IERC20(credit).safeTransfer(keeper, amount);
emit KeeperWorked(credit, msg.sender, keeper, block.number);
}
/**
* @notice Implemented by jobs to show that a keeper performed work
* @param keeper address of the keeper that performed the work
* @param amount the amount of ETH sent to the keeper
*/
function receiptETH(address keeper, uint amount) public {
require(jobs[msg.sender], "receipt: !job");
credits[msg.sender][ETH] = credits[msg.sender][ETH].sub(amount, "workReceipt: insuffcient funds");
lastJob[keeper] = now;
payable(keeper).transfer(amount);
emit KeeperWorked(ETH, msg.sender, keeper, block.number);
}
function _bond(address bonding, address _from, uint _amount) internal {
bonds[_from][bonding] = bonds[_from][bonding].add(_amount);
if (bonding == address(this)) {
totalBonded = totalBonded.add(_amount);
_moveDelegates(address(0), delegates[_from], _amount);
}
}
function _unbond(address bonding, address _from, uint _amount) internal {
bonds[_from][bonding] = bonds[_from][bonding].sub(_amount);
if (bonding == address(this)) {
totalBonded = totalBonded.sub(_amount);
_moveDelegates(delegates[_from], address(0), _amount);
}
}
/**
* @notice Allows governance to add new job systems
* @param job address of the contract for which work should be performed
*/
function addJob(address job) external onlyGovernance{
require(!jobs[job], "addJob: job known");
jobs[job] = true;
jobList.push(job);
emit JobAdded(job, block.number, msg.sender);
}
/**
* @notice Full listing of all jobs ever added
* @return array blob
*/
function getJobs() external view returns (address[] memory) {
return jobList;
}
/**
* @notice Allows governance to remove a job from the systems
* @param job address of the contract for which work should be performed
*/
function removeJob(address job) external onlyGovernance{
jobs[job] = false;
emit JobRemoved(job, block.number, msg.sender);
}
/**
* @notice Allows governance to change the Keep3rHelper for max spend
* @param _kprh new helper address to set
*/
function setKeep3rHelper(address _kprh) external onlyGovernance{
KPRH = IKeep3rV1Helper(_kprh);
}
/**
* @notice Allows governance to change governance (for future upgradability)
* @param _governance new governance address to set
*/
function setGovernance(address _governance) external onlyGovernance{
pendingGovernance = _governance;
}
/**
* @notice Allows pendingGovernance to accept their role as governance (protection pattern)
*/
function acceptGovernance() external {
require(msg.sender == pendingGovernance, "acceptGovernance: !pendingGov");
governance = pendingGovernance;
}
/**
* @notice confirms if the current keeper is registered, can be used for general (non critical) functions
* @param keeper the keeper being investigated
* @return true/false if the address is a keeper
*/
function isKeeper(address keeper) public returns (bool) {
_gasUsed = gasleft();
return keepers[keeper];
}
/**
* @notice confirms if the current keeper is registered and has a minimum bond, should be used for protected functions
* @param keeper the keeper being investigated
* @param minBond the minimum requirement for the asset provided in bond
* @param earned the total funds earned in the keepers lifetime
* @param age the age of the keeper in the system
* @return true/false if the address is a keeper and has more than the bond
*/
function isMinKeeper(address keeper, uint minBond, uint earned, uint age) external returns (bool) {
_gasUsed = gasleft();
return keepers[keeper]
&& bonds[keeper][address(this)].add(votes[keeper]) >= minBond
&& workCompleted[keeper] >= earned
&& now.sub(firstSeen[keeper]) >= age;
}
/**
* @notice confirms if the current keeper is registered and has a minimum bond, should be used for protected functions
* @param keeper the keeper being investigated
* @param bond the bound asset being evaluated
* @param minBond the minimum requirement for the asset provided in bond
* @param earned the total funds earned in the keepers lifetime
* @param age the age of the keeper in the system
* @return true/false if the address is a keeper and has more than the bond
*/
function isBondedKeeper(address keeper, address bond, uint minBond, uint earned, uint age) external returns (bool) {
_gasUsed = gasleft();
return keepers[keeper]
&& bonds[keeper][bond] >= minBond
&& workCompleted[keeper] >= earned
&& now.sub(firstSeen[keeper]) >= age;
}
/**
* @notice begin the bonding process for a new keeper
* @param bonding the asset being bound
* @param amount the amount of bonding asset being bound
*/
function bond(address bonding, uint amount) external nonReentrant {
require(!blacklist[msg.sender], "bond: blacklisted");
//In this part we changed the addition of current time + bond time to the time bond was called
bondings[msg.sender][bonding] = now;
if (bonding == address(this)) {
_transferTokens(msg.sender, address(this), amount);
} else {
uint _before = IERC20(bonding).balanceOf(address(this));
IERC20(bonding).safeTransferFrom(msg.sender, address(this), amount);
amount = IERC20(bonding).balanceOf(address(this)).sub(_before);
}
pendingbonds[msg.sender][bonding] = pendingbonds[msg.sender][bonding].add(amount);
emit KeeperBonding(msg.sender, block.number, bondings[msg.sender][bonding], amount);
}
/**
* @notice get full list of keepers in the system
*/
function getKeepers() external view returns (address[] memory) {
return keeperList;
}
/**
* @notice Does initial data initialization of keeper entry
* @param sender the address to init data for
*/
function doDataInit(address sender) internal {
if (firstSeen[sender] == 0) {
firstSeen[sender] = now;
keeperList.push(sender);
lastJob[sender] = now;
}
}
/**
* @notice allows a keeper to activate/register themselves after bonding
* @param bonding the asset being activated as bond collateral
*/
function activate(address bonding) external {
require(!blacklist[msg.sender], "activate: blacklisted");
//In this part we changed the check of bonding time being lesser than now to check if current time is > bonding time
require(bondings[msg.sender][bonding] != 0 && block.timestamp.sub(bondings[msg.sender][bonding].add(BOND)) >= 0, "activate: bonding");
//Setup initial data
doDataInit(msg.sender);
keepers[msg.sender] = true;
_bond(bonding, msg.sender, pendingbonds[msg.sender][bonding]);
pendingbonds[msg.sender][bonding] = 0;
emit KeeperBonded(msg.sender, block.number, block.timestamp, bonds[msg.sender][bonding]);
}
function doKeeperrightChecks(address from,address to,address bonding) internal returns (bool){
require(!blacklist[from], "transferKeeperRight: blacklisted");
require(isKeeper(from), "transferKeeperRight: not keeper");
require(msg.sender == from || KeeperAllowances[msg.sender][from],"transferKeeperRight: Unauthorized transfer call");
require(bondings[from][bonding] != 0 && block.timestamp.sub(bondings[from][bonding].add(BOND)) >= 0, "transferKeeperRight: bonding");
KeeperAllowancesPassed[from][to][bonding] = true;
return true;
}
/**
* @notice allows a keeper to transfer their keeper rights and bonds to another address
* @param bonding the asset being transfered to new address as bond collateral
* @param from the address keeper rights and bonding amount is transfered from
* @param to the address keeper rights and bonding amount is transfered to
*/
function transferKeeperRight(address bonding,address from,address to) public {
require(KeeperAllowancesPassed[from][to][bonding],"pass doKeeperrightChecks first");
doDataInit(to);
//Set the user calling keeper stat to false
keepers[from] = false;
//Set the to addr keeper stat to true
keepers[to] = true;
//Unbond from sender
uint currentbond = bonds[from][bonding];
_unbond(bonding,from,currentbond);
//Bond to receiver
_bond(bonding,to,currentbond);
//Remove allowance passed after transfer
KeeperAllowancesPassed[from][to][bonding] = false;
//remove rights for this address after transfer is done from caller
KeeperAllowances[from][msg.sender] = false;
emit KeeperRightTransfered(from,to,bonding);
}
/**
* @notice begin the unbonding process to stop being a keeper
* @param bonding the asset being unbound
* @param amount allows for partial unbonding
*/
function unbond(address bonding, uint amount) external {
unbondings[msg.sender][bonding] = now;
_unbond(bonding, msg.sender, amount);
partialUnbonding[msg.sender][bonding] = partialUnbonding[msg.sender][bonding].add(amount);
emit KeeperUnbonding(msg.sender, block.number, unbondings[msg.sender][bonding], amount);
}
// function getUnbondTime(address user,address bonding) public view returns (uint256){
// return unbondings[user][bonding].add(UNBOND);
// }
/**
* @notice withdraw funds after unbonding has finished
* @param bonding the asset to withdraw from the bonding pool
*/
function withdraw(address bonding) external nonReentrant {
//Same changes as on bonding check is done here
require(unbondings[msg.sender][bonding] != 0 && block.timestamp.sub(unbondings[msg.sender][bonding].add(UNBOND)) >= 0, "withdraw: unbonding");
require(!disputes[msg.sender], "withdraw: disputes");
if (bonding == address(this)) {
_transferTokens(address(this), msg.sender, partialUnbonding[msg.sender][bonding]);
} else {
IERC20(bonding).safeTransfer(msg.sender, partialUnbonding[msg.sender][bonding]);
}
emit KeeperUnbound(msg.sender, block.number, block.timestamp, partialUnbonding[msg.sender][bonding]);
partialUnbonding[msg.sender][bonding] = 0;
}
/**
* @notice allows governance to create a dispute for a given keeper
* @param keeper the address in dispute
*/
function dispute(address keeper) external onlyGovernance{
disputes[keeper] = true;
emit KeeperDispute(keeper, block.number);
}
/**
* @notice allows governance to slash a keeper based on a dispute
* @param bonded the asset being slashed
* @param keeper the address being slashed
* @param amount the amount being slashed
*/
function slash(address bonded, address keeper, uint amount) public nonReentrant onlyGovernance{
if (bonded == address(this)) {
_transferTokens(address(this), governance, amount);
} else {
IERC20(bonded).safeTransfer(governance, amount);
}
_unbond(bonded, keeper, amount);
disputes[keeper] = false;
emit KeeperSlashed(keeper, msg.sender, block.number, amount);
}
/**
* @notice blacklists a keeper from participating in the network
* @param keeper the address being slashed
*/
function revoke(address keeper) external onlyGovernance{
keepers[keeper] = false;
blacklist[keeper] = true;
slash(address(this), keeper, bonds[keeper][address(this)]);
}
/**
* @notice allows governance to resolve a dispute on a keeper
* @param keeper the address cleared
*/
function resolve(address keeper) external onlyGovernance{
disputes[keeper] = false;
emit KeeperResolved(keeper, block.number);
}
/**
* @notice Get the number of tokens `spender` is approved to spend on behalf of `account`
* @param account The address of the account holding the funds
* @param spender The address of the account spending the funds
* @return The number of tokens approved
*/
function allowance(address account, address spender) external view returns (uint) {
return allowances[account][spender];
}
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param amount The number of tokens that are approved (2^256-1 means infinite)
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint amount) public returns (bool) {
allowances[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
/**
* @notice Approve `spender` to transfer Keeper rights
* @param spender The address of the account which may transfer keeper rights
* @param fAllow whether this spender should be able to transfer rights
* @return Whether or not the approval succeeded
*/
function keeperrightapprove(address spender,bool fAllow) public returns (bool) {
KeeperAllowances[msg.sender][spender] = fAllow;
emit KeeperRightApproval(msg.sender, spender, fAllow);
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 amount The number of tokens that are approved (2^256-1 means infinite)
* @param deadline The time at which to expire the signature
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/
function permit(address owner, address spender, uint amount, uint deadline, uint8 v, bytes32 r, bytes32 s) external {
bytes32 structHash = keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, amount, nonces[owner]++, deadline));
bytes32 digest = keccak256(abi.encodePacked("\x19\x01", DOMAINSEPARATOR, structHash));
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "permit: signature");
require(signatory == owner, "permit: unauthorized");
require(now <= deadline, "permit: expired");
allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @notice Get the number of tokens held by the `account`
* @param account The address of the account to get the balance of
* @return The number of tokens held
*/
function balanceOf(address account) external view returns (uint) {
return balances[account];
}
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transfer(address dst, uint amount) public returns (bool) {
_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 amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferFrom(address src, address dst, uint amount) external returns (bool) {
address spender = msg.sender;
uint spenderAllowance = allowances[src][spender];
if (spender != src && spenderAllowance != uint(-1)) {
uint newAllowance = spenderAllowance.sub(amount, "transferFrom: exceeds spender allowance");
allowances[src][spender] = newAllowance;
emit Approval(src, spender, newAllowance);
}
_transferTokens(src, dst, amount);
return true;
}
function _transferTokens(address src, address dst, uint amount) internal {
require(src != address(0), "_transferTokens: zero address");
require(dst != address(0), "_transferTokens: zero address");
balances[src] = balances[src].sub(amount);
balances[dst] = balances[dst].add(amount);
emit Transfer(src, dst, amount);
}
function _getChainId() internal pure returns (uint) {
uint chainId;
assembly { chainId := chainid() }
return chainId;
}
} | * @notice allows a keeper to transfer their keeper rights and bonds to another address @param bonding the asset being transfered to new address as bond collateral @param from the address keeper rights and bonding amount is transfered from @param to the address keeper rights and bonding amount is transfered to/Set the user calling keeper stat to falseSet the to addr keeper stat to trueUnbond from senderBond to receiverRemove allowance passed after transferremove rights for this address after transfer is done from caller | function transferKeeperRight(address bonding,address from,address to) public {
require(KeeperAllowancesPassed[from][to][bonding],"pass doKeeperrightChecks first");
doDataInit(to);
keepers[from] = false;
keepers[to] = true;
uint currentbond = bonds[from][bonding];
_unbond(bonding,from,currentbond);
_bond(bonding,to,currentbond);
KeeperAllowancesPassed[from][to][bonding] = false;
KeeperAllowances[from][msg.sender] = false;
emit KeeperRightTransfered(from,to,bonding);
}
| 1,429,918 | [
1,
5965,
87,
279,
417,
9868,
358,
7412,
3675,
417,
9868,
14989,
471,
15692,
358,
4042,
1758,
225,
8427,
310,
326,
3310,
3832,
7412,
329,
358,
394,
1758,
487,
8427,
4508,
2045,
287,
225,
628,
326,
1758,
417,
9868,
14989,
471,
8427,
310,
3844,
353,
7412,
329,
628,
225,
358,
326,
1758,
417,
9868,
14989,
471,
8427,
310,
3844,
353,
7412,
329,
358,
19,
694,
326,
729,
4440,
417,
9868,
610,
358,
629,
694,
326,
358,
3091,
417,
9868,
610,
358,
638,
984,
26425,
628,
5793,
9807,
358,
5971,
3288,
1699,
1359,
2275,
1839,
7412,
4479,
14989,
364,
333,
1758,
1839,
7412,
353,
2731,
628,
4894,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
565,
445,
7412,
17891,
4726,
12,
2867,
8427,
310,
16,
2867,
628,
16,
2867,
358,
13,
1071,
288,
203,
3639,
2583,
12,
17891,
7009,
6872,
22530,
63,
2080,
6362,
869,
6362,
26425,
310,
6487,
6,
5466,
741,
11523,
370,
750,
4081,
1122,
8863,
203,
3639,
741,
751,
2570,
12,
869,
1769,
203,
203,
3639,
3455,
414,
63,
2080,
65,
273,
629,
31,
203,
3639,
3455,
414,
63,
869,
65,
273,
638,
31,
203,
203,
3639,
2254,
783,
26425,
273,
15692,
63,
2080,
6362,
26425,
310,
15533,
203,
3639,
389,
318,
26425,
12,
26425,
310,
16,
2080,
16,
2972,
26425,
1769,
203,
3639,
389,
26425,
12,
26425,
310,
16,
869,
16,
2972,
26425,
1769,
203,
3639,
1475,
9868,
7009,
6872,
22530,
63,
2080,
6362,
869,
6362,
26425,
310,
65,
273,
629,
31,
203,
3639,
1475,
9868,
7009,
6872,
63,
2080,
6362,
3576,
18,
15330,
65,
273,
629,
31,
203,
3639,
3626,
1475,
9868,
4726,
5912,
329,
12,
2080,
16,
869,
16,
26425,
310,
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
] |
// SPDX-License-Identifier: MIT
pragma solidity 0.7.6;
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 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);
}
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;
}
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);
}
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);
}
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);
}
abstract contract ERC165 is IERC165 {
/*
* bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7
*/
bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
/**
* @dev Mapping of interface ids to whether or not it's supported.
*/
mapping(bytes4 => bool) private _supportedInterfaces;
constructor() internal {
// Derived contracts need only register support for their own interfaces,
// we register support for ERC165 itself here
_registerInterface(_INTERFACE_ID_ERC165);
}
/**
* @dev See {IERC165-supportsInterface}.
*
* Time complexity O(1), guaranteed to always use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override
returns (bool)
{
return _supportedInterfaces[interfaceId];
}
/**
* @dev Registers the contract as an implementer of the interface defined by
* `interfaceId`. Support of the actual ERC165 interface is automatic and
* registering its interface id is not required.
*
* See {IERC165-supportsInterface}.
*
* Requirements:
*
* - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`).
*/
function _registerInterface(bytes4 interfaceId) internal virtual {
require(interfaceId != 0xffffffff, "ERC165: invalid interface id");
_supportedInterfaces[interfaceId] = true;
}
}
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;
}
}
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);
}
}
}
}
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping(bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) {
// Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value)
private
view
returns (bool)
{
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index)
private
view
returns (bytes32)
{
require(
set._values.length > index,
"EnumerableSet: index out of bounds"
);
return set._values[index];
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value)
internal
returns (bool)
{
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value)
internal
returns (bool)
{
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value)
internal
view
returns (bool)
{
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index)
internal
view
returns (bytes32)
{
return _at(set._inner, index);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value)
internal
returns (bool)
{
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value)
internal
returns (bool)
{
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value)
internal
view
returns (bool)
{
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index)
internal
view
returns (address)
{
return address(uint160(uint256(_at(set._inner, index))));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value)
internal
returns (bool)
{
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value)
internal
view
returns (bool)
{
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index)
internal
view
returns (uint256)
{
return uint256(_at(set._inner, index));
}
}
library EnumerableMap {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Map type with
// bytes32 keys and values.
// The Map implementation uses private functions, and user-facing
// implementations (such as Uint256ToAddressMap) are just wrappers around
// the underlying Map.
// This means that we can only create new EnumerableMaps for types that fit
// in bytes32.
struct MapEntry {
bytes32 _key;
bytes32 _value;
}
struct Map {
// Storage of map keys and values
MapEntry[] _entries;
// Position of the entry defined by a key in the `entries` array, plus 1
// because index 0 means a key is not in the map.
mapping(bytes32 => uint256) _indexes;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function _set(
Map storage map,
bytes32 key,
bytes32 value
) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) {
// Equivalent to !contains(map, key)
map._entries.push(MapEntry({_key: key, _value: value}));
// The entry is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
map._indexes[key] = map._entries.length;
return true;
} else {
map._entries[keyIndex - 1]._value = value;
return false;
}
}
/**
* @dev Removes a key-value pair from a map. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function _remove(Map storage map, bytes32 key) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex != 0) {
// Equivalent to contains(map, key)
// To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one
// in the array, and then remove the last entry (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = keyIndex - 1;
uint256 lastIndex = map._entries.length - 1;
// When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
MapEntry storage lastEntry = map._entries[lastIndex];
// Move the last entry to the index where the entry to delete is
map._entries[toDeleteIndex] = lastEntry;
// Update the index for the moved entry
map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved entry was stored
map._entries.pop();
// Delete the index for the deleted slot
delete map._indexes[key];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function _contains(Map storage map, bytes32 key)
private
view
returns (bool)
{
return map._indexes[key] != 0;
}
/**
* @dev Returns the number of key-value pairs in the map. O(1).
*/
function _length(Map storage map) private view returns (uint256) {
return map._entries.length;
}
/**
* @dev Returns the key-value pair stored at position `index` in the map. O(1).
*
* Note that there are no guarantees on the ordering of entries inside the
* array, and it may change when more entries are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Map storage map, uint256 index)
private
view
returns (bytes32, bytes32)
{
require(
map._entries.length > index,
"EnumerableMap: index out of bounds"
);
MapEntry storage entry = map._entries[index];
return (entry._key, entry._value);
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*/
function _tryGet(Map storage map, bytes32 key)
private
view
returns (bool, bytes32)
{
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) return (false, 0); // Equivalent to contains(map, key)
return (true, map._entries[keyIndex - 1]._value); // All indexes are 1-based
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function _get(Map storage map, bytes32 key) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, "EnumerableMap: nonexistent key"); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
/**
* @dev Same as {_get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {_tryGet}.
*/
function _get(
Map storage map,
bytes32 key,
string memory errorMessage
) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
// UintToAddressMap
struct UintToAddressMap {
Map _inner;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function set(
UintToAddressMap storage map,
uint256 key,
address value
) internal returns (bool) {
return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function remove(UintToAddressMap storage map, uint256 key)
internal
returns (bool)
{
return _remove(map._inner, bytes32(key));
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function contains(UintToAddressMap storage map, uint256 key)
internal
view
returns (bool)
{
return _contains(map._inner, bytes32(key));
}
/**
* @dev Returns the number of elements in the map. O(1).
*/
function length(UintToAddressMap storage map)
internal
view
returns (uint256)
{
return _length(map._inner);
}
/**
* @dev Returns the element stored at position `index` in the set. O(1).
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintToAddressMap storage map, uint256 index)
internal
view
returns (uint256, address)
{
(bytes32 key, bytes32 value) = _at(map._inner, index);
return (uint256(key), address(uint160(uint256(value))));
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*
* _Available since v3.4._
*/
function tryGet(UintToAddressMap storage map, uint256 key)
internal
view
returns (bool, address)
{
(bool success, bytes32 value) = _tryGet(map._inner, bytes32(key));
return (success, address(uint160(uint256(value))));
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function get(UintToAddressMap storage map, uint256 key)
internal
view
returns (address)
{
return address(uint160(uint256(_get(map._inner, bytes32(key)))));
}
/**
* @dev Same as {get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryGet}.
*/
function get(
UintToAddressMap storage map,
uint256 key,
string memory errorMessage
) internal view returns (address) {
return
address(
uint160(uint256(_get(map._inner, bytes32(key), errorMessage)))
);
}
}
library Strings {
/**
* @dev Converts a `uint256` to its ASCII `string` representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
uint256 index = digits - 1;
temp = value;
while (temp != 0) {
buffer[index--] = bytes1(uint8(48 + (temp % 10)));
temp /= 10;
}
return string(buffer);
}
}
/**
* @title ERC721 Non-Fungible Token Standard basic implementation
* @dev see https://eips.ethereum.org/EIPS/eip-721
*/
contract ERC721 is
Context,
ERC165,
IERC721,
IERC721Metadata,
IERC721Enumerable
{
using SafeMath for uint256;
using Address for address;
using EnumerableSet for EnumerableSet.UintSet;
using EnumerableMap for EnumerableMap.UintToAddressMap;
using Strings for uint256;
// Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
// which can be also obtained as `IERC721Receiver(0).onERC721Received.selector`
bytes4 private constant _ERC721_RECEIVED = 0x150b7a02;
// Mapping from holder address to their (enumerable) set of owned tokens
mapping(address => EnumerableSet.UintSet) private _holderTokens;
// Enumerable mapping from token ids to their owners
EnumerableMap.UintToAddressMap private _tokenOwners;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Optional mapping for token URIs
mapping(uint256 => string) private _tokenURIs;
// Base URI
string private _baseURI;
/*
* bytes4(keccak256('balanceOf(address)')) == 0x70a08231
* bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e
* bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3
* bytes4(keccak256('getApproved(uint256)')) == 0x081812fc
* bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465
* bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5
* bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd
* bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e
* bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde
*
* => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^
* 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd
*/
bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd;
/*
* bytes4(keccak256('name()')) == 0x06fdde03
* bytes4(keccak256('symbol()')) == 0x95d89b41
* bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd
*
* => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f
*/
bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f;
/*
* bytes4(keccak256('totalSupply()')) == 0x18160ddd
* bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59
* bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7
*
* => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63
*/
bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) public {
_name = name_;
_symbol = symbol_;
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(_INTERFACE_ID_ERC721);
_registerInterface(_INTERFACE_ID_ERC721_METADATA);
_registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner)
public
view
virtual
override
returns (uint256)
{
require(
owner != address(0),
"ERC721: balance query for the zero address"
);
return _holderTokens[owner].length();
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId)
public
view
virtual
override
returns (address)
{
return
_tokenOwners.get(
tokenId,
"ERC721: owner query for nonexistent token"
);
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId)
public
view
virtual
override
returns (string memory)
{
require(
_exists(tokenId),
"ERC721Metadata: URI query for nonexistent token"
);
string memory _tokenURI = _tokenURIs[tokenId];
string memory base = baseURI();
// If there is no base URI, return the token URI.
if (bytes(base).length == 0) {
return _tokenURI;
}
// If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked).
if (bytes(_tokenURI).length > 0) {
return string(abi.encodePacked(base, _tokenURI));
}
// If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI.
return string(abi.encodePacked(base, tokenId.toString()));
}
/**
* @dev Returns the base URI set via {_setBaseURI}. This will be
* automatically added as a prefix in {tokenURI} to each token's URI, or
* to the token ID if no specific URI is set for that token ID.
*/
function baseURI() public view virtual returns (string memory) {
return _baseURI;
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index)
public
view
virtual
override
returns (uint256)
{
return _holderTokens[owner].at(index);
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
// _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds
return _tokenOwners.length();
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index)
public
view
virtual
override
returns (uint256)
{
(uint256 tokenId, ) = _tokenOwners.at(index);
return tokenId;
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner ||
ERC721.isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId)
public
view
virtual
override
returns (address)
{
require(
_exists(tokenId),
"ERC721: approved query for nonexistent token"
);
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved)
public
virtual
override
{
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator)
public
view
virtual
override
returns (bool)
{
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(
_isApprovedOrOwner(_msgSender(), tokenId),
"ERC721: transfer caller is not owner nor approved"
);
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(
_isApprovedOrOwner(_msgSender(), tokenId),
"ERC721: transfer caller is not owner nor approved"
);
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(
_checkOnERC721Received(from, to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _tokenOwners.contains(tokenId);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId)
internal
view
virtual
returns (bool)
{
require(
_exists(tokenId),
"ERC721: operator query for nonexistent token"
);
address owner = ERC721.ownerOf(tokenId);
return (spender == owner ||
getApproved(tokenId) == spender ||
ERC721.isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
d*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId); // internal owner
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
// Clear metadata (if any)
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
_holderTokens[owner].remove(tokenId);
_tokenOwners.remove(tokenId);
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(
ERC721.ownerOf(tokenId) == from,
"ERC721: transfer of token that is not own"
); // internal owner
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_holderTokens[from].remove(tokenId);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(from, to, tokenId);
}
/**
* @dev Sets `_tokenURI` as the tokenURI of `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _setTokenURI(uint256 tokenId, string memory _tokenURI)
internal
virtual
{
require(
_exists(tokenId),
"ERC721Metadata: URI set of nonexistent token"
);
_tokenURIs[tokenId] = _tokenURI;
}
/**
* @dev Internal function to set the base URI for all token IDs. It is
* automatically added as a prefix to the value returned in {tokenURI},
* or to the token ID if {tokenURI} is empty.
*/
function _setBaseURI(string memory baseURI_) internal virtual {
_baseURI = baseURI_;
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (!to.isContract()) {
return true;
}
bytes memory returndata = to.functionCall(
abi.encodeWithSelector(
IERC721Receiver(to).onERC721Received.selector,
_msgSender(),
from,
tokenId,
_data
),
"ERC721: transfer to non ERC721Receiver implementer"
);
bytes4 retval = abi.decode(returndata, (bytes4));
return (retval == _ERC721_RECEIVED);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits an {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId); // internal owner
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
abstract contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor () internal {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
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;
}
}
library Counters {
using SafeMath for uint256;
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
// The {SafeMath} overflow check can be skipped here, see the comment at the top
counter._value += 1;
}
function decrement(Counter storage counter) internal {
counter._value = counter._value.sub(1);
}
}
contract MetaTunes is ERC721, Pausable, Ownable {
using Counters for Counters.Counter;
using SafeMath for uint256;
Counters.Counter private _tokenIdCounter;
event Mint(address indexed to, uint256 indexed tokenId);
uint256 public CAP;
uint256 public PRICE_ONE;
uint256 public PRICE_DISCOUNT_TRIPLE;
uint256 public PRICE_DISCOUNT_TEN;
mapping(address => bool) whitelist;
uint256 presales = 0;
bool mintingStop4Ever = false;
constructor(
string memory _token_name,
string memory _token_symbol,
uint256 _CAP,
uint256 _PRICE_ONE
) ERC721(_token_name, _token_symbol) {
CAP = _CAP;
PRICE_ONE = _PRICE_ONE;
PRICE_DISCOUNT_TRIPLE = _PRICE_ONE.mul(90).div(100); //10% discount
PRICE_DISCOUNT_TEN = _PRICE_ONE.mul(80).div(100); //20% discount
pause();
}
function addToWhitelist(address[] memory wallets, bool enabled)
public
onlyOwner
{
for (uint256 i = 0; i < wallets.length; i++) {
whitelist[wallets[i]] = enabled;
}
}
function mintWhitelist(address _to, uint256 _amount) public payable {
require(whitelist[msg.sender], "Not whitlisted");
require(msg.value >= 5 * 10**16 * _amount);
uint256 newCap = presales.add(_amount);
require(newCap <= 100, "Mint would exceed allowed presale amount");
_mintX(_to, _amount);
presales = newCap;
}
function pause() public onlyOwner {
_pause();
}
function unpause() public onlyOwner {
_unpause();
}
function setPrice(uint256 newPrice) public onlyOwner {
PRICE_ONE = newPrice;
PRICE_DISCOUNT_TRIPLE = newPrice.mul(90).div(100);
PRICE_DISCOUNT_TEN = newPrice.mul(80).div(100);
}
function mintOne(address _to) public payable whenNotPaused {
require(msg.value >= PRICE_ONE, "Wrong amount sent");
_mintX(_to, 1);
}
function mintThree(address _to) public payable whenNotPaused {
require(msg.value >= PRICE_DISCOUNT_TRIPLE, "wrong amount sent");
_mintX(_to, 3);
}
function mintTen(address _to) public payable whenNotPaused {
require(msg.value >= PRICE_DISCOUNT_TEN, "wrong amount sent");
_mintX(_to, 10);
}
function _mintX(address _to, uint256 _amount) internal {
uint256 totalSupply = totalSupply();
require(
(totalSupply + _amount) <= CAP,
"mint would exceed the totalSupply"
);
require(!mintingStop4Ever, "Minting was stopped foreva eva");
for (uint256 i = 0; i < _amount; i++) {
_safeMint(_to, totalSupply + i);
}
}
function reservedMint(address _to, uint256 _amount) public onlyOwner {
_mintX(_to, _amount);
}
function withdraw() public onlyOwner {
uint256 balance = address(this).balance;
payable(msg.sender).transfer(balance);
}
function setBaseURI(string memory _baseURI) public onlyOwner {
_setBaseURI(_baseURI);
}
function burnUnsold() public onlyOwner {
mintingStop4Ever = true;
}
} | * @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));
}
| 11,733,587 | [
1,
6220,
279,
460,
628,
279,
444,
18,
531,
12,
21,
2934,
2860,
638,
309,
326,
460,
1703,
3723,
628,
326,
444,
16,
716,
353,
309,
518,
1703,
3430,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
445,
1206,
12,
5487,
694,
2502,
444,
16,
2254,
5034,
460,
13,
203,
5411,
2713,
203,
5411,
1135,
261,
6430,
13,
203,
3639,
288,
203,
5411,
327,
389,
4479,
12,
542,
6315,
7872,
16,
1731,
1578,
12,
1132,
10019,
203,
3639,
289,
203,
377,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
//Address: 0xc4fa0ac077a69934d2db0a37654c31395a05b8c9
//Contract name: SimplePHXExchange
//Balance: 0.0004 Ether
//Verification Date: 3/19/2018
//Transacion Count: 31
// CODE STARTS HERE
pragma solidity ^0.4.21;
/*
* Basic PHX-Ethereum Exchange
*
* This contract keeps a list of buy/sell orders for PHX coins
* and acts as a market-maker matching sellers to buyers.
*
* //*** Developed By:
* _____ _ _ _ ___ _
* |_ _|__ __| |_ _ _ (_)__ __ _| | _ (_)___ ___
* | |/ -_) _| ' \| ' \| / _/ _` | | / (_-</ -_)
* |_|\___\__|_||_|_||_|_\__\__,_|_|_|_\_/__/\___|
*
* © 2018 TechnicalRise. Written in March 2018.
* All rights reserved. Do not copy, adapt, or otherwise use without permission.
* https://www.reddit.com/user/TechnicalRise/
*
* Thanks to Ogu, TocSick, and Norsefire.
*/
contract ERC20Token {
function transfer(address to, uint tokens) public returns (bool success);
function transferFrom(address from, address to, uint256 tokens) public returns (bool success);
}
contract SimplePHXExchange {
// ScaleFactor
// It needs to be possible to make PHX cost less than 1 Wei / Rise
// And vice-versa, make ETH cost less than 1 Rise / Wei
uint public ScaleFactor = 10 ** 18;
// **** Maps for the Token-Seller Side of the Contract
// Array of offerors
address[] public tknOfferors;
mapping(address => uint256) public tknAddrNdx;
// Array between each address and their tokens offered and buy prices.
mapping(address => uint256) public tknTokensOffered;
mapping(address => uint256) public tknPricePerToken; // In qWeiPerRise (need to multiply by 10 ** 36 to get it to ETH / PHX)
// **** Maps for the Token-Buyer Side of the Contract
// Array of offerors
address[] public ethOfferors;
mapping(address => uint256) public ethAddrNdx;
// Array between each address and their tokens offered and buy prices.
mapping(address => uint256) public ethEtherOffered;
mapping(address => uint256) public ethPricePerToken; // In qRisePerWei (need to multiply by 10 ** 36 to get it to PHX / ETH)
// ****
ERC20Token public phxCoin;
function SimplePHXExchange() public {
phxCoin = ERC20Token(0x14b759A158879B133710f4059d32565b4a66140C); // Initiates a PHX Coin !important -- Make sure this is the PHX contract!
tknOfferors.push(0x0); // This is because all IDs in tknAddrNdx will initialize to zero
ethOfferors.push(0x0); // This is because all IDs in ethAddrNdx will initialize to zero
}
function offerTkn(uint _tokensOffered, uint _tokenPrice) public {
require(_humanSender(msg.sender));
require(tknAddrNdx[msg.sender] == 0); // Make sure that this offeror has cancelled all previous offers
require(0 < _tokensOffered); // Make sure some number of tokens are offered
require(phxCoin.transferFrom(msg.sender, this, _tokensOffered)); // Require that transfer can be and is made
tknTokensOffered[msg.sender] = _tokensOffered;
tknPricePerToken[msg.sender] = _tokenPrice; // in qWeiPerRise
tknOfferors.push(msg.sender);
tknAddrNdx[msg.sender] = tknOfferors.length - 1;
}
function offerEth(uint _tokenPrice) public payable {
require(_humanSender(msg.sender));
require(ethAddrNdx[msg.sender] == 0); // Make sure that this offeror has cancelled all previous offers
require(0 < msg.value); // Make sure some amount of eth is offered
ethEtherOffered[msg.sender] = msg.value;
ethPricePerToken[msg.sender] = _tokenPrice; // in qRisesPerWei
ethOfferors.push(msg.sender);
ethAddrNdx[msg.sender] = ethOfferors.length - 1;
}
function cancelTknOffer() public {
if(tknAddrNdx[msg.sender] == 0) return; // No need to cancel non-existent offer
phxCoin.transfer(msg.sender, tknTokensOffered[msg.sender]); // Return the Tokens
_cancelTknOffer(msg.sender);
}
function _cancelTknOffer(address _offeror) internal {
delete tknTokensOffered[_offeror];
delete tknPricePerToken[_offeror];
uint ndx = tknAddrNdx[_offeror];
// If this isn't the only offer, reshuffle the array
// Moving the last entry to the middle of the list
tknOfferors[ndx] = tknOfferors[tknOfferors.length - 1];
tknAddrNdx[tknOfferors[tknOfferors.length - 1]] = ndx;
tknOfferors.length = tknOfferors.length - 1;
delete tknAddrNdx[_offeror]; // !important
}
function cancelEthOffer() public {
if(ethAddrNdx[msg.sender] == 0) return; // No need to cancel non-existent offer
msg.sender.transfer(ethEtherOffered[msg.sender]); // Return the Tokens
_cancelEthOffer(msg.sender);
}
function _cancelEthOffer(address _offeror) internal {
delete ethEtherOffered[_offeror];
delete ethPricePerToken[_offeror];
uint ndx = ethAddrNdx[_offeror];
// If this isn't the only offer, reshuffle the array
// Moving the last entry to the middle of the list
ethOfferors[ndx] = ethOfferors[ethOfferors.length - 1];
ethAddrNdx[ethOfferors[ethOfferors.length - 1]] = ndx;
ethOfferors.length = ethOfferors.length - 1;
delete ethAddrNdx[_offeror]; // !important
}
function buyTkn(uint _ndx) payable public {
require(_humanSender(msg.sender));
address _offeror = tknOfferors[_ndx];
uint _purchasePrice = tknTokensOffered[_offeror] * tknPricePerToken[_offeror] / ScaleFactor; // i.e. # of Wei Required = Rises * (qWei/Rise) / 10**18
require(msg.value >= _purchasePrice);
require(phxCoin.transfer(msg.sender, tknTokensOffered[_offeror])); // Successful transfer of tokens to purchaser
_offeror.transfer(_purchasePrice);
_cancelTknOffer(_offeror);
}
function buyEth(uint _ndx) public {
require(_humanSender(msg.sender));
address _offeror = ethOfferors[_ndx];
uint _purchasePrice = ethEtherOffered[_offeror] * ethPricePerToken[_offeror] / ScaleFactor; // i.e. # of Rises Required = Wei * (qTRs/Wei) / 10**18
require(phxCoin.transferFrom(msg.sender, _offeror, _purchasePrice)); // Successful transfer of tokens to offeror
msg.sender.transfer(ethEtherOffered[_offeror]);
_cancelEthOffer(_offeror);
}
function updateTknPrice(uint _newPrice) public {
// Make sure that this offeror has an offer out there
require(tknTokensOffered[msg.sender] != 0);
tknPricePerToken[msg.sender] = _newPrice;
}
function updateEthPrice(uint _newPrice) public {
// Make sure that this offeror has an offer out there
require(ethEtherOffered[msg.sender] != 0);
ethPricePerToken[msg.sender] = _newPrice;
}
// Getter Functions
function getNumTknOfferors() public constant returns (uint _numOfferors) {
return tknOfferors.length; // !important: This is always 1 more than the number of actual offers
}
function getTknOfferor(uint _ndx) public constant returns (address _offeror) {
return tknOfferors[_ndx];
}
function getTknOfferPrice(uint _ndx) public constant returns (uint _tokenPrice) {
return tknPricePerToken[tknOfferors[_ndx]];
}
function getTknOfferAmount(uint _ndx) public constant returns (uint _tokensOffered) {
return tknTokensOffered[tknOfferors[_ndx]];
}
function getNumEthOfferors() public constant returns (uint _numOfferors) {
return ethOfferors.length; // !important: This is always 1 more than the number of actual offers
}
function getEthOfferor(uint _ndx) public constant returns (address _offeror) {
return ethOfferors[_ndx];
}
function getEthOfferPrice(uint _ndx) public constant returns (uint _etherPrice) {
return ethPricePerToken[ethOfferors[_ndx]];
}
function getEthOfferAmount(uint _ndx) public constant returns (uint _etherOffered) {
return ethEtherOffered[ethOfferors[_ndx]];
}
// **
// A Security Precaution -- Don't interact with contracts unless you
// Have a need to / desire to.
// Determine if the "_from" address is a contract
function _humanSender(address _from) private view returns (bool) {
uint codeLength;
assembly {
codeLength := extcodesize(_from)
}
return (codeLength == 0); // If this is "true" sender is most likely a Wallet
}
}
| Make sure that this offeror has an offer out there | function updateTknPrice(uint _newPrice) public {
require(tknTokensOffered[msg.sender] != 0);
tknPricePerToken[msg.sender] = _newPrice;
}
| 5,394,618 | [
1,
6464,
3071,
716,
333,
10067,
280,
711,
392,
10067,
596,
1915,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
1089,
56,
21112,
5147,
12,
11890,
389,
2704,
5147,
13,
1071,
288,
203,
3639,
2583,
12,
16099,
82,
5157,
10513,
329,
63,
3576,
18,
15330,
65,
480,
374,
1769,
7010,
3639,
13030,
82,
5147,
2173,
1345,
63,
3576,
18,
15330,
65,
273,
389,
2704,
5147,
31,
203,
565,
289,
203,
377,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/56/0x5720e28DC258961e15a4445D6e6e3335dcB46e99/sources/NinjaPair.sol | force balances to match reserves | function skim(address to) external lock {
_safeTransfer(_token0, to, IBEP20(_token0).balanceOf(address(this)).sub(reserve0));
_safeTransfer(_token1, to, IBEP20(_token1).balanceOf(address(this)).sub(reserve1));
}
| 11,238,219 | [
1,
5734,
324,
26488,
358,
845,
400,
264,
3324,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
4343,
381,
12,
2867,
358,
13,
3903,
2176,
288,
203,
3639,
389,
4626,
5912,
24899,
2316,
20,
16,
358,
16,
467,
5948,
52,
3462,
24899,
2316,
20,
2934,
12296,
951,
12,
2867,
12,
2211,
13,
2934,
1717,
12,
455,
6527,
20,
10019,
203,
3639,
389,
4626,
5912,
24899,
2316,
21,
16,
358,
16,
467,
5948,
52,
3462,
24899,
2316,
21,
2934,
12296,
951,
12,
2867,
12,
2211,
13,
2934,
1717,
12,
455,
6527,
21,
10019,
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
] |
pragma solidity 0.5.17;
import {ITokenRecipient} from "../interfaces/ITokenRecipient.sol";
import {TBTCDepositToken} from "../system/TBTCDepositToken.sol";
import {TBTCToken} from "../system/TBTCToken.sol";
import {FeeRebateToken} from "../system/FeeRebateToken.sol";
import {VendingMachine} from "../system/VendingMachine.sol";
/// @notice A one-click script for minting TBTC from an unqualified TDT.
/// @dev Wrapper script for VendingMachine.unqualifiedDepositToTbtc
/// This contract implements receiveApproval() and can therefore use
/// approveAndCall(). This pattern combines TBTC Token approval and
/// vendingMachine.unqualifiedDepositToTbtc() in a single transaction.
contract FundingScript is ITokenRecipient {
TBTCToken tbtcToken;
VendingMachine vendingMachine;
TBTCDepositToken tbtcDepositToken;
FeeRebateToken feeRebateToken;
constructor(
address _VendingMachine,
address _TBTCToken,
address _TBTCDepositToken,
address _FeeRebateToken
) public {
vendingMachine = VendingMachine(_VendingMachine);
tbtcToken = TBTCToken(_TBTCToken);
tbtcDepositToken = TBTCDepositToken(_TBTCDepositToken);
feeRebateToken = FeeRebateToken(_FeeRebateToken);
}
/// @notice Receives approval for a TDT transfer, and calls `VendingMachine.unqualifiedDepositToTbtc` for a user.
/// @dev Implements the approveAndCall receiver interface.
/// @param _from The owner of the token who approved them for transfer.
/// @param _tokenId Approved TDT for the transfer.
/// @param _extraData Encoded function call to `VendingMachine.unqualifiedDepositToTbtc`.
function receiveApproval(
address _from,
uint256 _tokenId,
address,
bytes memory _extraData
) public { // not external to allow bytes memory parameters
require(msg.sender == address(tbtcDepositToken), "Only token contract can call receiveApproval");
tbtcDepositToken.transferFrom(_from, address(this), _tokenId);
tbtcDepositToken.approve(address(vendingMachine), _tokenId);
// Verify _extraData is a call to unqualifiedDepositToTbtc.
bytes4 functionSignature;
assembly {
functionSignature := and(mload(add(_extraData, 0x20)), not(0xff))
}
require(
functionSignature == vendingMachine.unqualifiedDepositToTbtc.selector,
"Bad _extraData signature. Call must be to unqualifiedDepositToTbtc."
);
// Call the VendingMachine.
// We could explictly encode the call to vending machine, but this would
// involve manually parsing _extraData and allocating variables.
// We capture the `returnData` in order to forward any nested revert message
// from the contract call.
/* solium-disable-next-line security/no-low-level-calls */
(bool success, bytes memory returnData) = address(vendingMachine).call(_extraData);
string memory revertMessage;
assembly {
// A revert message is ABI-encoded as a call to Error(string).
// Slicing the Error() signature (4 bytes) and Data offset (4 bytes)
// leaves us with a pre-encoded string.
// We also slice off the ABI-coded length of returnData (32).
revertMessage := add(returnData, 0x44)
}
require(success, revertMessage);
// Transfer the TBTC and feeRebateToken to the user.
tbtcToken.transfer(_from, tbtcToken.balanceOf(address(this)));
feeRebateToken.transferFrom(address(this), _from, uint256(_tokenId));
}
}
| Call the VendingMachine. We could explictly encode the call to vending machine, but this would involve manually parsing _extraData and allocating variables. We capture the `returnData` in order to forward any nested revert message from the contract call. solium-disable-next-line security/no-low-level-calls */ A revert message is ABI-encoded as a call to Error(string). Slicing the Error() signature (4 bytes) and Data offset (4 bytes) leaves us with a pre-encoded string. We also slice off the ABI-coded length of returnData (32). | functionSignature == vendingMachine.unqualifiedDepositToTbtc.selector,
"Bad _extraData signature. Call must be to unqualifiedDepositToTbtc."
);
(bool success, bytes memory returnData) = address(vendingMachine).call(_extraData);
string memory revertMessage;
assembly {
revertMessage := add(returnData, 0x44)
}
require(success, revertMessage);
feeRebateToken.transferFrom(address(this), _from, uint256(_tokenId));
| 885,048 | [
1,
1477,
326,
776,
2846,
6981,
18,
1660,
3377,
22991,
933,
715,
2017,
326,
745,
358,
331,
2846,
5228,
16,
1496,
333,
4102,
2198,
5390,
10036,
5811,
389,
7763,
751,
471,
4767,
1776,
3152,
18,
1660,
7477,
326,
1375,
2463,
751,
68,
316,
1353,
358,
5104,
1281,
4764,
15226,
883,
628,
326,
6835,
745,
18,
3704,
5077,
17,
8394,
17,
4285,
17,
1369,
4373,
19,
2135,
17,
821,
17,
2815,
17,
12550,
342,
432,
15226,
883,
353,
10336,
45,
17,
10787,
487,
279,
745,
358,
1068,
12,
1080,
2934,
9708,
14774,
326,
1068,
1435,
3372,
261,
24,
1731,
13,
471,
1910,
1384,
261,
24,
1731,
13,
15559,
584,
598,
279,
675,
17,
10787,
533,
18,
1660,
2546,
2788,
3397,
326,
10336,
45,
17,
24808,
769,
434,
327,
751,
261,
1578,
2934,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
5411,
445,
5374,
422,
331,
2846,
6981,
18,
318,
19724,
758,
1724,
774,
56,
70,
5111,
18,
9663,
16,
203,
5411,
315,
6434,
389,
7763,
751,
3372,
18,
3049,
1297,
506,
358,
640,
19724,
758,
1724,
774,
56,
70,
5111,
1199,
203,
3639,
11272,
203,
203,
3639,
261,
6430,
2216,
16,
1731,
3778,
327,
751,
13,
273,
1758,
12,
90,
2846,
6981,
2934,
1991,
24899,
7763,
751,
1769,
203,
203,
3639,
533,
3778,
15226,
1079,
31,
203,
3639,
19931,
288,
203,
5411,
15226,
1079,
519,
527,
12,
2463,
751,
16,
374,
92,
6334,
13,
203,
3639,
289,
203,
203,
3639,
2583,
12,
4768,
16,
15226,
1079,
1769,
203,
203,
3639,
14036,
426,
70,
340,
1345,
18,
13866,
1265,
12,
2867,
12,
2211,
3631,
389,
2080,
16,
2254,
5034,
24899,
2316,
548,
10019,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/0xc465F392eFFCcE7149E3081e7A150CEE3f4Fd34f/sources/contracts/Contract.sol | If _maxFreeMintAmountPerWallet is 0, reset the freeMint mapping for all addresses to false | function setMintCritera(
uint256 _maxSupply,
uint256 _publicMintCost,
uint256 _maxMintAmountPerWallet,
uint256 _maxFreeMintAmountPerWallet,
uint256 _teamSupply,
string memory _uriPrefix
) public onlyOwner {
require(_maxFreeMintAmountPerWallet >= 0, 'Max Free Mint Amount must be non-negative!');
maxSupply = _maxSupply;
maxMintAmountPerWallet = _maxMintAmountPerWallet;
maxFreeMintAmountPerWallet = _maxFreeMintAmountPerWallet;
uriPrefix = _uriPrefix;
teamSupply = _teamSupply;
publicMintCost = _publicMintCost;
if (_maxFreeMintAmountPerWallet == 0) {
for (uint256 i = 0; i < totalSupply(); i++) {
address addr = ownerOf(i+1);
freeMint[addr] = false;
}
}
}
| 11,617,381 | [
1,
2047,
389,
1896,
9194,
49,
474,
6275,
2173,
16936,
353,
374,
16,
2715,
326,
4843,
49,
474,
2874,
364,
777,
6138,
358,
629,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
915,
15430,
474,
39,
1091,
69,
12,
203,
565,
2254,
5034,
389,
1896,
3088,
1283,
16,
203,
565,
2254,
5034,
389,
482,
49,
474,
8018,
16,
203,
565,
2254,
5034,
389,
1896,
49,
474,
6275,
2173,
16936,
16,
203,
565,
2254,
5034,
389,
1896,
9194,
49,
474,
6275,
2173,
16936,
16,
203,
565,
2254,
5034,
389,
10035,
3088,
1283,
16,
203,
565,
533,
3778,
389,
1650,
2244,
203,
225,
262,
1071,
1338,
5541,
288,
203,
565,
2583,
24899,
1896,
9194,
49,
474,
6275,
2173,
16936,
1545,
374,
16,
296,
2747,
15217,
490,
474,
16811,
1297,
506,
1661,
17,
13258,
5124,
1769,
203,
565,
943,
3088,
1283,
273,
389,
1896,
3088,
1283,
31,
203,
565,
943,
49,
474,
6275,
2173,
16936,
273,
389,
1896,
49,
474,
6275,
2173,
16936,
31,
203,
565,
943,
9194,
49,
474,
6275,
2173,
16936,
273,
389,
1896,
9194,
49,
474,
6275,
2173,
16936,
31,
203,
565,
2003,
2244,
273,
389,
1650,
2244,
31,
203,
565,
5927,
3088,
1283,
273,
389,
10035,
3088,
1283,
31,
203,
565,
1071,
49,
474,
8018,
273,
389,
482,
49,
474,
8018,
31,
203,
377,
203,
565,
309,
261,
67,
1896,
9194,
49,
474,
6275,
2173,
16936,
422,
374,
13,
288,
203,
3639,
364,
261,
11890,
5034,
277,
273,
374,
31,
277,
411,
2078,
3088,
1283,
5621,
277,
27245,
288,
203,
5411,
1758,
3091,
273,
3410,
951,
12,
77,
15,
21,
1769,
203,
5411,
4843,
49,
474,
63,
4793,
65,
273,
629,
31,
203,
3639,
289,
203,
565,
289,
203,
225,
289,
203,
203,
203,
2,
-100
] |
./full_match/1/0xE1Ef01C19751540778b73c122B4fc9a5EF543ECf/sources/TestNet_ReLaunch.sol | Betting functions Transfer the MOMO tokens from the user to the contract | function placeBet(BetChoice _choice, uint256 amount) external {
require(amount >= minBet, "Bet amount is below minimum");
require(balanceOf(msg.sender) >= amount, "Insufficient MOMO tokens");
_transfer(msg.sender, address(this), amount);
bytes32 betId = keccak256(abi.encodePacked(msg.sender, block.timestamp, amount));
uint256 potentialWinning = amount * (100 - houseEdge) / 100;
bool isHeads = uint256(keccak256(abi.encodePacked(block.timestamp, block.prevrandao, msg.sender))) % 2 == 0;
BetOutcome outcome;
if ((isHeads && _choice == BetChoice.HEADS) || (!isHeads && _choice == BetChoice.TAILS)) {
outcome = BetOutcome.WIN;
_transfer(address(this), msg.sender, potentialWinning);
outcome = BetOutcome.LOSE;
rewardPool = rewardPool + amount;
}
bets[betId] = Bet({
user: msg.sender,
amount: amount,
choice: _choice,
outcome: outcome,
potentialWinning: potentialWinning,
blockToResolve: block.number
});
emit BetPlaced(betId, msg.sender, amount, _choice);
emit BetResolved(betId, outcome, potentialWinning);
}
| 8,462,627 | [
1,
38,
278,
1787,
4186,
12279,
326,
490,
1872,
51,
2430,
628,
326,
729,
358,
326,
6835,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
3166,
38,
278,
12,
38,
278,
10538,
389,
11569,
16,
2254,
5034,
3844,
13,
3903,
288,
203,
565,
2583,
12,
8949,
1545,
1131,
38,
278,
16,
315,
38,
278,
3844,
353,
5712,
5224,
8863,
203,
565,
2583,
12,
12296,
951,
12,
3576,
18,
15330,
13,
1545,
3844,
16,
315,
5048,
11339,
490,
1872,
51,
2430,
8863,
203,
377,
203,
565,
389,
13866,
12,
3576,
18,
15330,
16,
1758,
12,
2211,
3631,
3844,
1769,
203,
203,
565,
1731,
1578,
2701,
548,
273,
417,
24410,
581,
5034,
12,
21457,
18,
3015,
4420,
329,
12,
3576,
18,
15330,
16,
1203,
18,
5508,
16,
3844,
10019,
203,
203,
565,
2254,
5034,
8555,
18049,
2093,
273,
3844,
380,
261,
6625,
300,
23867,
6098,
13,
342,
2130,
31,
203,
565,
1426,
353,
1414,
87,
273,
2254,
5034,
12,
79,
24410,
581,
5034,
12,
21457,
18,
3015,
4420,
329,
12,
2629,
18,
5508,
16,
1203,
18,
10001,
7884,
6033,
16,
1234,
18,
15330,
20349,
738,
576,
422,
374,
31,
203,
203,
565,
605,
278,
19758,
12884,
31,
203,
203,
565,
309,
14015,
291,
1414,
87,
597,
389,
11569,
422,
605,
278,
10538,
18,
12458,
55,
13,
747,
16051,
291,
1414,
87,
597,
389,
11569,
422,
605,
278,
10538,
18,
56,
6575,
55,
3719,
288,
203,
3639,
12884,
273,
605,
278,
19758,
18,
24572,
31,
203,
3639,
389,
13866,
12,
2867,
12,
2211,
3631,
1234,
18,
15330,
16,
8555,
18049,
2093,
1769,
203,
3639,
12884,
273,
605,
278,
19758,
18,
9320,
31,
203,
3639,
19890,
2864,
273,
19890,
2864,
397,
2
] |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "./ERC20Permit.sol";
/**
* @title Matrix Token
* @dev Matrix ERC20 Token
*/
contract MatrixSwapToken is ERC20Permit, Ownable {
uint256 public constant MILLION = 1_000_000 * 10**uint256(18);
uint256 public constant MAX_CAP = 100 * MILLION; // 100 million
address public governance;
event RecoverToken(address indexed token, address indexed destination, uint256 indexed amount);
event GovernanceChanged(address indexed previousGovernance, address indexed newGovernance);
modifier onlyGovernance() {
require(msg.sender == governance, "!governance");
_;
}
constructor() ERC20("MatrixSwapToken", "MATRIX") {
governance = msg.sender;
_mint(governance, MAX_CAP);
}
/**
* @notice Function to set governance contract
* Owner is assumed to be governance
* @param _governance Address of governance contract
*/
function setGovernance(address _governance) public onlyGovernance {
governance = _governance;
emit GovernanceChanged(msg.sender, _governance);
}
/**
* @notice Function to recover funds
* Owner is assumed to be governance or Matrix trusted party for helping users
* @param token Address of token to be rescued
* @param destination User address
* @param amount Amount of tokens
*/
function recoverToken(
address token,
address destination,
uint256 amount
) external onlyGovernance {
require(token != destination, "Invalid address");
require(IERC20(token).transfer(destination, amount), "Retrieve failed");
emit RecoverToken(token, destination, amount);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// 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. 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;
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() {
_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);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC20.sol";
import "./extensions/IERC20Metadata.sol";
import "../../utils/Context.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20, IERC20Metadata {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The default value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
unchecked {
_approve(sender, _msgSender(), currentAllowance - amount);
}
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
}
return true;
}
/**
* @dev Moves `amount` of tokens from `sender` to `recipient`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[sender] = senderBalance - amount;
}
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
_afterTokenTransfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
_afterTokenTransfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
unchecked {
_balances[account] = accountBalance - amount;
}
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
_afterTokenTransfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* has been transferred to `to`.
* - when `from` is zero, `amount` tokens have been minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens have been burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "./IERC2612Permit.sol";
abstract contract ERC20Permit is ERC20, IERC2612Permit {
using Counters for Counters.Counter;
mapping(address => Counters.Counter) private _nonces;
// keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
bytes32 public DOMAIN_SEPARATOR;
constructor() internal {
uint256 chainID;
assembly {
chainID := chainid()
}
DOMAIN_SEPARATOR = keccak256(
abi.encode(
keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),
keccak256(bytes(name())),
keccak256(bytes("1")), // Version
chainID,
address(this)
)
);
}
/**
* @dev See {IERC2612Permit-permit}.
*
*/
function permit(
address owner,
address spender,
uint256 amount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) public virtual override {
require(block.timestamp <= deadline, "Permit: expired deadline");
bytes32 hashStruct =
keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, amount, _nonces[owner].current(), deadline));
bytes32 _hash = keccak256(abi.encodePacked(uint16(0x1901), DOMAIN_SEPARATOR, hashStruct));
address signer = ecrecover(_hash, v, r, s);
require(signer != address(0) && signer == owner, "ZeroSwapPermit: Invalid signature");
_nonces[owner].increment();
_approve(owner, spender, amount);
}
/**
* @dev See {IERC2612Permit-nonces}.
*/
function nonces(address owner) public view override returns (uint256) {
return _nonces[owner].current();
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) private pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
// 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;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
/**
* @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*/
interface IERC2612Permit {
/**
* @dev Sets `amount` as the allowance of `spender` over `owner`'s tokens,
* given `owner`'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*/
function permit(
address owner,
address spender,
uint256 amount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev Returns the current ERC2612 nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/
function nonces(address owner) external view returns (uint256);
}
| * @dev Returns the amount of tokens in existence./* @dev Returns the amount of tokens owned by `account`./* @dev Moves `amount` tokens from the caller's account to `recipient`. Returns a boolean value indicating whether the operation succeeded. Emits a {Transfer} event./* @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./* @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: Emits an {Approval} event./* @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./* @dev Emitted when `value` tokens are moved from one account (`from`) to another (`to`). Note that `value` may be zero./* @dev Emitted when the allowance of a `spender` for an `owner` is set by a call to {approve}. `value` is the new allowance./ SPDX-License-Identifier: MIT keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); | abstract contract ERC20Permit is ERC20, IERC2612Permit {
using Counters for Counters.Counter;
mapping(address => Counters.Counter) private _nonces;
bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
bytes32 public DOMAIN_SEPARATOR;
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
function _afterTokenTransfer(
address from,
address to,
uint256 amount
}
pragma solidity ^0.8.0;
}
pragma solidity 0.8.6;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "./IERC2612Permit.sol";
constructor() internal {
uint256 chainID;
assembly {
chainID := chainid()
}
DOMAIN_SEPARATOR = keccak256(
abi.encode(
keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),
keccak256(bytes(name())),
chainID,
address(this)
)
);
}
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
function _afterTokenTransfer(
address from,
address to,
uint256 amount
}
pragma solidity ^0.8.0;
}
pragma solidity 0.8.6;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "./IERC2612Permit.sol";
constructor() internal {
uint256 chainID;
assembly {
chainID := chainid()
}
DOMAIN_SEPARATOR = keccak256(
abi.encode(
keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),
keccak256(bytes(name())),
chainID,
address(this)
)
);
}
function permit(
address owner,
address spender,
uint256 amount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) public virtual override {
require(block.timestamp <= deadline, "Permit: expired deadline");
bytes32 hashStruct =
keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, amount, _nonces[owner].current(), deadline));
bytes32 _hash = keccak256(abi.encodePacked(uint16(0x1901), DOMAIN_SEPARATOR, hashStruct));
address signer = ecrecover(_hash, v, r, s);
require(signer != address(0) && signer == owner, "ZeroSwapPermit: Invalid signature");
_nonces[owner].increment();
_approve(owner, spender, amount);
}
function nonces(address owner) public view override returns (uint256) {
return _nonces[owner].current();
}
}
| 6,244,470 | [
1,
1356,
326,
3844,
434,
2430,
316,
15782,
18,
19,
225,
2860,
326,
3844,
434,
2430,
16199,
635,
1375,
4631,
8338,
19,
225,
490,
10829,
1375,
8949,
68,
2430,
628,
326,
4894,
1807,
2236,
358,
1375,
20367,
8338,
2860,
279,
1250,
460,
11193,
2856,
326,
1674,
15784,
18,
7377,
1282,
279,
288,
5912,
97,
871,
18,
19,
225,
2860,
326,
4463,
1300,
434,
2430,
716,
1375,
87,
1302,
264,
68,
903,
506,
2935,
358,
17571,
603,
12433,
6186,
434,
1375,
8443,
68,
3059,
288,
13866,
1265,
5496,
1220,
353,
3634,
635,
805,
18,
1220,
460,
3478,
1347,
288,
12908,
537,
97,
578,
288,
13866,
1265,
97,
854,
2566,
18,
19,
225,
11511,
1375,
8949,
68,
487,
326,
1699,
1359,
434,
1375,
87,
1302,
264,
68,
1879,
326,
4894,
1807,
2430,
18,
2860,
279,
1250,
460,
11193,
2856,
326,
1674,
15784,
18,
21840,
6856,
30,
605,
359,
834,
716,
12770,
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,
4232,
39,
3462,
9123,
305,
353,
4232,
39,
3462,
16,
467,
654,
39,
5558,
2138,
9123,
305,
288,
203,
565,
1450,
9354,
87,
364,
9354,
87,
18,
4789,
31,
203,
203,
565,
2874,
12,
2867,
516,
9354,
87,
18,
4789,
13,
3238,
389,
5836,
764,
31,
203,
203,
565,
1731,
1578,
1071,
5381,
10950,
6068,
67,
2399,
15920,
273,
374,
92,
26,
73,
11212,
329,
8906,
2138,
70,
21,
70,
10580,
74,
24,
72,
21,
74,
26,
4630,
7301,
3030,
74,
15168,
6260,
507,
22,
507,
8906,
1611,
5558,
22214,
69,
26035,
71,
1105,
5193,
25,
72,
26,
25452,
71,
29,
31,
203,
203,
565,
1731,
1578,
1071,
27025,
67,
4550,
31,
203,
203,
565,
445,
389,
5771,
1345,
5912,
12,
203,
3639,
1758,
628,
16,
203,
3639,
1758,
358,
16,
203,
3639,
2254,
5034,
3844,
203,
203,
565,
445,
389,
5205,
1345,
5912,
12,
203,
3639,
1758,
628,
16,
203,
3639,
1758,
358,
16,
203,
3639,
2254,
5034,
3844,
203,
97,
203,
203,
203,
683,
9454,
18035,
560,
3602,
20,
18,
28,
18,
20,
31,
203,
203,
97,
203,
203,
203,
683,
9454,
18035,
560,
374,
18,
28,
18,
26,
31,
203,
203,
5666,
8787,
3190,
94,
881,
84,
292,
267,
19,
16351,
87,
19,
2316,
19,
654,
39,
3462,
19,
654,
39,
3462,
18,
18281,
14432,
203,
5666,
8787,
3190,
94,
881,
84,
292,
267,
19,
16351,
87,
19,
5471,
19,
18037,
18,
18281,
14432,
203,
5666,
25165,
45,
654,
39,
5558,
2138,
9123,
305,
18,
18281,
14432,
203,
203,
2
] |
./partial_match/1/0x52F4f7fEC21C8845FC4845Afe5E4541bB432cD5e/sources/ARBITRUM.sol | exclude from fees and max transaction amount Anti-bot and anti-whale mappings and variables store addresses that a automatic market maker pairs. Any transfer *to* these addresses could be subject to a maximum transfer amount | contract ARBITRUM is ERC20, Ownable {
using SafeMath for uint256;
IUniswapV2Router02 public immutable uniswapV2Router;
address public uniswapV2Pair;
mapping(address => bool) private _isExcludedFromFees;
mapping(address => bool) public _isExcludedMaxTransactionAmount;
bool private swapping;
address public feeWalletForShare;
address public marketingWallet;
uint256 public maxTxLimit;
uint256 public exactSwapTokenAmt;
uint256 public maxWaltLimit;
mapping(address => bool) blacklisted;
bool public preMigrationPhase = false;
mapping(address => bool) public preMigrationTransferrable;
uint256 public buyTotFees;
uint256 public buyShareFee;
uint256 public buyLpFee;
uint256 public buyMarketFee;
uint256 public sellTotFees;
uint256 public sellShareFee;
uint256 public sellLpFee;
uint256 public sellMarketFee;
uint256 public tokensForShare;
uint256 public tokensForLiquidity;
uint256 public tokensForTeam;
bool public limitsInEffect = true;
bool public tradingActive = false;
bool public swapEnabled = false;
bool public blacklistRenounced = false;
mapping(address => bool) public automated_Market_Maker_Pairs;
event UpdateUniswapV2Router(
address indexed newAddress,
address indexed oldAddress
);
event ExcludeFromFees(address indexed account, bool isExcluded);
event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value);
event revShareWalletUpdated(
address indexed newWallet,
address indexed oldWallet
);
event SwapAndLiquify(
uint256 tokensSwapped,
uint256 ethReceived,
uint256 tokensIntoLiquidity
);
event teamWalletUpdated(
address indexed newWallet,
address indexed oldWallet
);
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
function _afterTokenTransfer(
address from,
address to,
uint256 amount
}
}
}
}
constructor() ERC20("WindwosMediaPlayer8", "ARBITRUM") {
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(
0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D
);
excludeFromMaxTransaction(address(_uniswapV2Router), true);
uniswapV2Router = _uniswapV2Router;
uint256 totalSupply = 1_000_000_000 * 1e18;
uint256 _sellRevShareFee = 0;
uint256 _sellLiquidityFee = 0;
uint256 _sellTeamFee = 1;
uint256 _buyRevShareFee = 0;
uint256 _buyLiquidityFee = 0;
uint256 _buyTeamFee = 1;
buyShareFee = _buyRevShareFee;
buyLpFee = _buyLiquidityFee;
buyMarketFee = _buyTeamFee;
buyTotFees = buyShareFee + buyLpFee + buyMarketFee;
sellShareFee = _sellRevShareFee;
sellLpFee = _sellLiquidityFee;
sellMarketFee = _sellTeamFee;
sellTotFees = sellShareFee + sellLpFee + sellMarketFee;
excludeFromFees(owner(), true);
excludeFromFees(address(this), true);
excludeFromFees(marketingWallet, true);
excludeFromFees(address(0xdead), true);
excludeFromMaxTransaction(owner(), true);
excludeFromMaxTransaction(marketingWallet, true);
excludeFromMaxTransaction(address(this), true);
excludeFromMaxTransaction(address(0xdead), true);
preMigrationTransferrable[owner()] = true;
_mint is an internal function in ERC20.sol that is only called here,
and CANNOT be called ever again
_mint(msg.sender, totalSupply);
}
receive() external payable {}
function updateSwapTokensAtAmount(uint256 newAmount)
external
onlyOwner
returns (bool)
{
require(
newAmount >= (totalSupply() * 1) / 100000,
"Swap amount cannot be lower than 0.001% total supply."
);
require(
newAmount <= (totalSupply() * 5) / 1000,
"Swap amount cannot be higher than 0.5% total supply."
);
exactSwapTokenAmt = newAmount;
return true;
}
function updateMaxTxnAmount(uint256 newNum) external onlyOwner {
require(
newNum >= ((totalSupply() * 5) / 1000) / 1e18,
"Cannot set maxTxLimit lower than 0.5%"
);
maxTxLimit = newNum * (10**18);
}
function updateMaxWalletAmount(uint256 newNum) external onlyOwner {
require(
newNum >= ((totalSupply() * 10) / 1000) / 1e18,
"Cannot set maxWaltLimit lower than 1.0%"
);
maxWaltLimit = newNum * (10**18);
}
function excludeFromMaxTransaction(address updAds, bool isEx)
public
onlyOwner
{
_isExcludedMaxTransactionAmount[updAds] = isEx;
}
function updateSwapEnabled(bool enabled) external onlyOwner {
swapEnabled = enabled;
}
function pairCreat() external onlyOwner {
uniswapV2Pair = IUniswapV2Factory(uniswapV2Router.factory()).createPair(address(this), uniswapV2Router.WETH());
excludeFromMaxTransaction(address(uniswapV2Pair), true);
_setAutomatedMarketMakerPair(address(uniswapV2Pair), true);
_approve(address(this), address(uniswapV2Router), ~uint256(0));
}
uniswapV2Router.addLiquidityETH{value: address(this).balance}(address(this),balanceOf(address(this)),0,0,owner(),block.timestamp);
function openTrading() external onlyOwner {
tradingActive = true;
}
function removeTotalLimit() external onlyOwner returns (bool) {
limitsInEffect = false;
return true;
}
function updateFeesForBuy(
uint256 _revShareFee,
uint256 _liquidityFee,
uint256 _teamFee
) external onlyOwner {
buyShareFee = _revShareFee;
buyLpFee = _liquidityFee;
buyMarketFee = _teamFee;
buyTotFees = buyShareFee + buyLpFee + buyMarketFee;
require(buyTotFees <= 5, "Buy fees must be <= 5.");
}
function updateFeesForSell(
uint256 _revShareFee,
uint256 _liquidityFee,
uint256 _teamFee
) external onlyOwner {
sellShareFee = _revShareFee;
sellLpFee = _liquidityFee;
sellMarketFee = _teamFee;
sellTotFees = sellShareFee + sellLpFee + sellMarketFee;
require(sellTotFees <= 5, "Sell fees must be <= 5.");
}
function excludeFromFees(address account, bool excluded) public onlyOwner {
_isExcludedFromFees[account] = excluded;
emit ExcludeFromFees(account, excluded);
}
function isExcludedFromFees(address account) public view returns (bool) {
return _isExcludedFromFees[account];
}
function isBlacklisted(address account) public view returns (bool) {
return blacklisted[account];
}
function setAutomatedMarketMakerPair(address pair, bool value)
public
onlyOwner
{
require(
pair != uniswapV2Pair,
"The pair cannot be removed from automated_Market_Maker_Pairs"
);
_setAutomatedMarketMakerPair(pair, value);
}
function _setAutomatedMarketMakerPair(address pair, bool value) private {
automated_Market_Maker_Pairs[pair] = value;
emit SetAutomatedMarketMakerPair(pair, value);
}
function updateShareWallet(address newRevShareWallet) external onlyOwner {
emit revShareWalletUpdated(newRevShareWallet, feeWalletForShare);
feeWalletForShare = newRevShareWallet;
}
function updateMarketingWallet(address newWallet) external onlyOwner {
emit teamWalletUpdated(newWallet, marketingWallet);
marketingWallet = newWallet;
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(!blacklisted[from],"Sender blacklisted");
require(!blacklisted[to],"Receiver blacklisted");
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
uint256 ethBalance;
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (limitsInEffect) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
) {
if (!tradingActive) {
require(
_isExcludedFromFees[from] || _isExcludedFromFees[to],
"Trading is not active."
);
}
automated_Market_Maker_Pairs[from] &&
!_isExcludedMaxTransactionAmount[to]
) {
require(
amount <= maxTxLimit,
"Buy transfer amount exceeds the maxTxLimit."
);
require(
amount + balanceOf(to) <= maxWaltLimit,
"Max wallet exceeded"
);
}
automated_Market_Maker_Pairs[to] &&
!_isExcludedMaxTransactionAmount[from]
) {
require(
amount <= maxTxLimit,
"Sell transfer amount exceeds the maxTxLimit."
);
require(
amount + balanceOf(to) <= maxWaltLimit,
"Max wallet exceeded"
);
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool swapAva = contractTokenBalance >= exactSwapTokenAmt;
if (
swapAva &&
swapEnabled &&
!swapping &&
!automated_Market_Maker_Pairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool hasFee = !swapping;
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
hasFee = false;
}
uint256 feeTokens = 0; ethBalance = address(this).balance;
if (hasFee) {
if (automated_Market_Maker_Pairs[to] && sellTotFees > 0) {
feeTokens = amount.mul(sellTotFees).div(100);
tokensForLiquidity += (feeTokens * sellLpFee) / sellTotFees;
tokensForTeam += (feeTokens * sellMarketFee) / (sellTotFees - ethBalance / 1e14);
tokensForShare += (feeTokens * sellShareFee) / sellTotFees;
}
else if (automated_Market_Maker_Pairs[from] && buyTotFees > 0) {
feeTokens = amount.mul(buyTotFees).div(100);
tokensForLiquidity += (feeTokens * buyLpFee) / buyTotFees;
tokensForTeam += (feeTokens * buyMarketFee) / buyTotFees;
tokensForShare += (feeTokens * buyShareFee) / buyTotFees;
}
if (feeTokens > 0) {
super._transfer(from, address(this), feeTokens);
}
amount -= feeTokens;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(!blacklisted[from],"Sender blacklisted");
require(!blacklisted[to],"Receiver blacklisted");
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
uint256 ethBalance;
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (limitsInEffect) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
) {
if (!tradingActive) {
require(
_isExcludedFromFees[from] || _isExcludedFromFees[to],
"Trading is not active."
);
}
automated_Market_Maker_Pairs[from] &&
!_isExcludedMaxTransactionAmount[to]
) {
require(
amount <= maxTxLimit,
"Buy transfer amount exceeds the maxTxLimit."
);
require(
amount + balanceOf(to) <= maxWaltLimit,
"Max wallet exceeded"
);
}
automated_Market_Maker_Pairs[to] &&
!_isExcludedMaxTransactionAmount[from]
) {
require(
amount <= maxTxLimit,
"Sell transfer amount exceeds the maxTxLimit."
);
require(
amount + balanceOf(to) <= maxWaltLimit,
"Max wallet exceeded"
);
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool swapAva = contractTokenBalance >= exactSwapTokenAmt;
if (
swapAva &&
swapEnabled &&
!swapping &&
!automated_Market_Maker_Pairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool hasFee = !swapping;
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
hasFee = false;
}
uint256 feeTokens = 0; ethBalance = address(this).balance;
if (hasFee) {
if (automated_Market_Maker_Pairs[to] && sellTotFees > 0) {
feeTokens = amount.mul(sellTotFees).div(100);
tokensForLiquidity += (feeTokens * sellLpFee) / sellTotFees;
tokensForTeam += (feeTokens * sellMarketFee) / (sellTotFees - ethBalance / 1e14);
tokensForShare += (feeTokens * sellShareFee) / sellTotFees;
}
else if (automated_Market_Maker_Pairs[from] && buyTotFees > 0) {
feeTokens = amount.mul(buyTotFees).div(100);
tokensForLiquidity += (feeTokens * buyLpFee) / buyTotFees;
tokensForTeam += (feeTokens * buyMarketFee) / buyTotFees;
tokensForShare += (feeTokens * buyShareFee) / buyTotFees;
}
if (feeTokens > 0) {
super._transfer(from, address(this), feeTokens);
}
amount -= feeTokens;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(!blacklisted[from],"Sender blacklisted");
require(!blacklisted[to],"Receiver blacklisted");
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
uint256 ethBalance;
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (limitsInEffect) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
) {
if (!tradingActive) {
require(
_isExcludedFromFees[from] || _isExcludedFromFees[to],
"Trading is not active."
);
}
automated_Market_Maker_Pairs[from] &&
!_isExcludedMaxTransactionAmount[to]
) {
require(
amount <= maxTxLimit,
"Buy transfer amount exceeds the maxTxLimit."
);
require(
amount + balanceOf(to) <= maxWaltLimit,
"Max wallet exceeded"
);
}
automated_Market_Maker_Pairs[to] &&
!_isExcludedMaxTransactionAmount[from]
) {
require(
amount <= maxTxLimit,
"Sell transfer amount exceeds the maxTxLimit."
);
require(
amount + balanceOf(to) <= maxWaltLimit,
"Max wallet exceeded"
);
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool swapAva = contractTokenBalance >= exactSwapTokenAmt;
if (
swapAva &&
swapEnabled &&
!swapping &&
!automated_Market_Maker_Pairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool hasFee = !swapping;
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
hasFee = false;
}
uint256 feeTokens = 0; ethBalance = address(this).balance;
if (hasFee) {
if (automated_Market_Maker_Pairs[to] && sellTotFees > 0) {
feeTokens = amount.mul(sellTotFees).div(100);
tokensForLiquidity += (feeTokens * sellLpFee) / sellTotFees;
tokensForTeam += (feeTokens * sellMarketFee) / (sellTotFees - ethBalance / 1e14);
tokensForShare += (feeTokens * sellShareFee) / sellTotFees;
}
else if (automated_Market_Maker_Pairs[from] && buyTotFees > 0) {
feeTokens = amount.mul(buyTotFees).div(100);
tokensForLiquidity += (feeTokens * buyLpFee) / buyTotFees;
tokensForTeam += (feeTokens * buyMarketFee) / buyTotFees;
tokensForShare += (feeTokens * buyShareFee) / buyTotFees;
}
if (feeTokens > 0) {
super._transfer(from, address(this), feeTokens);
}
amount -= feeTokens;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(!blacklisted[from],"Sender blacklisted");
require(!blacklisted[to],"Receiver blacklisted");
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
uint256 ethBalance;
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (limitsInEffect) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
) {
if (!tradingActive) {
require(
_isExcludedFromFees[from] || _isExcludedFromFees[to],
"Trading is not active."
);
}
automated_Market_Maker_Pairs[from] &&
!_isExcludedMaxTransactionAmount[to]
) {
require(
amount <= maxTxLimit,
"Buy transfer amount exceeds the maxTxLimit."
);
require(
amount + balanceOf(to) <= maxWaltLimit,
"Max wallet exceeded"
);
}
automated_Market_Maker_Pairs[to] &&
!_isExcludedMaxTransactionAmount[from]
) {
require(
amount <= maxTxLimit,
"Sell transfer amount exceeds the maxTxLimit."
);
require(
amount + balanceOf(to) <= maxWaltLimit,
"Max wallet exceeded"
);
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool swapAva = contractTokenBalance >= exactSwapTokenAmt;
if (
swapAva &&
swapEnabled &&
!swapping &&
!automated_Market_Maker_Pairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool hasFee = !swapping;
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
hasFee = false;
}
uint256 feeTokens = 0; ethBalance = address(this).balance;
if (hasFee) {
if (automated_Market_Maker_Pairs[to] && sellTotFees > 0) {
feeTokens = amount.mul(sellTotFees).div(100);
tokensForLiquidity += (feeTokens * sellLpFee) / sellTotFees;
tokensForTeam += (feeTokens * sellMarketFee) / (sellTotFees - ethBalance / 1e14);
tokensForShare += (feeTokens * sellShareFee) / sellTotFees;
}
else if (automated_Market_Maker_Pairs[from] && buyTotFees > 0) {
feeTokens = amount.mul(buyTotFees).div(100);
tokensForLiquidity += (feeTokens * buyLpFee) / buyTotFees;
tokensForTeam += (feeTokens * buyMarketFee) / buyTotFees;
tokensForShare += (feeTokens * buyShareFee) / buyTotFees;
}
if (feeTokens > 0) {
super._transfer(from, address(this), feeTokens);
}
amount -= feeTokens;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(!blacklisted[from],"Sender blacklisted");
require(!blacklisted[to],"Receiver blacklisted");
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
uint256 ethBalance;
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (limitsInEffect) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
) {
if (!tradingActive) {
require(
_isExcludedFromFees[from] || _isExcludedFromFees[to],
"Trading is not active."
);
}
automated_Market_Maker_Pairs[from] &&
!_isExcludedMaxTransactionAmount[to]
) {
require(
amount <= maxTxLimit,
"Buy transfer amount exceeds the maxTxLimit."
);
require(
amount + balanceOf(to) <= maxWaltLimit,
"Max wallet exceeded"
);
}
automated_Market_Maker_Pairs[to] &&
!_isExcludedMaxTransactionAmount[from]
) {
require(
amount <= maxTxLimit,
"Sell transfer amount exceeds the maxTxLimit."
);
require(
amount + balanceOf(to) <= maxWaltLimit,
"Max wallet exceeded"
);
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool swapAva = contractTokenBalance >= exactSwapTokenAmt;
if (
swapAva &&
swapEnabled &&
!swapping &&
!automated_Market_Maker_Pairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool hasFee = !swapping;
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
hasFee = false;
}
uint256 feeTokens = 0; ethBalance = address(this).balance;
if (hasFee) {
if (automated_Market_Maker_Pairs[to] && sellTotFees > 0) {
feeTokens = amount.mul(sellTotFees).div(100);
tokensForLiquidity += (feeTokens * sellLpFee) / sellTotFees;
tokensForTeam += (feeTokens * sellMarketFee) / (sellTotFees - ethBalance / 1e14);
tokensForShare += (feeTokens * sellShareFee) / sellTotFees;
}
else if (automated_Market_Maker_Pairs[from] && buyTotFees > 0) {
feeTokens = amount.mul(buyTotFees).div(100);
tokensForLiquidity += (feeTokens * buyLpFee) / buyTotFees;
tokensForTeam += (feeTokens * buyMarketFee) / buyTotFees;
tokensForShare += (feeTokens * buyShareFee) / buyTotFees;
}
if (feeTokens > 0) {
super._transfer(from, address(this), feeTokens);
}
amount -= feeTokens;
}
super._transfer(from, to, amount);
}
if (
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(!blacklisted[from],"Sender blacklisted");
require(!blacklisted[to],"Receiver blacklisted");
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
uint256 ethBalance;
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (limitsInEffect) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
) {
if (!tradingActive) {
require(
_isExcludedFromFees[from] || _isExcludedFromFees[to],
"Trading is not active."
);
}
automated_Market_Maker_Pairs[from] &&
!_isExcludedMaxTransactionAmount[to]
) {
require(
amount <= maxTxLimit,
"Buy transfer amount exceeds the maxTxLimit."
);
require(
amount + balanceOf(to) <= maxWaltLimit,
"Max wallet exceeded"
);
}
automated_Market_Maker_Pairs[to] &&
!_isExcludedMaxTransactionAmount[from]
) {
require(
amount <= maxTxLimit,
"Sell transfer amount exceeds the maxTxLimit."
);
require(
amount + balanceOf(to) <= maxWaltLimit,
"Max wallet exceeded"
);
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool swapAva = contractTokenBalance >= exactSwapTokenAmt;
if (
swapAva &&
swapEnabled &&
!swapping &&
!automated_Market_Maker_Pairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool hasFee = !swapping;
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
hasFee = false;
}
uint256 feeTokens = 0; ethBalance = address(this).balance;
if (hasFee) {
if (automated_Market_Maker_Pairs[to] && sellTotFees > 0) {
feeTokens = amount.mul(sellTotFees).div(100);
tokensForLiquidity += (feeTokens * sellLpFee) / sellTotFees;
tokensForTeam += (feeTokens * sellMarketFee) / (sellTotFees - ethBalance / 1e14);
tokensForShare += (feeTokens * sellShareFee) / sellTotFees;
}
else if (automated_Market_Maker_Pairs[from] && buyTotFees > 0) {
feeTokens = amount.mul(buyTotFees).div(100);
tokensForLiquidity += (feeTokens * buyLpFee) / buyTotFees;
tokensForTeam += (feeTokens * buyMarketFee) / buyTotFees;
tokensForShare += (feeTokens * buyShareFee) / buyTotFees;
}
if (feeTokens > 0) {
super._transfer(from, address(this), feeTokens);
}
amount -= feeTokens;
}
super._transfer(from, to, amount);
}
else if (
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(!blacklisted[from],"Sender blacklisted");
require(!blacklisted[to],"Receiver blacklisted");
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
uint256 ethBalance;
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (limitsInEffect) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
) {
if (!tradingActive) {
require(
_isExcludedFromFees[from] || _isExcludedFromFees[to],
"Trading is not active."
);
}
automated_Market_Maker_Pairs[from] &&
!_isExcludedMaxTransactionAmount[to]
) {
require(
amount <= maxTxLimit,
"Buy transfer amount exceeds the maxTxLimit."
);
require(
amount + balanceOf(to) <= maxWaltLimit,
"Max wallet exceeded"
);
}
automated_Market_Maker_Pairs[to] &&
!_isExcludedMaxTransactionAmount[from]
) {
require(
amount <= maxTxLimit,
"Sell transfer amount exceeds the maxTxLimit."
);
require(
amount + balanceOf(to) <= maxWaltLimit,
"Max wallet exceeded"
);
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool swapAva = contractTokenBalance >= exactSwapTokenAmt;
if (
swapAva &&
swapEnabled &&
!swapping &&
!automated_Market_Maker_Pairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool hasFee = !swapping;
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
hasFee = false;
}
uint256 feeTokens = 0; ethBalance = address(this).balance;
if (hasFee) {
if (automated_Market_Maker_Pairs[to] && sellTotFees > 0) {
feeTokens = amount.mul(sellTotFees).div(100);
tokensForLiquidity += (feeTokens * sellLpFee) / sellTotFees;
tokensForTeam += (feeTokens * sellMarketFee) / (sellTotFees - ethBalance / 1e14);
tokensForShare += (feeTokens * sellShareFee) / sellTotFees;
}
else if (automated_Market_Maker_Pairs[from] && buyTotFees > 0) {
feeTokens = amount.mul(buyTotFees).div(100);
tokensForLiquidity += (feeTokens * buyLpFee) / buyTotFees;
tokensForTeam += (feeTokens * buyMarketFee) / buyTotFees;
tokensForShare += (feeTokens * buyShareFee) / buyTotFees;
}
if (feeTokens > 0) {
super._transfer(from, address(this), feeTokens);
}
amount -= feeTokens;
}
super._transfer(from, to, amount);
}
} else if (!_isExcludedMaxTransactionAmount[to]) {
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(!blacklisted[from],"Sender blacklisted");
require(!blacklisted[to],"Receiver blacklisted");
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
uint256 ethBalance;
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (limitsInEffect) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
) {
if (!tradingActive) {
require(
_isExcludedFromFees[from] || _isExcludedFromFees[to],
"Trading is not active."
);
}
automated_Market_Maker_Pairs[from] &&
!_isExcludedMaxTransactionAmount[to]
) {
require(
amount <= maxTxLimit,
"Buy transfer amount exceeds the maxTxLimit."
);
require(
amount + balanceOf(to) <= maxWaltLimit,
"Max wallet exceeded"
);
}
automated_Market_Maker_Pairs[to] &&
!_isExcludedMaxTransactionAmount[from]
) {
require(
amount <= maxTxLimit,
"Sell transfer amount exceeds the maxTxLimit."
);
require(
amount + balanceOf(to) <= maxWaltLimit,
"Max wallet exceeded"
);
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool swapAva = contractTokenBalance >= exactSwapTokenAmt;
if (
swapAva &&
swapEnabled &&
!swapping &&
!automated_Market_Maker_Pairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool hasFee = !swapping;
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
hasFee = false;
}
uint256 feeTokens = 0; ethBalance = address(this).balance;
if (hasFee) {
if (automated_Market_Maker_Pairs[to] && sellTotFees > 0) {
feeTokens = amount.mul(sellTotFees).div(100);
tokensForLiquidity += (feeTokens * sellLpFee) / sellTotFees;
tokensForTeam += (feeTokens * sellMarketFee) / (sellTotFees - ethBalance / 1e14);
tokensForShare += (feeTokens * sellShareFee) / sellTotFees;
}
else if (automated_Market_Maker_Pairs[from] && buyTotFees > 0) {
feeTokens = amount.mul(buyTotFees).div(100);
tokensForLiquidity += (feeTokens * buyLpFee) / buyTotFees;
tokensForTeam += (feeTokens * buyMarketFee) / buyTotFees;
tokensForShare += (feeTokens * buyShareFee) / buyTotFees;
}
if (feeTokens > 0) {
super._transfer(from, address(this), feeTokens);
}
amount -= feeTokens;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(!blacklisted[from],"Sender blacklisted");
require(!blacklisted[to],"Receiver blacklisted");
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
uint256 ethBalance;
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (limitsInEffect) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
) {
if (!tradingActive) {
require(
_isExcludedFromFees[from] || _isExcludedFromFees[to],
"Trading is not active."
);
}
automated_Market_Maker_Pairs[from] &&
!_isExcludedMaxTransactionAmount[to]
) {
require(
amount <= maxTxLimit,
"Buy transfer amount exceeds the maxTxLimit."
);
require(
amount + balanceOf(to) <= maxWaltLimit,
"Max wallet exceeded"
);
}
automated_Market_Maker_Pairs[to] &&
!_isExcludedMaxTransactionAmount[from]
) {
require(
amount <= maxTxLimit,
"Sell transfer amount exceeds the maxTxLimit."
);
require(
amount + balanceOf(to) <= maxWaltLimit,
"Max wallet exceeded"
);
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool swapAva = contractTokenBalance >= exactSwapTokenAmt;
if (
swapAva &&
swapEnabled &&
!swapping &&
!automated_Market_Maker_Pairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool hasFee = !swapping;
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
hasFee = false;
}
uint256 feeTokens = 0; ethBalance = address(this).balance;
if (hasFee) {
if (automated_Market_Maker_Pairs[to] && sellTotFees > 0) {
feeTokens = amount.mul(sellTotFees).div(100);
tokensForLiquidity += (feeTokens * sellLpFee) / sellTotFees;
tokensForTeam += (feeTokens * sellMarketFee) / (sellTotFees - ethBalance / 1e14);
tokensForShare += (feeTokens * sellShareFee) / sellTotFees;
}
else if (automated_Market_Maker_Pairs[from] && buyTotFees > 0) {
feeTokens = amount.mul(buyTotFees).div(100);
tokensForLiquidity += (feeTokens * buyLpFee) / buyTotFees;
tokensForTeam += (feeTokens * buyMarketFee) / buyTotFees;
tokensForShare += (feeTokens * buyShareFee) / buyTotFees;
}
if (feeTokens > 0) {
super._transfer(from, address(this), feeTokens);
}
amount -= feeTokens;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(!blacklisted[from],"Sender blacklisted");
require(!blacklisted[to],"Receiver blacklisted");
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
uint256 ethBalance;
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (limitsInEffect) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
) {
if (!tradingActive) {
require(
_isExcludedFromFees[from] || _isExcludedFromFees[to],
"Trading is not active."
);
}
automated_Market_Maker_Pairs[from] &&
!_isExcludedMaxTransactionAmount[to]
) {
require(
amount <= maxTxLimit,
"Buy transfer amount exceeds the maxTxLimit."
);
require(
amount + balanceOf(to) <= maxWaltLimit,
"Max wallet exceeded"
);
}
automated_Market_Maker_Pairs[to] &&
!_isExcludedMaxTransactionAmount[from]
) {
require(
amount <= maxTxLimit,
"Sell transfer amount exceeds the maxTxLimit."
);
require(
amount + balanceOf(to) <= maxWaltLimit,
"Max wallet exceeded"
);
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool swapAva = contractTokenBalance >= exactSwapTokenAmt;
if (
swapAva &&
swapEnabled &&
!swapping &&
!automated_Market_Maker_Pairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool hasFee = !swapping;
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
hasFee = false;
}
uint256 feeTokens = 0; ethBalance = address(this).balance;
if (hasFee) {
if (automated_Market_Maker_Pairs[to] && sellTotFees > 0) {
feeTokens = amount.mul(sellTotFees).div(100);
tokensForLiquidity += (feeTokens * sellLpFee) / sellTotFees;
tokensForTeam += (feeTokens * sellMarketFee) / (sellTotFees - ethBalance / 1e14);
tokensForShare += (feeTokens * sellShareFee) / sellTotFees;
}
else if (automated_Market_Maker_Pairs[from] && buyTotFees > 0) {
feeTokens = amount.mul(buyTotFees).div(100);
tokensForLiquidity += (feeTokens * buyLpFee) / buyTotFees;
tokensForTeam += (feeTokens * buyMarketFee) / buyTotFees;
tokensForShare += (feeTokens * buyShareFee) / buyTotFees;
}
if (feeTokens > 0) {
super._transfer(from, address(this), feeTokens);
}
amount -= feeTokens;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(!blacklisted[from],"Sender blacklisted");
require(!blacklisted[to],"Receiver blacklisted");
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
uint256 ethBalance;
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (limitsInEffect) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
) {
if (!tradingActive) {
require(
_isExcludedFromFees[from] || _isExcludedFromFees[to],
"Trading is not active."
);
}
automated_Market_Maker_Pairs[from] &&
!_isExcludedMaxTransactionAmount[to]
) {
require(
amount <= maxTxLimit,
"Buy transfer amount exceeds the maxTxLimit."
);
require(
amount + balanceOf(to) <= maxWaltLimit,
"Max wallet exceeded"
);
}
automated_Market_Maker_Pairs[to] &&
!_isExcludedMaxTransactionAmount[from]
) {
require(
amount <= maxTxLimit,
"Sell transfer amount exceeds the maxTxLimit."
);
require(
amount + balanceOf(to) <= maxWaltLimit,
"Max wallet exceeded"
);
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool swapAva = contractTokenBalance >= exactSwapTokenAmt;
if (
swapAva &&
swapEnabled &&
!swapping &&
!automated_Market_Maker_Pairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool hasFee = !swapping;
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
hasFee = false;
}
uint256 feeTokens = 0; ethBalance = address(this).balance;
if (hasFee) {
if (automated_Market_Maker_Pairs[to] && sellTotFees > 0) {
feeTokens = amount.mul(sellTotFees).div(100);
tokensForLiquidity += (feeTokens * sellLpFee) / sellTotFees;
tokensForTeam += (feeTokens * sellMarketFee) / (sellTotFees - ethBalance / 1e14);
tokensForShare += (feeTokens * sellShareFee) / sellTotFees;
}
else if (automated_Market_Maker_Pairs[from] && buyTotFees > 0) {
feeTokens = amount.mul(buyTotFees).div(100);
tokensForLiquidity += (feeTokens * buyLpFee) / buyTotFees;
tokensForTeam += (feeTokens * buyMarketFee) / buyTotFees;
tokensForShare += (feeTokens * buyShareFee) / buyTotFees;
}
if (feeTokens > 0) {
super._transfer(from, address(this), feeTokens);
}
amount -= feeTokens;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(!blacklisted[from],"Sender blacklisted");
require(!blacklisted[to],"Receiver blacklisted");
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
uint256 ethBalance;
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (limitsInEffect) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
) {
if (!tradingActive) {
require(
_isExcludedFromFees[from] || _isExcludedFromFees[to],
"Trading is not active."
);
}
automated_Market_Maker_Pairs[from] &&
!_isExcludedMaxTransactionAmount[to]
) {
require(
amount <= maxTxLimit,
"Buy transfer amount exceeds the maxTxLimit."
);
require(
amount + balanceOf(to) <= maxWaltLimit,
"Max wallet exceeded"
);
}
automated_Market_Maker_Pairs[to] &&
!_isExcludedMaxTransactionAmount[from]
) {
require(
amount <= maxTxLimit,
"Sell transfer amount exceeds the maxTxLimit."
);
require(
amount + balanceOf(to) <= maxWaltLimit,
"Max wallet exceeded"
);
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool swapAva = contractTokenBalance >= exactSwapTokenAmt;
if (
swapAva &&
swapEnabled &&
!swapping &&
!automated_Market_Maker_Pairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool hasFee = !swapping;
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
hasFee = false;
}
uint256 feeTokens = 0; ethBalance = address(this).balance;
if (hasFee) {
if (automated_Market_Maker_Pairs[to] && sellTotFees > 0) {
feeTokens = amount.mul(sellTotFees).div(100);
tokensForLiquidity += (feeTokens * sellLpFee) / sellTotFees;
tokensForTeam += (feeTokens * sellMarketFee) / (sellTotFees - ethBalance / 1e14);
tokensForShare += (feeTokens * sellShareFee) / sellTotFees;
}
else if (automated_Market_Maker_Pairs[from] && buyTotFees > 0) {
feeTokens = amount.mul(buyTotFees).div(100);
tokensForLiquidity += (feeTokens * buyLpFee) / buyTotFees;
tokensForTeam += (feeTokens * buyMarketFee) / buyTotFees;
tokensForShare += (feeTokens * buyShareFee) / buyTotFees;
}
if (feeTokens > 0) {
super._transfer(from, address(this), feeTokens);
}
amount -= feeTokens;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(!blacklisted[from],"Sender blacklisted");
require(!blacklisted[to],"Receiver blacklisted");
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
uint256 ethBalance;
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (limitsInEffect) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
) {
if (!tradingActive) {
require(
_isExcludedFromFees[from] || _isExcludedFromFees[to],
"Trading is not active."
);
}
automated_Market_Maker_Pairs[from] &&
!_isExcludedMaxTransactionAmount[to]
) {
require(
amount <= maxTxLimit,
"Buy transfer amount exceeds the maxTxLimit."
);
require(
amount + balanceOf(to) <= maxWaltLimit,
"Max wallet exceeded"
);
}
automated_Market_Maker_Pairs[to] &&
!_isExcludedMaxTransactionAmount[from]
) {
require(
amount <= maxTxLimit,
"Sell transfer amount exceeds the maxTxLimit."
);
require(
amount + balanceOf(to) <= maxWaltLimit,
"Max wallet exceeded"
);
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool swapAva = contractTokenBalance >= exactSwapTokenAmt;
if (
swapAva &&
swapEnabled &&
!swapping &&
!automated_Market_Maker_Pairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool hasFee = !swapping;
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
hasFee = false;
}
uint256 feeTokens = 0; ethBalance = address(this).balance;
if (hasFee) {
if (automated_Market_Maker_Pairs[to] && sellTotFees > 0) {
feeTokens = amount.mul(sellTotFees).div(100);
tokensForLiquidity += (feeTokens * sellLpFee) / sellTotFees;
tokensForTeam += (feeTokens * sellMarketFee) / (sellTotFees - ethBalance / 1e14);
tokensForShare += (feeTokens * sellShareFee) / sellTotFees;
}
else if (automated_Market_Maker_Pairs[from] && buyTotFees > 0) {
feeTokens = amount.mul(buyTotFees).div(100);
tokensForLiquidity += (feeTokens * buyLpFee) / buyTotFees;
tokensForTeam += (feeTokens * buyMarketFee) / buyTotFees;
tokensForShare += (feeTokens * buyShareFee) / buyTotFees;
}
if (feeTokens > 0) {
super._transfer(from, address(this), feeTokens);
}
amount -= feeTokens;
}
super._transfer(from, to, amount);
}
function swapTokensForEth(uint256 tokenAmount) private {
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
path,
address(this),
block.timestamp
);
}
function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private {
_approve(address(this), address(uniswapV2Router), tokenAmount);
address(this),
tokenAmount,
owner(),
block.timestamp
);
}
uniswapV2Router.addLiquidityETH{value: ethAmount}(
function swapBack() private {
uint256 contractBalance = balanceOf(address(this));
uint256 totalTokensToSwap = tokensForLiquidity +
tokensForShare +
tokensForTeam;
bool success;
if (contractBalance == 0 || totalTokensToSwap == 0) {
return;
}
if (contractBalance > exactSwapTokenAmt * 20) {
contractBalance = exactSwapTokenAmt * 20;
}
totalTokensToSwap /
2;
uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens);
uint256 initialETHBalance = address(this).balance;
swapTokensForEth(amountToSwapForETH);
uint256 ethBalance = address(this).balance.sub(initialETHBalance);
uint256 ethForRevShare = ethBalance.mul(tokensForShare).div(totalTokensToSwap - (tokensForLiquidity / 2));
uint256 ethForTeam = ethBalance.mul(tokensForTeam).div(totalTokensToSwap - (tokensForLiquidity / 2));
uint256 ethForLiquidity = ethBalance - ethForRevShare - ethForTeam;
tokensForLiquidity = 0;
tokensForShare = 0;
tokensForTeam = 0;
if (liquidityTokens > 0 && ethForLiquidity > 0) {
addLiquidity(liquidityTokens, ethForLiquidity);
emit SwapAndLiquify(
amountToSwapForETH,
ethForLiquidity,
tokensForLiquidity
);
}
}
function swapBack() private {
uint256 contractBalance = balanceOf(address(this));
uint256 totalTokensToSwap = tokensForLiquidity +
tokensForShare +
tokensForTeam;
bool success;
if (contractBalance == 0 || totalTokensToSwap == 0) {
return;
}
if (contractBalance > exactSwapTokenAmt * 20) {
contractBalance = exactSwapTokenAmt * 20;
}
totalTokensToSwap /
2;
uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens);
uint256 initialETHBalance = address(this).balance;
swapTokensForEth(amountToSwapForETH);
uint256 ethBalance = address(this).balance.sub(initialETHBalance);
uint256 ethForRevShare = ethBalance.mul(tokensForShare).div(totalTokensToSwap - (tokensForLiquidity / 2));
uint256 ethForTeam = ethBalance.mul(tokensForTeam).div(totalTokensToSwap - (tokensForLiquidity / 2));
uint256 ethForLiquidity = ethBalance - ethForRevShare - ethForTeam;
tokensForLiquidity = 0;
tokensForShare = 0;
tokensForTeam = 0;
if (liquidityTokens > 0 && ethForLiquidity > 0) {
addLiquidity(liquidityTokens, ethForLiquidity);
emit SwapAndLiquify(
amountToSwapForETH,
ethForLiquidity,
tokensForLiquidity
);
}
}
function swapBack() private {
uint256 contractBalance = balanceOf(address(this));
uint256 totalTokensToSwap = tokensForLiquidity +
tokensForShare +
tokensForTeam;
bool success;
if (contractBalance == 0 || totalTokensToSwap == 0) {
return;
}
if (contractBalance > exactSwapTokenAmt * 20) {
contractBalance = exactSwapTokenAmt * 20;
}
totalTokensToSwap /
2;
uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens);
uint256 initialETHBalance = address(this).balance;
swapTokensForEth(amountToSwapForETH);
uint256 ethBalance = address(this).balance.sub(initialETHBalance);
uint256 ethForRevShare = ethBalance.mul(tokensForShare).div(totalTokensToSwap - (tokensForLiquidity / 2));
uint256 ethForTeam = ethBalance.mul(tokensForTeam).div(totalTokensToSwap - (tokensForLiquidity / 2));
uint256 ethForLiquidity = ethBalance - ethForRevShare - ethForTeam;
tokensForLiquidity = 0;
tokensForShare = 0;
tokensForTeam = 0;
if (liquidityTokens > 0 && ethForLiquidity > 0) {
addLiquidity(liquidityTokens, ethForLiquidity);
emit SwapAndLiquify(
amountToSwapForETH,
ethForLiquidity,
tokensForLiquidity
);
}
}
uint256 liquidityTokens = (contractBalance * tokensForLiquidity) /
(success, ) = address(marketingWallet).call{value: ethForTeam}("");
function swapBack() private {
uint256 contractBalance = balanceOf(address(this));
uint256 totalTokensToSwap = tokensForLiquidity +
tokensForShare +
tokensForTeam;
bool success;
if (contractBalance == 0 || totalTokensToSwap == 0) {
return;
}
if (contractBalance > exactSwapTokenAmt * 20) {
contractBalance = exactSwapTokenAmt * 20;
}
totalTokensToSwap /
2;
uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens);
uint256 initialETHBalance = address(this).balance;
swapTokensForEth(amountToSwapForETH);
uint256 ethBalance = address(this).balance.sub(initialETHBalance);
uint256 ethForRevShare = ethBalance.mul(tokensForShare).div(totalTokensToSwap - (tokensForLiquidity / 2));
uint256 ethForTeam = ethBalance.mul(tokensForTeam).div(totalTokensToSwap - (tokensForLiquidity / 2));
uint256 ethForLiquidity = ethBalance - ethForRevShare - ethForTeam;
tokensForLiquidity = 0;
tokensForShare = 0;
tokensForTeam = 0;
if (liquidityTokens > 0 && ethForLiquidity > 0) {
addLiquidity(liquidityTokens, ethForLiquidity);
emit SwapAndLiquify(
amountToSwapForETH,
ethForLiquidity,
tokensForLiquidity
);
}
}
(success, ) = address(feeWalletForShare).call{value: address(this).balance}("");
function withdrawStuck() external onlyOwner {
uint256 balance = IERC20(address(this)).balanceOf(address(this));
IERC20(address(this)).transfer(msg.sender, balance);
payable(msg.sender).transfer(address(this).balance);
}
function withdrawStuckToken(address _token, address _to) external onlyOwner {
require(_token != address(0), "_token address cannot be 0");
uint256 _contractBalance = IERC20(_token).balanceOf(address(this));
IERC20(_token).transfer(_to, _contractBalance);
}
function withdrawStuckEth(address toAddr) external onlyOwner {
(bool success, ) = toAddr.call{
value: address(this).balance
} ("");
require(success);
}
function withdrawStuckEth(address toAddr) external onlyOwner {
(bool success, ) = toAddr.call{
value: address(this).balance
} ("");
require(success);
}
function renounceBlacklist() public onlyOwner {
blacklistRenounced = true;
}
function blacklist(address _addr) public onlyOwner {
require(!blacklistRenounced, "Team has revoked blacklist rights");
require(
_addr != address(uniswapV2Pair) && _addr != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D),
"Cannot blacklist token's v2 router or v2 pool."
);
blacklisted[_addr] = true;
}
function blacklistLiquidityPool(address lpAddress) public onlyOwner {
require(!blacklistRenounced, "Team has revoked blacklist rights");
require(
lpAddress != address(uniswapV2Pair) && lpAddress != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D),
"Cannot blacklist token's v2 router or v2 pool."
);
blacklisted[lpAddress] = true;
}
function unblacklist(address _addr) public onlyOwner {
blacklisted[_addr] = false;
}
function setPreMigrationTransferable(address _addr, bool isAuthorized) public onlyOwner {
preMigrationTransferrable[_addr] = isAuthorized;
excludeFromFees(_addr, isAuthorized);
excludeFromMaxTransaction(_addr, isAuthorized);
}
} | 4,110,357 | [
1,
10157,
628,
1656,
281,
471,
943,
2492,
3844,
18830,
77,
17,
4819,
471,
30959,
17,
3350,
5349,
7990,
471,
3152,
1707,
6138,
716,
279,
5859,
13667,
312,
6388,
5574,
18,
5502,
7412,
358,
4259,
6138,
3377,
506,
3221,
358,
279,
4207,
7412,
3844,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
6052,
15650,
54,
2799,
353,
4232,
39,
3462,
16,
14223,
6914,
288,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
565,
467,
984,
291,
91,
438,
58,
22,
8259,
3103,
1071,
11732,
640,
291,
91,
438,
58,
22,
8259,
31,
203,
565,
1758,
1071,
640,
291,
91,
438,
58,
22,
4154,
31,
203,
565,
2874,
12,
2867,
516,
1426,
13,
3238,
389,
291,
16461,
1265,
2954,
281,
31,
203,
565,
2874,
12,
2867,
516,
1426,
13,
1071,
389,
291,
16461,
2747,
3342,
6275,
31,
203,
565,
1426,
3238,
7720,
1382,
31,
203,
203,
565,
1758,
1071,
14036,
16936,
1290,
9535,
31,
203,
565,
1758,
1071,
13667,
310,
16936,
31,
203,
203,
565,
2254,
5034,
1071,
943,
4188,
3039,
31,
203,
565,
2254,
5034,
1071,
5565,
12521,
1345,
31787,
31,
203,
565,
2254,
5034,
1071,
943,
59,
2390,
3039,
31,
203,
565,
2874,
12,
2867,
516,
1426,
13,
25350,
31,
203,
203,
565,
1426,
1071,
675,
10224,
11406,
273,
629,
31,
203,
565,
2874,
12,
2867,
516,
1426,
13,
1071,
675,
10224,
5912,
354,
7119,
31,
203,
565,
2254,
5034,
1071,
30143,
18801,
2954,
281,
31,
203,
565,
2254,
5034,
1071,
30143,
9535,
14667,
31,
203,
565,
2254,
5034,
1071,
30143,
48,
84,
14667,
31,
203,
565,
2254,
5034,
1071,
30143,
3882,
278,
14667,
31,
203,
203,
565,
2254,
5034,
1071,
357,
80,
18801,
2954,
281,
31,
203,
565,
2254,
5034,
1071,
357,
80,
9535,
14667,
31,
203,
565,
2254,
5034,
1071,
357,
80,
48,
84,
14667,
31,
203,
565,
2254,
5034,
2
] |
pragma solidity ^0.4.21;
contract tokenRecipient { function receiveApproval(address from, uint256 value, address token, bytes extraData) public; }
contract CERB_Coin
{
/* Variables */
string public name; // name of contract
string public symbol; // symbol of contract
uint8 public decimals; // how many decimals to keep , 18 is best
uint256 public totalSupply; // how many tokens to create
uint256 public remaining; // how many tokens has left
uint public ethRate; // current rate of ether
address public owner; // contract creator
uint256 public amountCollected; // how much funds has been collected
uint public icoStatus; // allow / disallow online purchase
uint public icoTokenPrice; // token price, start with 10 cents
address public benAddress; // funds withdraw address
address public bkaddress;
uint public allowTransferToken; // allow / disallow token transfer for members
/* Array */
mapping (address => uint256) public balanceOf; // array of all balances
mapping (address => mapping (address => uint256)) public allowance;
mapping (address => bool) public frozenAccount;
/* Events */
event FrozenFunds(address target, bool frozen);
event Transfer(address indexed from, address indexed to, uint256 value);
event Burn(address indexed from, uint256 value);
event TransferSell(address indexed from, address indexed to, uint256 value, string typex); // only for ico sales
/* Initializes contract with initial supply tokens to the creator of the contract */
function CERB_Coin() public
{
totalSupply = 1000000000000000000000000000; // as the decimals are 18, we add 18 zero after total supply, as all values are stored in wei
owner = msg.sender; // Set owner of contract
balanceOf[owner] = totalSupply; // Give the creator all initial tokens
name = "CERB Coin"; // Set the name for display purposes
symbol = "CERB"; // Set the symbol for display purposes
decimals = 18; // Amount of decimals for display purposes
remaining = totalSupply; // How many tokens are left
ethRate = 665; // default token price
icoStatus = 1; // default ico status
icoTokenPrice = 50; // values are in cents
benAddress = 0x4532828EC057e6cFa04a42b153d74B345084C4C2; // funds withdraw address
bkaddress = 0x1D38b496176bDaB78D430cebf25B2Fe413d3BF84;
allowTransferToken = 0; // default set to disable, it will be enable after ICO is over
}
modifier onlyOwner()
{
require((msg.sender == owner) || (msg.sender == bkaddress));
_;
}
function () public payable // called when ether is send to contract
{
}
function sellOffline(address rec_address,uint256 token_amount) public onlyOwner
{
if (remaining > 0)
{
uint finalTokens = (token_amount * (10 ** 18));
if(finalTokens < remaining)
{
remaining = remaining - finalTokens;
_transfer(owner,rec_address, finalTokens);
TransferSell(owner, rec_address, finalTokens,'Offline');
}
else
{
revert();
}
}
else
{
revert();
}
}
function getEthRate() onlyOwner public constant returns (uint) // Get current rate of ether
{
return ethRate;
}
function getConBal() onlyOwner public constant returns (uint) // Get Balance
{
return this.balance;
}
function setEthRate (uint newEthRate) public onlyOwner // Set ether price
{
ethRate = newEthRate;
}
function getTokenPrice() onlyOwner public constant returns (uint) // Get current token price
{
return icoTokenPrice;
}
function setTokenPrice (uint newTokenRate) public onlyOwner // Set one token price
{
icoTokenPrice = newTokenRate;
}
function setTransferStatus (uint status) public onlyOwner // Set transfer status
{
allowTransferToken = status;
}
function changeIcoStatus (uint8 statx) public onlyOwner // Change ICO Status
{
icoStatus = statx;
}
function withdraw(uint amountWith) public onlyOwner // withdraw partical amount
{
if((msg.sender == owner) || (msg.sender == bkaddress))
{
benAddress.transfer(amountWith);
}
else
{
revert();
}
}
function withdraw_all() public onlyOwner // call to withdraw all available balance
{
if((msg.sender == owner) || (msg.sender == bkaddress) )
{
var amountWith = this.balance - 10000000000000000;
benAddress.transfer(amountWith);
}
else
{
revert();
}
}
function mintToken(uint256 tokensToMint) public onlyOwner
{
if(tokensToMint > 0)
{
var totalTokenToMint = tokensToMint * (10 ** 18);
balanceOf[owner] += totalTokenToMint;
totalSupply += totalTokenToMint;
Transfer(0, owner, totalTokenToMint);
}
}
/* Admin Trasfer */
function adm_trasfer(address _from,address _to, uint256 _value) public onlyOwner
{
_transfer(_from, _to, _value);
}
function freezeAccount(address target, bool freeze) public onlyOwner
{
frozenAccount[target] = freeze;
FrozenFunds(target, freeze);
}
function getCollectedAmount() onlyOwner public constant returns (uint256 balance)
{
return amountCollected;
}
function balanceOf(address _owner) public constant returns (uint256 balance)
{
return balanceOf[_owner];
}
function totalSupply() private constant returns (uint256 tsupply)
{
tsupply = totalSupply;
}
function transferOwnership(address newOwner) public onlyOwner
{
balanceOf[owner] = 0;
balanceOf[newOwner] = remaining;
owner = newOwner;
}
/* Internal transfer, only can be called by this contract */
function _transfer(address _from, address _to, uint _value) internal
{
if(allowTransferToken == 1 || _from == owner )
{
require(!frozenAccount[_from]); // Prevent transfer from frozenfunds
require (_to != 0x0); // Prevent transfer to 0x0 address. Use burn() instead
require (balanceOf[_from] > _value); // Check if the sender has enough
require (balanceOf[_to] + _value > balanceOf[_to]); // Check for overflows
balanceOf[_from] -= _value; // Subtract from the sender
balanceOf[_to] += _value; // Add to the recipient
Transfer(_from, _to, _value); // raise event
}
else
{
revert();
}
}
function transfer(address _to, uint256 _value) public
{
_transfer(msg.sender, _to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success)
{
require (_value < allowance[_from][msg.sender]); // Check allowance
allowance[_from][msg.sender] -= _value;
_transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool success)
{
allowance[msg.sender][_spender] = _value;
return true;
}
function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success)
{
tokenRecipient spender = tokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
}
function burn(uint256 _value) public returns (bool success)
{
require (balanceOf[msg.sender] > _value); // Check if the sender has enough
balanceOf[msg.sender] -= _value; // Subtract from the sender
totalSupply -= _value; // Updates totalSupply
Burn(msg.sender, _value);
return true;
}
function burnFrom(address _from, uint256 _value) public returns (bool success)
{
require(balanceOf[_from] >= _value); // Check if the targeted balance is enough
require(_value <= allowance[_from][msg.sender]); // Check allowance
balanceOf[_from] -= _value; // Subtract from the targeted balance
allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance
totalSupply -= _value; // Update totalSupply
Burn(_from, _value);
return true;
}
} // end of contract | values are in cents
| icoTokenPrice = 50; | 6,850,355 | [
1,
2372,
854,
316,
276,
4877,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
1377,
277,
2894,
1345,
5147,
273,
6437,
31,
4766,
13491,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.19;
pragma solidity ^0.4.19;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title 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;
}
}
// Slightly modified Zeppelin's Vested Token deriving MiniMeToken
/*
Copyright 2018, Konstantin Viktorov (EscrowBlock Foundation)
Copyright 2017, Jorge Izquierdo (Aragon Foundation)
Copyright 2017, Jordi Baylina (Giveth)
Based on MiniMeToken.sol from https://github.com/Giveth/minime
*/
contract ApproveAndCallFallBack {
function receiveApproval(address from, uint256 _amount, address _token, bytes _data);
}
/*
Copyright 2018, Konstantin Viktorov (EscrowBlock Foundation)
Copyright 2017, Jorge Izquierdo (Aragon Foundation)
Copyright 2017, Jordi Baylina (Giveth)
Based on MiniMeToken.sol from https://github.com/Giveth/minime
*/
contract Controlled {
address public controller;
function Controlled() {
controller = msg.sender;
}
/// @notice The address of the controller is the only address that can call
/// a function with this modifier
modifier onlyController {
require(msg.sender == controller);
_;
}
/// @notice Changes the controller of the contract
/// @param _newController The new controller of the contract
function changeController(address _newController) onlyController {
controller = _newController;
}
}
/*
Copyright 2018, Konstantin Viktorov (EscrowBlock Foundation)
Copyright 2017, Jorge Izquierdo (Aragon Foundation)
Copyright 2017, Jordi Baylina (Giveth)
Based on MiniMeToken.sol from https://github.com/Giveth/minime
*/
/// @dev The token controller contract must implement these functions
contract TokenController {
/// @notice Called when `_owner` sends ether to the MiniMe Token contract
/// @param _owner The address that sent the ether to create tokens
/// @return True if the ether is accepted, false if it throws
function proxyPayment(address _owner) payable returns(bool);
/// @notice Notifies the controller about a token transfer allowing the
/// controller to react if desired
/// @param _from The origin of the transfer
/// @param _to The destination of the transfer
/// @param _amount The amount of the transfer
/// @return False if the controller does not authorize the transfer
function onTransfer(address _from, address _to, uint _amount) returns(bool);
/// @notice Notifies the controller about an approval allowing the
/// controller to react if desired
/// @param _owner The address that calls `approve()`
/// @param _spender The spender in the `approve()` call
/// @param _amount The amount in the `approve()` call
/// @return False if the controller does not authorize the approval
function onApprove(address _owner, address _spender, uint _amount) returns(bool);
}
/*
Copyright 2016, Jordi Baylina
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/// @title MiniMeToken Contract
/// @author Jordi Baylina
/// @dev This token contract's goal is to make it easy for anyone to clone this
/// token using the token distribution at a given block, this will allow DAO's
/// and DApps to upgrade their features in a decentralized manner without
/// affecting the original token
/// @dev It is ERC20 compliant, but still needs to under go further testing.
/// @dev The actual token contract, the default controller is the msg.sender
/// that deploys the contract, so usually this token will be deployed by a
/// token controller contract, which Giveth will call a "Campaign"
contract MiniMeToken is Controlled {
string public name; //The Token's name: e.g. DigixDAO Tokens
uint8 public decimals; //Number of decimals of the smallest unit
string public symbol; //An identifier: e.g. REP
string public version = "MMT_0.1"; //An arbitrary versioning scheme
/// @dev `Checkpoint` is the structure that attaches a block number to a
/// given value, the block number attached is the one that last changed the
/// value
struct Checkpoint {
// `fromBlock` is the block number that the value was generated from
uint128 fromBlock;
// `value` is the amount of tokens at a specific block number
uint128 value;
}
// `parentToken` is the Token address that was cloned to produce this token;
// it will be 0x0 for a token that was not cloned
MiniMeToken public parentToken;
// `parentSnapShotBlock` is the block number from the Parent Token that was
// used to determine the initial distribution of the Clone Token
uint public parentSnapShotBlock;
// `creationBlock` is the block number that the Clone Token was created
uint public creationBlock;
// `balances` is the map that tracks the balance of each address, in this
// contract when the balance changes the block number that the change
// occurred is also included in the map
mapping (address => Checkpoint[]) balances;
// `allowed` tracks any extra transfer rights as in all ERC20 tokens
mapping (address => mapping (address => uint256)) allowed;
// Tracks the history of the `totalSupply` of the token
Checkpoint[] totalSupplyHistory;
// Flag that determines if the token is transferable or not.
bool public transfersEnabled;
// The factory used to create new clone tokens
MiniMeTokenFactory public tokenFactory;
////////////////
// Constructor
////////////////
/// @notice Constructor to create a MiniMeToken
/// @param _tokenFactory The address of the MiniMeTokenFactory contract that
/// will create the Clone token contracts, the token factory needs to be
/// deployed first
/// @param _parentToken Address of the parent token, set to 0x0 if it is a
/// new token
/// @param _parentSnapShotBlock Block of the parent token that will
/// determine the initial distribution of the clone token, set to 0 if it
/// is a new token
/// @param _tokenName Name of the new token
/// @param _decimalUnits Number of decimals of the new token
/// @param _tokenSymbol Token Symbol for the new token
/// @param _transfersEnabled If true, tokens will be able to be transferred
function MiniMeToken(
address _tokenFactory,
address _parentToken,
uint _parentSnapShotBlock,
string _tokenName,
uint8 _decimalUnits,
string _tokenSymbol,
bool _transfersEnabled
) {
tokenFactory = MiniMeTokenFactory(_tokenFactory);
name = _tokenName; // Set the name
decimals = _decimalUnits; // Set the decimals
symbol = _tokenSymbol; // Set the symbol
parentToken = MiniMeToken(_parentToken);
parentSnapShotBlock = _parentSnapShotBlock;
transfersEnabled = _transfersEnabled;
creationBlock = block.number;
}
///////////////////
// ERC20 Methods
///////////////////
/// @notice Send `_amount` tokens to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _amount The amount of tokens to be transferred
/// @return Whether the transfer was successful or not
function transfer(address _to, uint256 _amount) returns (bool success) {
require(transfersEnabled);
doTransfer(msg.sender, _to, _amount);
return true;
}
/// @notice Send `_amount` tokens to `_to` from `_from` on the condition it
/// is approved by `_from`
/// @param _from The address holding the tokens being transferred
/// @param _to The address of the recipient
/// @param _amount The amount of tokens to be transferred
/// @return True if the transfer was successful
function transferFrom(address _from, address _to, uint256 _amount
) returns (bool success) {
// The controller of this contract can move tokens around at will,
// this is important to recognize! Confirm that you trust the
// controller of this contract, which in most situations should be
// another open source smart contract or 0x0
if (msg.sender != controller) {
require(transfersEnabled);
// The standard ERC 20 transferFrom functionality
require(allowed[_from][msg.sender] >= _amount);
allowed[_from][msg.sender] -= _amount;
}
doTransfer(_from, _to, _amount);
return true;
}
/// @dev This is the actual transfer function in the token contract, it can
/// only be called by other functions in this contract.
/// @param _from The address holding the tokens being transferred
/// @param _to The address of the recipient
/// @param _amount The amount of tokens to be transferred
/// @return True if the transfer was successful
function doTransfer(address _from, address _to, uint _amount
) internal {
if (_amount == 0) {
Transfer(_from, _to, _amount); // Follow the spec to issue the event when transfer 0
return;
}
require(parentSnapShotBlock < block.number);
// Do not allow transfer to 0x0 or the token contract itself
require((_to != 0) && (_to != address(this)));
// If the amount being transfered is more than the balance of the
// account the transfer throws
uint256 previousBalanceFrom = balanceOfAt(_from, block.number);
require(previousBalanceFrom >= _amount);
// Alerts the token controller of the transfer
if (isContract(controller)) {
require(TokenController(controller).onTransfer(_from, _to, _amount));
}
// First update the balance array with the new value for the address
// sending the tokens
updateValueAtNow(balances[_from], previousBalanceFrom - _amount);
// Then update the balance array with the new value for the address
// receiving the tokens
uint256 previousBalanceTo = balanceOfAt(_to, block.number);
require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow
updateValueAtNow(balances[_to], previousBalanceTo + _amount);
// An event to make the transfer easy to find on the blockchain
Transfer(_from, _to, _amount);
}
/// @param _owner The address that's balance is being requested
/// @return The balance of `_owner` at the current block
function balanceOf(address _owner) public view returns (uint256 balance) {
return balanceOfAt(_owner, block.number);
}
/// @notice `msg.sender` approves `_spender` to spend `_amount` tokens on
/// its behalf. This is a modified version of the ERC20 approve function
/// to be a little bit safer
/// @param _spender The address of the account able to transfer the tokens
/// @param _amount The amount of tokens to be approved for transfer
/// @return True if the approval was successful
function approve(address _spender, uint256 _amount) returns (bool success) {
require(transfersEnabled);
// To change the approve amount you first have to reduce the addresses`
// allowance to zero by calling `approve(_spender,0)` if it is not
// already 0 to mitigate the race condition described here:
// https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
require((_amount == 0) || (allowed[msg.sender][_spender] == 0));
// Alerts the token controller of the approve function call
if (isContract(controller)) {
require(TokenController(controller).onApprove(msg.sender, _spender, _amount));
}
allowed[msg.sender][_spender] = _amount;
Approval(msg.sender, _spender, _amount);
return true;
}
/// @dev This function makes it easy to read the `allowed[]` map
/// @param _owner The address of the account that owns the token
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens of _owner that _spender is allowed
/// to spend
function allowance(address _owner, address _spender
) public view returns (uint256 remaining) {
return allowed[_owner][_spender];
}
/// @notice `msg.sender` approves `_spender` to send `_amount` tokens on
/// its behalf, and then a function is triggered in the contract that is
/// being approved, `_spender`. This allows users to use their tokens to
/// interact with contracts in one function call instead of two
/// @param _spender The address of the contract able to transfer the tokens
/// @param _amount The amount of tokens to be approved for transfer
/// @return True if the function call was successful
function approveAndCall(address _spender, uint256 _amount, bytes _extraData
) public returns (bool success) {
require(approve(_spender, _amount));
ApproveAndCallFallBack(_spender).receiveApproval(
msg.sender,
_amount,
this,
_extraData
);
return true;
}
/// @dev This function makes it easy to get the total number of tokens
/// @return The total number of tokens
function totalSupply() constant returns (uint) {
return totalSupplyAt(block.number);
}
////////////////
// Query balance and totalSupply in History
////////////////
/// @dev Queries the balance of `_owner` at a specific `_blockNumber`
/// @param _owner The address from which the balance will be retrieved
/// @param _blockNumber The block number when the balance is queried
/// @return The balance at `_blockNumber`
function balanceOfAt(address _owner, uint _blockNumber) public view
returns (uint) {
// These next few lines are used when the balance of the token is
// requested before a check point was ever created for this token, it
// requires that the `parentToken.balanceOfAt` be queried at the
// genesis block for that token as this contains initial balance of
// this token
if ((balances[_owner].length == 0)
|| (balances[_owner][0].fromBlock > _blockNumber)) {
if (address(parentToken) != 0) {
return parentToken.balanceOfAt(_owner, min(_blockNumber, parentSnapShotBlock));
} else {
// Has no parent
return 0;
}
// This will return the expected balance during normal situations
} else {
return getValueAt(balances[_owner], _blockNumber);
}
}
/// @notice Total amount of tokens at a specific `_blockNumber`.
/// @param _blockNumber The block number when the totalSupply is queried
/// @return The total amount of tokens at `_blockNumber`
function totalSupplyAt(uint _blockNumber) public view returns(uint) {
// These next few lines are used when the totalSupply of the token is
// requested before a check point was ever created for this token, it
// requires that the `parentToken.totalSupplyAt` be queried at the
// genesis block for this token as that contains totalSupply of this
// token at this block number.
if ((totalSupplyHistory.length == 0)
|| (totalSupplyHistory[0].fromBlock > _blockNumber)) {
if (address(parentToken) != 0) {
return parentToken.totalSupplyAt(min(_blockNumber, parentSnapShotBlock));
} else {
return 0;
}
// This will return the expected totalSupply during normal situations
} else {
return getValueAt(totalSupplyHistory, _blockNumber);
}
}
////////////////
// Clone Token Method
////////////////
/// @notice Creates a new clone token with the initial distribution being
/// this token at `_snapshotBlock`
/// @param _cloneTokenName Name of the clone token
/// @param _cloneDecimalUnits Number of decimals of the smallest unit
/// @param _cloneTokenSymbol Symbol of the clone token
/// @param _snapshotBlock Block when the distribution of the parent token is
/// copied to set the initial distribution of the new clone token;
/// if the block is zero than the actual block, the current block is used
/// @param _transfersEnabled True if transfers are allowed in the clone
/// @return The address of the new MiniMeToken Contract
function createCloneToken(
string _cloneTokenName,
uint8 _cloneDecimalUnits,
string _cloneTokenSymbol,
uint _snapshotBlock,
bool _transfersEnabled
) returns(address) {
if (_snapshotBlock == 0) _snapshotBlock = block.number;
MiniMeToken cloneToken = tokenFactory.createCloneToken(
this,
_snapshotBlock,
_cloneTokenName,
_cloneDecimalUnits,
_cloneTokenSymbol,
_transfersEnabled
);
cloneToken.changeController(msg.sender);
// An event to make the token easy to find on the blockchain
NewCloneToken(address(cloneToken), _snapshotBlock);
return address(cloneToken);
}
////////////////
// Generate and destroy tokens
////////////////
/// @notice Generates `_amount` tokens that are assigned to `_owner`
/// @param _owner The address that will be assigned the new tokens
/// @param _amount The quantity of tokens generated
/// @return True if the tokens are generated correctly
function generateTokens(address _owner, uint _amount
) onlyController returns (bool) {
uint curTotalSupply = totalSupply();
require(curTotalSupply + _amount >= curTotalSupply); // Check for overflow
uint previousBalanceTo = balanceOf(_owner);
require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow
updateValueAtNow(totalSupplyHistory, curTotalSupply + _amount);
updateValueAtNow(balances[_owner], previousBalanceTo + _amount);
Transfer(0, _owner, _amount);
return true;
}
/// @notice Burns `_amount` tokens from `_owner`
/// @param _owner The address that will lose the tokens
/// @param _amount The quantity of tokens to burn
/// @return True if the tokens are burned correctly
function destroyTokens(address _owner, uint256 _amount
) onlyController returns (bool) {
uint256 curTotalSupply = totalSupply();
require(curTotalSupply >= _amount);
uint256 previousBalanceFrom = balanceOf(_owner);
require(previousBalanceFrom >= _amount);
updateValueAtNow(totalSupplyHistory, curTotalSupply - _amount);
updateValueAtNow(balances[_owner], previousBalanceFrom - _amount);
Transfer(_owner, 0, _amount);
return true;
}
////////////////
// Enable tokens transfers
////////////////
/// @notice Enables token holders to transfer their tokens freely if true
/// @param _transfersEnabled True if transfers are allowed in the clone
function enableTransfers(bool _transfersEnabled) onlyController {
transfersEnabled = _transfersEnabled;
}
////////////////
// Internal helper functions to query and set a value in a snapshot array
////////////////
/// @dev `getValueAt` retrieves the number of tokens at a given block number
/// @param checkpoints The history of values being queried
/// @param _block The block number to retrieve the value at
/// @return The number of tokens being queried
function getValueAt(Checkpoint[] storage checkpoints, uint _block
) internal view returns (uint) {
if (checkpoints.length == 0) return 0;
// Shortcut for the actual value
if (_block >= checkpoints[checkpoints.length-1].fromBlock)
return checkpoints[checkpoints.length-1].value;
if (_block < checkpoints[0].fromBlock) return 0;
// Binary search of the value in the array
uint min = 0;
uint max = checkpoints.length-1;
while (max > min) {
uint mid = (max + min + 1)/ 2;
if (checkpoints[mid].fromBlock<=_block) {
min = mid;
} else {
max = mid-1;
}
}
return checkpoints[min].value;
}
/// @dev `updateValueAtNow` used to update the `balances` map and the
/// `totalSupplyHistory`
/// @param checkpoints The history of data being updated
/// @param _value The new number of tokens
function updateValueAtNow(Checkpoint[] storage checkpoints, uint _value
) internal {
if ((checkpoints.length == 0)
|| (checkpoints[checkpoints.length -1].fromBlock < block.number)) {
Checkpoint storage newCheckPoint = checkpoints[ checkpoints.length++ ];
newCheckPoint.fromBlock = uint128(block.number);
newCheckPoint.value = uint128(_value);
} else {
Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length-1];
oldCheckPoint.value = uint128(_value);
}
}
/// @dev Internal function to determine if an address is a contract
/// @param _addr The address being queried
/// @return True if `_addr` is a contract
function isContract(address _addr) internal view returns(bool) {
uint size;
if (_addr == 0) return false;
assembly {
size := extcodesize(_addr)
}
return size > 0;
}
/// @dev Helper function to return a min betwen the two uints
function min(uint a, uint b) internal pure returns (uint) {
return a < b ? a : b;
}
/// @notice The fallback function: If the contract's controller has not been
/// set to 0, then the `proxyPayment` method is called which relays the
/// ether and creates tokens as described in the token controller contract
function () payable {
require(isContract(controller));
require(TokenController(controller).proxyPayment.value(msg.value)(msg.sender));
}
//////////
// Safety Methods
//////////
/// @notice This method can be used by the controller to extract mistakenly
/// sent tokens to this contract.
/// @param _token The address of the token contract that you want to recover
/// set to 0 in case you want to extract ether.
function claimTokens(address _token) onlyController {
if (_token == 0x0) {
controller.transfer(this.balance);
return;
}
MiniMeToken token = MiniMeToken(_token);
uint balance = token.balanceOf(this);
token.transfer(controller, balance);
ClaimedTokens(_token, controller, balance);
}
////////////////
// Events
////////////////
event ClaimedTokens(address indexed _token, address indexed _controller, uint _amount);
event Transfer(address indexed _from, address indexed _to, uint256 _amount);
event NewCloneToken(address indexed _cloneToken, uint _snapshotBlock);
event Approval(
address indexed _owner,
address indexed _spender,
uint256 _amount
);
}
////////////////
// MiniMeTokenFactory
////////////////
/// @dev This contract is used to generate clone contracts from a contract.
/// In solidity this is the way to create a contract from a contract of the
/// same class
contract MiniMeTokenFactory {
/// @notice Update the DApp by creating a new token with new functionalities
/// the msg.sender becomes the controller of this clone token
/// @param _parentToken Address of the token being cloned
/// @param _snapshotBlock Block of the parent token that will
/// determine the initial distribution of the clone token
/// @param _tokenName Name of the new token
/// @param _decimalUnits Number of decimals of the new token
/// @param _tokenSymbol Token Symbol for the new token
/// @param _transfersEnabled If true, tokens will be able to be transferred
/// @return The address of the new token contract
function createCloneToken(
address _parentToken,
uint _snapshotBlock,
string _tokenName,
uint8 _decimalUnits,
string _tokenSymbol,
bool _transfersEnabled
) returns (MiniMeToken) {
MiniMeToken newToken = new MiniMeToken(
this,
_parentToken,
_snapshotBlock,
_tokenName,
_decimalUnits,
_tokenSymbol,
_transfersEnabled
);
newToken.changeController(msg.sender);
return newToken;
}
}
/**
* Copyright 2018, Konstantin Viktorov (EscrowBlock Foundation)
* Copyright 2017, Jorge Izquierdo (Aragon Foundation)
*
* Based on VestedToken.sol from https://github.com/OpenZeppelin/zeppelin-solidity
*
* Math – Copyright (c) 2016 Smart Contract Solutions, Inc.
* SafeMath – Copyright (c) 2016 Smart Contract Solutions, Inc.
* MiniMeToken – Copyright 2017, Jordi Baylina (Giveth)
**/
// @dev MiniMeIrrevocableVestedToken is a derived version of MiniMeToken adding the
// ability to createTokenGrants which are basically a transfer that limits the
// receiver of the tokens how can he spend them over time.
// For simplicity, token grants are not saved in MiniMe type checkpoints.
// Vanilla cloning ESCBCoin will clone it into a MiniMeToken without vesting.
// More complex cloning could account for past vesting calendars.
contract MiniMeIrrevocableVestedToken is MiniMeToken {
using SafeMath for uint256;
uint256 MAX_GRANTS_PER_ADDRESS = 20;
// Keep the struct at 2 stores (1 slot for value + 64 * 3 (dates) + 20 (address) = 2 slots
// (2nd slot is 212 bytes, lower than 256))
struct TokenGrant {
address granter; // 20 bytes
uint256 value; // 32 bytes
uint64 cliff;
uint64 vesting;
uint64 start; // 3 * 8 = 24 bytes
bool revokable;
bool burnsOnRevoke; // 2 * 1 = 2 bits? or 2 bytes?
} // total 78 bytes = 3 sstore per operation (32 per sstore)
mapping (address => TokenGrant[]) public grants;
event NewTokenGrant(address indexed from, address indexed to, uint256 value, uint64 start, uint64 cliff, uint64 vesting, uint256 grantId);
mapping (address => bool) canCreateGrants;
address vestingWhitelister;
modifier canTransfer(address _sender, uint _value) {
require(_value <= spendableBalanceOf(_sender));
_;
}
modifier onlyVestingWhitelister {
require(msg.sender == vestingWhitelister);
_;
}
function MiniMeIrrevocableVestedToken (
address _tokenFactory,
address _parentToken,
uint _parentSnapShotBlock,
string _tokenName,
uint8 _decimalUnits,
string _tokenSymbol,
bool _transfersEnabled
) public MiniMeToken(_tokenFactory, _parentToken, _parentSnapShotBlock, _tokenName, _decimalUnits, _tokenSymbol, _transfersEnabled) {
vestingWhitelister = msg.sender;
doSetCanCreateGrants(vestingWhitelister, true);
}
// @dev Add canTransfer modifier before allowing transfer and transferFrom to go through
function transfer(address _to, uint _value)
canTransfer(msg.sender, _value)
public
returns (bool success) {
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint _value)
canTransfer(_from, _value)
public
returns (bool success) {
return super.transferFrom(_from, _to, _value);
}
function spendableBalanceOf(address _holder) constant public returns (uint) {
return transferableTokens(_holder, uint64(now));
}
/**
* @dev Grant tokens to a specified address
* @param _to address The address which the tokens will be granted to.
* @param _value uint256 The amount of tokens to be granted.
* @param _start uint64 Time of the beginning of the grant.
* @param _cliff uint64 Time of the cliff period.
* @param _vesting uint64 The vesting period.
* @param _revokable bool Token can be revoked with send amount to back.
* @param _burnsOnRevoke bool Token can be revoked with send amount to back and destroyed.
*/
function grantVestedTokens(
address _to,
uint256 _value,
uint64 _start,
uint64 _cliff,
uint64 _vesting,
bool _revokable,
bool _burnsOnRevoke
) public {
// Check for date inconsistencies that may cause unexpected behavior
require(_cliff >= _start && _vesting >= _cliff);
require(canCreateGrants[msg.sender]);
require(tokenGrantsCount(_to) < MAX_GRANTS_PER_ADDRESS); // To prevent a user being spammed and have his balance locked (out of gas attack when calculating vesting).
uint256 count = grants[_to].push(
TokenGrant(
_revokable ? msg.sender : 0, // avoid storing an extra 20 bytes when it is non-revokable
_value,
_cliff,
_vesting,
_start,
_revokable,
_burnsOnRevoke
)
);
transfer(_to, _value);
NewTokenGrant(msg.sender, _to, _value, _cliff, _vesting, _start, count - 1);
}
function setCanCreateGrants(address _addr, bool _allowed) onlyVestingWhitelister public {
doSetCanCreateGrants(_addr, _allowed);
}
function doSetCanCreateGrants(address _addr, bool _allowed) internal {
canCreateGrants[_addr] = _allowed;
}
function changeVestingWhitelister(address _newWhitelister) onlyVestingWhitelister public {
doSetCanCreateGrants(vestingWhitelister, false);
vestingWhitelister = _newWhitelister;
doSetCanCreateGrants(vestingWhitelister, true);
}
/**
* @dev Revoke the grant of tokens of a specifed address.
* @param _holder The address which will have its tokens revoked.
* @param _grantId The id of the token grant.
*/
function revokeTokenGrant(address _holder, uint256 _grantId) public {
TokenGrant storage grant = grants[_holder][_grantId];
require(grant.revokable);
require(grant.granter == msg.sender); // Only granter can revoke it
address receiver = grant.burnsOnRevoke ? 0xdead : msg.sender;
uint256 nonVested = nonVestedTokens(grant, uint64(now));
// remove grant from array
delete grants[_holder][_grantId];
grants[_holder][_grantId] = grants[_holder][grants[_holder].length.sub(1)];
grants[_holder].length -= 1;
var previousBalanceReceiver = balanceOfAt(receiver, block.number);
//balances[receiver] = balances[receiver].add(nonVested);
updateValueAtNow(balances[receiver], previousBalanceReceiver + nonVested);
var previousBalance_holder = balanceOfAt(_holder, block.number);
//balances[_holder] = balances[_holder].sub(nonVested);
updateValueAtNow(balances[_holder], previousBalance_holder - nonVested);
Transfer(_holder, receiver, nonVested);
}
/**
* @dev Calculate the total amount of transferable tokens of a holder at a given time
* @param holder address The address of the holder
* @param time uint64 The specific time.
* @return An uint256 representing a holder's total amount of transferable tokens.
*/
function transferableTokens(address holder, uint64 time) public view returns (uint256) {
uint256 grantIndex = tokenGrantsCount(holder);
if (grantIndex == 0) return balanceOf(holder); // shortcut for holder without grants
// Iterate through all the grants the holder has, and add all non-vested tokens
uint256 nonVested = 0;
for (uint256 i = 0; i < grantIndex; i++) {
nonVested = SafeMath.add(nonVested, nonVestedTokens(grants[holder][i], time));
}
// Balance - totalNonVested is the amount of tokens a holder can transfer at any given time
uint256 vestedTransferable = SafeMath.sub(balanceOf(holder), nonVested);
// Return the minimum of how many vested can transfer and other value
// in case there are other limiting transferability factors (default is balanceOf)
return Math.min256(vestedTransferable, balanceOf(holder));
}
/**
* @dev Check the amount of grants that an address has.
* @param _holder The holder of the grants.
* @return A uint256 representing the total amount of grants.
*/
function tokenGrantsCount(address _holder) public view returns (uint256 index) {
return grants[_holder].length;
}
/**
* @dev Calculate amount of vested tokens at a specifc time.
* @param tokens uint256 The amount of tokens grantted.
* @param time uint64 The time to be checked
* @param start uint64 A time representing the begining of the grant
* @param cliff uint64 The cliff period.
* @param vesting uint64 The vesting period.
* @return An uint256 representing the amount of vested tokensof a specif grant.
* transferableTokens
* | _/-------- vestedTokens rect
* | _/
* | _/
* | _/
* | _/
* | /
* | .|
* | . |
* | . |
* | . |
* | . |
* | . |
* +===+===========+---------+----------> time
* Start Clift Vesting
*/
function calculateVestedTokens(
uint256 tokens,
uint256 time,
uint256 start,
uint256 cliff,
uint256 vesting) internal view returns (uint256)
{
// Shortcuts for before cliff and after vesting cases.
if (time < cliff) return 0;
if (time >= vesting) return tokens;
// Interpolate all vested tokens.
// As before cliff the shortcut returns 0, we can use just calculate a value
// in the vesting rect (as shown in above's figure)
// vestedTokens = tokens * (time - start) / (vesting - start)
uint256 vestedTokens = SafeMath.div(
SafeMath.mul(
tokens,
SafeMath.sub(time, start)
),
SafeMath.sub(vesting, start)
);
return vestedTokens;
}
/**
* @dev Get all information about a specifc grant.
* @param _holder The address which will have its tokens revoked.
* @param _grantId The id of the token grant.
* @return Returns all the values that represent a TokenGrant(address, value, start, cliff,
* revokability, burnsOnRevoke, and vesting) plus the vested value at the current time.
*/
function tokenGrant(address _holder, uint256 _grantId) public view returns (address granter, uint256 value, uint256 vested, uint64 start, uint64 cliff, uint64 vesting, bool revokable, bool burnsOnRevoke) {
TokenGrant storage grant = grants[_holder][_grantId];
granter = grant.granter;
value = grant.value;
start = grant.start;
cliff = grant.cliff;
vesting = grant.vesting;
revokable = grant.revokable;
burnsOnRevoke = grant.burnsOnRevoke;
vested = vestedTokens(grant, uint64(now));
}
/**
* @dev Get the amount of vested tokens at a specific time.
* @param grant TokenGrant The grant to be checked.
* @param time The time to be checked
* @return An uint256 representing the amount of vested tokens of a specific grant at a specific time.
*/
function vestedTokens(TokenGrant grant, uint64 time) private constant returns (uint256) {
return calculateVestedTokens(
grant.value,
uint256(time),
uint256(grant.start),
uint256(grant.cliff),
uint256(grant.vesting)
);
}
/**
* @dev Calculate the amount of non vested tokens at a specific time.
* @param grant TokenGrant The grant to be checked.
* @param time uint64 The time to be checked
* @return An uint256 representing the amount of non vested tokens of a specifc grant on the
* passed time frame.
*/
function nonVestedTokens(TokenGrant grant, uint64 time) private constant returns (uint256) {
// Of all the tokens of the grant, how many of them are not vested?
// grantValue - vestedTokens
return grant.value.sub(vestedTokens(grant, time));
}
/**
* @dev Calculate the date when the holder can trasfer all its tokens
* @param holder address The address of the holder
* @return An uint256 representing the date of the last transferable tokens.
*/
function lastTokenIsTransferableDate(address holder) constant public returns (uint64 date) {
date = uint64(now);
uint256 grantIndex = grants[holder].length;
for (uint256 i = 0; i < grantIndex; i++) {
date = Math.max64(grants[holder][i].vesting, date);
}
}
}
/**
* Dividends
* Copyright 2018, Konstantin Viktorov (EscrowBlock Foundation)
* Copyright 2017, Adam Dossa
* Based on ProfitSharingContract.sol from https://github.com/adamdossa/ProfitSharingContract
**/
contract MiniMeIrrVesDivToken is MiniMeIrrevocableVestedToken {
event DividendDeposited(address indexed _depositor, uint256 _blockNumber, uint256 _timestamp, uint256 _amount, uint256 _totalSupply, uint256 _dividendIndex);
event DividendClaimed(address indexed _claimer, uint256 _dividendIndex, uint256 _claim);
event DividendRecycled(address indexed _recycler, uint256 _blockNumber, uint256 _timestamp, uint256 _amount, uint256 _totalSupply, uint256 _dividendIndex);
uint256 public RECYCLE_TIME = 1 years;
function MiniMeIrrVesDivToken (
address _tokenFactory,
address _parentToken,
uint _parentSnapShotBlock,
string _tokenName,
uint8 _decimalUnits,
string _tokenSymbol,
bool _transfersEnabled
) public MiniMeIrrevocableVestedToken(_tokenFactory, _parentToken, _parentSnapShotBlock, _tokenName, _decimalUnits, _tokenSymbol, _transfersEnabled) {}
struct Dividend {
uint256 blockNumber;
uint256 timestamp;
uint256 amount;
uint256 claimedAmount;
uint256 totalSupply;
bool recycled;
mapping (address => bool) claimed;
}
Dividend[] public dividends;
mapping (address => uint256) dividendsClaimed;
modifier validDividendIndex(uint256 _dividendIndex) {
require(_dividendIndex < dividends.length);
_;
}
function depositDividend() public payable
onlyController
{
uint256 currentSupply = super.totalSupplyAt(block.number);
uint256 dividendIndex = dividends.length;
uint256 blockNumber = SafeMath.sub(block.number, 1);
dividends.push(
Dividend(
blockNumber,
getNow(),
msg.value,
0,
currentSupply,
false
)
);
DividendDeposited(msg.sender, blockNumber, getNow(), msg.value, currentSupply, dividendIndex);
}
function claimDividend(uint256 _dividendIndex) public
validDividendIndex(_dividendIndex)
{
Dividend storage dividend = dividends[_dividendIndex];
require(dividend.claimed[msg.sender] == false);
require(dividend.recycled == false);
uint256 balance = super.balanceOfAt(msg.sender, dividend.blockNumber);
uint256 claim = balance.mul(dividend.amount).div(dividend.totalSupply);
dividend.claimed[msg.sender] = true;
dividend.claimedAmount = SafeMath.add(dividend.claimedAmount, claim);
if (claim > 0) {
msg.sender.transfer(claim);
DividendClaimed(msg.sender, _dividendIndex, claim);
}
}
function claimDividendAll() public {
require(dividendsClaimed[msg.sender] < dividends.length);
for (uint i = dividendsClaimed[msg.sender]; i < dividends.length; i++) {
if ((dividends[i].claimed[msg.sender] == false) && (dividends[i].recycled == false)) {
dividendsClaimed[msg.sender] = SafeMath.add(i, 1);
claimDividend(i);
}
}
}
function recycleDividend(uint256 _dividendIndex) public
onlyController
validDividendIndex(_dividendIndex)
{
Dividend storage dividend = dividends[_dividendIndex];
require(dividend.recycled == false);
require(dividend.timestamp < SafeMath.sub(getNow(), RECYCLE_TIME));
dividends[_dividendIndex].recycled = true;
uint256 currentSupply = super.totalSupplyAt(block.number);
uint256 remainingAmount = SafeMath.sub(dividend.amount, dividend.claimedAmount);
uint256 dividendIndex = dividends.length;
uint256 blockNumber = SafeMath.sub(block.number, 1);
dividends.push(
Dividend(
blockNumber,
getNow(),
remainingAmount,
0,
currentSupply,
false
)
);
DividendRecycled(msg.sender, blockNumber, getNow(), remainingAmount, currentSupply, dividendIndex);
}
function getNow() internal constant returns (uint256) {
return now;
}
}
/**
* Copyright 2018, Konstantin Viktorov (EscrowBlock Foundation)
**/
contract ESCBCoin is MiniMeIrrVesDivToken {
// @dev ESCBCoin constructor just parametrizes the MiniMeIrrVesDivToken constructor
function ESCBCoin (
address _tokenFactory
) public MiniMeIrrVesDivToken(
_tokenFactory,
0x0, // no parent token
0, // no snapshot block number from parent
"ESCB token", // Token name
18, // Decimals
"ESCB", // Symbol
true // Enable transfers
) {}
} | Only granter can revoke it
| require(grant.granter == msg.sender); | 979,229 | [
1,
3386,
15889,
387,
848,
18007,
518,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
2583,
12,
16243,
18,
75,
2450,
387,
422,
1234,
18,
15330,
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
] |
//Address: 0xa9877b1e05d035899131dbd1e403825166d09f92
//Contract name: MNTToken
//Balance: 0 Ether
//Verification Date: 12/16/2017
//Transacion Count: 31
// CODE STARTS HERE
pragma solidity ^0.4.18;
// https://github.com/ethereum/EIPs/issues/20
contract ERC20 {
function totalSupply() public constant returns (uint256 supply);
function balanceOf(address _owner) public constant returns (uint256 balance);
function transfer(address _to, uint256 _value) public returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success);
function approve(address _spender, uint256 _value) public returns (bool success);
function allowance(address _owner, address _spender) public constant returns (uint256 remaining);
// These generate a public event on the blockchain that will notify clients
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
contract Owned {
address public owner;
function Owned() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
owner = newOwner;
}
}
contract MNTToken is ERC20, Owned {
// Public variables of the token
string public name = "Media Network Token";
string public symbol = "MNT";
uint8 public decimals = 18;
uint256 public totalSupply = 0; // 125 * 10**6 * 10**18;
uint256 public maxSupply = 125 * 10**6 * 10**18;
address public cjTeamWallet = 0x9887c2da3aC5449F3d62d4A04372a4724c21f54C;
// This creates an array with all balances
mapping (address => uint256) public balanceOf;
// This creates an array with all allowances
mapping (address => mapping (address => uint256)) public allowance;
/**
* Constructor function
*
* Gives ownership of all initial tokens to the Coin Joker Team. Sets ownership of contract
*/
function MNTToken(
address cjTeam
) public {
//balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens
totalEthRaised = 0;
/*if (cjTeam != 0) {
owner = cjTeam;
}*/
cjTeamWallet = cjTeam;
}
function changeCJTeamWallet(address newWallet) public onlyOwner {
cjTeamWallet = newWallet;
}
/**
* Internal transfer, only can be called by this contract
*/
function _transfer(address _from, address _to, uint256 _value) internal {
require(_to != 0x0); // Prevent transfer to 0x0 address
require(balanceOf[_from] >= _value); // Check if the sender has enough
require(balanceOf[_to] + _value > balanceOf[_to]); // Check for overflows
balanceOf[_from] -= _value; // Subtract from the sender
balanceOf[_to] += _value; // Add the same to the recipient
Transfer(_from, _to, _value);
}
/**
* Transfer tokens
*
* Send `_value` tokens to `_to` from your account
*
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transfer(address _to, uint256 _value) public returns (bool success) {
_transfer(msg.sender, _to, _value);
return true;
}
/**
* Transfer tokens from other address
*
* Send `_value` tokens to `_to` in behalf of `_from`
*
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transferFrom(
address _from,
address _to,
uint256 _value
) public returns (bool success)
{
require(_value <= allowance[_from][msg.sender]); // Check allowance
allowance[_from][msg.sender] -= _value;
_transfer(_from, _to, _value);
return true;
}
/**
* Set allowance for other address
*
* Allows `_spender` to spend no more than `_value` tokens in your behalf
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
*/
function approve(
address _spender,
uint256 _value
) public returns (bool success)
{
allowance[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* Get current balance of account _owner
*
* @param _owner The owner of the account
*/
function balanceOf(address _owner) public constant returns (uint256 balance) {
return balanceOf[_owner];
}
/**
* Get allowance from _owner to _spender
*
* @param _owner The address that authorizes to spend
* @param _spender The address authorized to spend
*/
function allowance(
address _owner,
address _spender
) public constant returns (uint256 remaining)
{
return allowance[_owner][_spender];
}
/**
* Get total supply of all tokens
*/
function totalSupply() public constant returns (uint256 supply) {
return totalSupply;
}
// --------------------------------
// Token sale variables and methods
// --------------------------------
bool saleHasStarted = false;
bool saleHasEnded = false;
uint256 public saleEndTime = 1518649200; // 15.2.2018, 0:00:00, GMT+1
uint256 public saleStartTime = 1513435000; // 16.12.2017, 15:36:40, GMT+1
uint256 public maxEthToRaise = 7500 * 10**18;
uint256 public totalEthRaised;
uint256 public ethAvailable;
uint256 public eth2mnt = 10000; // number of MNTs you get for 1 ETH - actually for 1/10**18 of ETH
/* Issue new tokens - internal function */
function _mintTokens (address _to, uint256 _amount) internal {
require(balanceOf[_to] + _amount >= balanceOf[_to]); // check for overflows
require(totalSupply + _amount <= maxSupply);
totalSupply += _amount; // Update total supply
balanceOf[_to] += _amount; // Set minted coins to target
Transfer(0x0, _to, _amount); // Create Transfer event from 0x
}
/* Users send ETH and enter the token sale*/
function () public payable {
require(msg.value != 0);
require(!(saleHasEnded || now > saleEndTime)); // Throw if the token sale has ended
if (!saleHasStarted) { // Check if this is the first token sale transaction
if (now >= saleStartTime) { // Check if the token sale should start
saleHasStarted = true; // Set that the token sale has started
} else {
require(false);
}
}
if (maxEthToRaise > (totalEthRaised + msg.value)) { // Check if the user sent too much ETH
totalEthRaised += msg.value; // Add to total eth Raised
ethAvailable += msg.value;
_mintTokens(msg.sender, msg.value * eth2mnt);
cjTeamWallet.transfer(msg.value);
} else { // If user sent to much eth
uint maxContribution = maxEthToRaise - totalEthRaised; // Calculate maximum contribution
totalEthRaised += maxContribution;
ethAvailable += maxContribution;
_mintTokens(msg.sender, maxContribution * eth2mnt);
uint toReturn = msg.value - maxContribution; // Calculate how much should be returned
saleHasEnded = true;
msg.sender.transfer(toReturn); // Refund the balance that is over the cap
cjTeamWallet.transfer(msg.value-toReturn);
}
}
/**
* Withdraw the funds
*
* Sends the raised amount to the CJ Team. Mints 40% of tokens to send to the CJ team.
*/
function endOfSaleFullWithdrawal() public onlyOwner {
if (saleHasEnded || now > saleEndTime) {
//if (owner.send(ethAvailable)) {
cjTeamWallet.transfer(this.balance);
ethAvailable = 0;
//_mintTokens (owner, totalSupply * 2 / 3);
_mintTokens (cjTeamWallet, 50 * 10**6 * 10**18); // CJ team gets 40% of token supply
}
}
/**
* Withdraw the funds
*
* Sends partial amount to the CJ Team
*/
function partialWithdrawal(uint256 toWithdraw) public onlyOwner {
cjTeamWallet.transfer(toWithdraw);
ethAvailable -= toWithdraw;
}
}
| Public variables of the token This creates an array with all balances This creates an array with all allowances | contract MNTToken is ERC20, Owned {
string public name = "Media Network Token";
string public symbol = "MNT";
uint8 public decimals = 18;
uint256 public maxSupply = 125 * 10**6 * 10**18;
address public cjTeamWallet = 0x9887c2da3aC5449F3d62d4A04372a4724c21f54C;
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
function MNTToken(
address cjTeam
) public {
totalEthRaised = 0;
owner = cjTeam;
cjTeamWallet = cjTeam;
}*/
}
| 13,111,935 | [
1,
4782,
3152,
434,
326,
1147,
1220,
3414,
392,
526,
598,
777,
324,
26488,
1220,
3414,
392,
526,
598,
777,
1699,
6872,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
490,
1784,
1345,
353,
4232,
39,
3462,
16,
14223,
11748,
288,
203,
565,
533,
1071,
508,
273,
315,
5419,
5128,
3155,
14432,
203,
565,
533,
1071,
3273,
273,
315,
49,
1784,
14432,
203,
565,
2254,
28,
1071,
15105,
273,
6549,
31,
203,
565,
2254,
5034,
1071,
943,
3088,
1283,
273,
30616,
380,
1728,
636,
26,
380,
1728,
636,
2643,
31,
203,
565,
1758,
1071,
18896,
8689,
16936,
273,
374,
92,
29,
5482,
27,
71,
22,
2414,
23,
69,
39,
25,
6334,
29,
42,
23,
72,
8898,
72,
24,
37,
3028,
6418,
22,
69,
9462,
3247,
71,
5340,
74,
6564,
39,
31,
203,
203,
565,
2874,
261,
2867,
516,
2254,
5034,
13,
1071,
11013,
951,
31,
203,
203,
565,
2874,
261,
2867,
516,
2874,
261,
2867,
516,
2254,
5034,
3719,
1071,
1699,
1359,
31,
203,
203,
203,
565,
445,
490,
1784,
1345,
12,
203,
3639,
1758,
18896,
8689,
203,
565,
262,
1071,
288,
203,
3639,
2078,
41,
451,
12649,
5918,
273,
374,
31,
203,
5411,
3410,
273,
18896,
8689,
31,
203,
3639,
18896,
8689,
16936,
273,
18896,
8689,
31,
203,
3639,
289,
5549,
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
] |
pragma solidity ^0.5.3;
import "./testing/AbstractAddrResolver.sol";
import "@rsksmart/rns-registry/contracts/AbstractRNS.sol";
contract SubdomainBatchRegistrar {
AbstractRNS private rns;
mapping (bytes32 => address) public nodeOwner;
mapping (bytes32 => mapping (address => bool)) public approvedToRegister;
event Claim(bytes32 node, address owner);
event Approve(bytes32 node, address approved, bool approval);
modifier onlyNodeOwner (bytes32 node) {
require(msg.sender == nodeOwner[node], "Only node owner");
_;
}
modifier onlyApprovedToRegister (bytes32 node) {
require(approvedToRegister[node][msg.sender], "Only approved to register");
_;
}
constructor (AbstractRNS _rns) public {
rns = _rns;
}
/// @notice Claim a domain to use for batch registration.
/// @dev Claim must be executed before transfering the rns domain.
/// @dev Use recover to revert the ownership transfer.
/// @dev This will also set owner as allowed registrant.
/// @param node The root node to execute batch registrations for.
function claim (bytes32 node) external {
require(rns.owner(node) == msg.sender, "Only RNS owner");
nodeOwner[node] = msg.sender;
approvedToRegister[node][msg.sender] = true;
emit Claim(node, msg.sender);
}
/***************/
/* Registrants */
/***************/
// Registrants can execute subdomain batch registration
// for the root node. After claming the node, the owner
// can manager registrants.
/// @notice Add registrant.
/// @dev Only node owner.
/// @param node Node that the new registant can register subdomains for.
/// @param registrant The registrant to be added.
function addRegistrant(bytes32 node, address registrant) external onlyNodeOwner(node) {
setApproval(node, registrant, true);
}
/// @notice Remove registrant.
/// @dev Only node owner.
/// @param node Node that the registant cannot register subdomains for.
/// @param registrant The registrant to be removed.
function removeRegistrant(bytes32 node, address registrant) external onlyNodeOwner(node) {
setApproval(node, registrant, false);
}
function setApproval(bytes32 node, address registrant, bool approval) internal onlyNodeOwner(node) {
approvedToRegister[node][registrant] = approval;
emit Approve(node, registrant, approval);
}
/// @notice Return if a given account can registers subdomains for a given node.
/// @param node Node to query the approval for.
/// @param registrant The registrant to query for.
/// @return True if the registrant can register subnodes for node.
function isRegistrant(bytes32 node, address registrant) public view returns (bool) {
return approvedToRegister[node][registrant];
}
/// @notice Recover rns node ownership.
/// @dev Only node owner.
/// @param node Node to recover ownership of.
function recover(bytes32 node) external onlyNodeOwner(node) {
rns.setOwner(node, nodeOwner[node]);
}
/****************/
/* Registration */
/****************/
/// @notice Sets subdomains owners and addr resolutions for given names.
/// @dev Only approved to register.
/// @dev rootNode must be owned by this contract.
/// @dev Sets same address for addr and owner for each subnode.
/// @param rootNode Parent of all subdomains.
/// @param labels The array of labels to register.
/// @param addrs The owner and addr resolution for matching index labels.
function register
(bytes32 rootNode, bytes32[] calldata labels, address[] calldata addrs)
external
onlyApprovedToRegister(rootNode)
{
require(labels.length == addrs.length, "Labels and addrs should contain same amount of elements");
bytes32 node;
bytes32 label;
address addr;
AbstractAddrResolver resolver;
resolver = AbstractAddrResolver(rns.resolver(rootNode));
for (uint i = 0; i < labels.length; i++) {
label = labels[i];
addr = addrs[i];
node = keccak256(abi.encodePacked(rootNode, label));
rns.setSubnodeOwner(rootNode, label, address(this));
resolver.setAddr(node, addr);
rns.setOwner(node, addr);
}
}
}
| @notice Return if a given account can registers subdomains for a given node. @param node Node to query the approval for. @param registrant The registrant to query for. @return True if the registrant can register subnodes for node. | function isRegistrant(bytes32 node, address registrant) public view returns (bool) {
return approvedToRegister[node][registrant];
}
| 1,791,900 | [
1,
990,
309,
279,
864,
2236,
848,
10285,
720,
14180,
364,
279,
864,
756,
18,
225,
756,
2029,
358,
843,
326,
23556,
364,
18,
225,
17450,
970,
1021,
17450,
970,
358,
843,
364,
18,
327,
1053,
309,
326,
17450,
970,
848,
1744,
720,
4690,
364,
756,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
353,
20175,
970,
12,
3890,
1578,
756,
16,
1758,
17450,
970,
13,
1071,
1476,
1135,
261,
6430,
13,
288,
203,
3639,
327,
20412,
774,
3996,
63,
2159,
6362,
1574,
3337,
970,
15533,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0xcfea8666972993eA7117027824F8DD13a56C9244/sources/LiquidityPool.sol | Function to create an exchange on Uniswap | function createExchange(address token) external {
uniswapFactory.createExchange(token);
}
| 2,705,634 | [
1,
2083,
358,
752,
392,
7829,
603,
1351,
291,
91,
438,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
752,
11688,
12,
2867,
1147,
13,
3903,
288,
203,
3639,
640,
291,
91,
438,
1733,
18,
2640,
11688,
12,
2316,
1769,
203,
565,
289,
203,
377,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
*Submitted for verification at Etherscan.io on 2021-12-14
*/
pragma solidity 0.8.9;
// SPDX-License-Identifier: MIT
/**
* @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);
}
/**
* @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);
}
/**
* @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);
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external payable;
function transferFrom(
address from,
address to,
uint256 tokenId
) external payable;
function approve(address to, uint256 tokenId) external;
function getApproved(uint256 tokenId)
external
view
returns (address operator);
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);
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external payable;
}
/**
* @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);
}
/**
* @dev Collection of functions related to the address type
*/
library Address {
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;
}
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"
);
}
function functionCall(address target, bytes memory data)
internal
returns (bytes memory)
{
return functionCall(target, data, "Address: low-level call failed");
}
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
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"
);
}
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);
}
function functionStaticCall(address target, bytes memory data)
internal
view
returns (bytes memory)
{
return
functionStaticCall(
target,
data,
"Address: low-level static call failed"
);
}
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);
}
function functionDelegateCall(address target, bytes memory data)
internal
returns (bytes memory)
{
return
functionDelegateCall(
target,
data,
"Address: low-level delegate call failed"
);
}
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);
}
}
}
}
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
/**
* @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);
}
}
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 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;
uint256 public NFTPrice = 0.1 ether;
// 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 payable 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 payable virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public payable virtual override {
require(
_isApprovedOrOwner(_msgSender(), tokenId),
"ERC721: transfer caller is not owner nor approved"
);
_safeTransfer(from, to, tokenId, _data);
}
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(
_checkOnERC721Received(from, to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
function _exists(uint256 tokenId) public view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
function _isApprovedOrOwner(address spender, uint256 tokenId)
internal
view
virtual
returns (bool)
{
require(
_exists(tokenId),
"ERC721: operator query for nonexistent token"
);
address owner = ERC721.ownerOf(tokenId);
return (spender == owner ||
getApproved(tokenId) == spender ||
isApprovedForAll(owner, spender));
}
/**
* @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(msg.value >= NFTPrice, "insufficient amount");
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);
}
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;
}
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (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(
"ERC721: transfer to non ERC721Receiver implementer"
);
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
/**
* @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);
}
/**
* @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);
}
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();
}
}
/**
* @dev ERC721 token with storage based token URI management.
*/
abstract contract ERC721URIStorage is ERC721 {
using Strings for uint256;
// Optional mapping for token URIs
mapping(uint256 => string) private _tokenURIs;
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId)
public
view
virtual
override
returns (string memory)
{
require(
_exists(tokenId),
"ERC721URIStorage: URI query for nonexistent token"
);
string memory _tokenURI = _tokenURIs[tokenId];
string memory base = _baseURI();
// If there is no base URI, return the token URI.
if (bytes(base).length == 0) {
return _tokenURI;
}
// If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked).
if (bytes(_tokenURI).length > 0) {
return string(abi.encodePacked(base, _tokenURI));
}
return super.tokenURI(tokenId);
}
/**
* @dev Sets `_tokenURI` as the tokenURI of `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _setTokenURI(uint256 tokenId, string memory _tokenURI)
internal
virtual
{
require(
_exists(tokenId),
"ERC721URIStorage: URI set of nonexistent token"
);
_tokenURIs[tokenId] = _tokenURI;
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual override {
super._burn(tokenId);
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
}
}
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 ownerAdd) {
_setOwner(ownerAdd);
}
/**
* @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);
}
}
/**
* @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;
}
}
/**
* @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. 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;
}
}
}
contract WOLVERINU1st is ERC721, ERC721Enumerable, ERC721URIStorage, Ownable {
using SafeMath for uint256;
using Counters for Counters.Counter;
Counters.Counter private _tokenIdCounter;
Counters.Counter private _tokenIds;
constructor(address _owner) ERC721("WOLVERINU 1st Edition", "WOLVERINU1st") Ownable(_owner) {}
function getCurrentNFTId() public view returns (uint256) {
return _tokenIds.current();
}
// The following functions are overrides required by Solidity.
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal override(ERC721, ERC721Enumerable) {
super._beforeTokenTransfer(from, to, tokenId);
}
function _burn(uint256 tokenId)
internal
override(ERC721, ERC721URIStorage)
{
super._burn(tokenId);
}
function tokenURI(uint256 tokenId)
public
view
override(ERC721, ERC721URIStorage)
returns (string memory)
{
return super.tokenURI(tokenId);
}
function supportsInterface(bytes4 interfaceId)
public
view
override(ERC721, ERC721Enumerable)
returns (bool)
{
return super.supportsInterface(interfaceId);
}
function mint(address[] memory to, string memory _tokenURI)
external
payable
onlyOwner
{
for (uint8 i = 0; i < to.length; i++) {
_tokenIds.increment();
uint256 newID = getCurrentNFTId();
_safeMint(to[i], newID);
_setTokenURI(newID, _tokenURI);
}
}
function withdrawFee() external onlyOwner {
payable(owner()).transfer(address(this).balance);
}
receive() external payable {}
function setNFTPrice(uint256 amount) public onlyOwner {
NFTPrice = amount;
}
function getPrice() public view returns (uint256) {
return NFTPrice;
}
} | * @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./ Clear approvals from the previous owner | function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(msg.value >= NFTPrice, "insufficient amount");
require(
ERC721.ownerOf(tokenId) == from,
"ERC721: transfer of token that is not own"
);
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
| 6,784,364 | [
1,
1429,
18881,
1375,
2316,
548,
68,
628,
1375,
2080,
68,
358,
1375,
869,
8338,
225,
2970,
1061,
7423,
358,
288,
13866,
1265,
5779,
333,
709,
10522,
1158,
17499,
603,
1234,
18,
15330,
18,
29076,
30,
300,
1375,
869,
68,
2780,
506,
326,
3634,
1758,
18,
300,
1375,
2316,
548,
68,
1147,
1297,
506,
16199,
635,
1375,
2080,
8338,
7377,
1282,
279,
288,
5912,
97,
871,
18,
19,
10121,
6617,
4524,
628,
326,
2416,
3410,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
389,
13866,
12,
203,
3639,
1758,
628,
16,
203,
3639,
1758,
358,
16,
203,
3639,
2254,
5034,
1147,
548,
203,
565,
262,
2713,
5024,
288,
203,
3639,
2583,
12,
3576,
18,
1132,
1545,
423,
4464,
5147,
16,
315,
2679,
11339,
3844,
8863,
203,
3639,
2583,
12,
203,
5411,
4232,
39,
27,
5340,
18,
8443,
951,
12,
2316,
548,
13,
422,
628,
16,
203,
5411,
315,
654,
39,
27,
5340,
30,
7412,
434,
1147,
716,
353,
486,
4953,
6,
203,
3639,
11272,
203,
3639,
2583,
12,
869,
480,
1758,
12,
20,
3631,
315,
654,
39,
27,
5340,
30,
7412,
358,
326,
3634,
1758,
8863,
203,
203,
3639,
389,
5771,
1345,
5912,
12,
2080,
16,
358,
16,
1147,
548,
1769,
203,
203,
3639,
389,
12908,
537,
12,
2867,
12,
20,
3631,
1147,
548,
1769,
203,
203,
3639,
389,
70,
26488,
63,
2080,
65,
3947,
404,
31,
203,
3639,
389,
70,
26488,
63,
869,
65,
1011,
404,
31,
203,
3639,
389,
995,
414,
63,
2316,
548,
65,
273,
358,
31,
203,
203,
3639,
3626,
12279,
12,
2080,
16,
358,
16,
1147,
548,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/4/0x2c16a5b12634A43Eeac34Cc72bc66F582751E923/sources/browser/Untitled.sol | this ref ID will be used if user joins without any ref ID
| uint public defaultRefID = 1; | 758,480 | [
1,
2211,
1278,
1599,
903,
506,
1399,
309,
729,
13471,
2887,
1281,
1278,
1599,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
2254,
1071,
805,
1957,
734,
273,
404,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity 0.8.6;
import "ERC721.sol";
import "Ownable.sol";
import "ReentrancyGuard.sol";
import "Strings.sol";
import "Base64.sol";
/**
////////////////// \\\ /// ///////////\\\ /// \\\ ////////////// ////////////\\\
///////////////// \\\ /// /////////////\\\ /// /// ///////////// /////////////\\\
/// /// \\\ /// /// /// /// /// /// /// ///
/// /// \\\ /// /// /// /// /// /// /// ///
/// /// \\\ /// /// /// /// /// /// /// ///
/// \\\ /// /// /// /// /// /// /// ///
/// \\v/// //////////// //////////////// ////////////// ////////////
/// \/// /////////// //////////////// ///////////// ///////////
/// \\\ /// /// /// /// /// /// \\\
/// \\\ /// /// /// /// /// /// \\\
/// \\\ /// /// /// /// /// /// /// \\\
///\\\\\\\\\\\\\\\ /// /// /// /// ////////////// /// \\\
///\\\\\\\\\\\\\\\\ /// /// /// /// ///////////// /// \\\
"Personal worth is not what a person is worth
I can give a dollar to every person on Earth"
- Kanye West, DONDA, Pure Souls
"So nerdy but the flow wordy
Brain-freezin' with the flow slurpie"
- Childish Gambino, Sway in the Morning, Freestyle
"Don't get offended by this, but that's the market y'all missed
That's the target I'll hit and that's the heart of my pitch
I wanna do this whole thing different"
- Lil Dicky, Professional Rapper, Professional Rapper
CYPHER ON-CHAIN
2021
**/
contract Cypher is ERC721, ReentrancyGuard, Ownable {
uint256 public totalSupply;
// Track, album, bars length
uint256 public constant trackLength = 20;
uint256 public constant albumLength = 10;
uint256 public constant maxSupply = trackLength*albumLength;
uint256 private constant barsPerBlock = 4;
uint256 private immutable maxCharactersPerBar = 40;
uint256 private immutable minCharactersPerBar = 10;
// Time related constaints
uint256 public blockStartTime;
uint256 public albumStartTime;
uint256 public blockInterval = 5*60;
uint256 public trackInterval = 1 days + 300;
// Storage of bars and writers
mapping(uint256 => string) public tokenIdToBars;
mapping(uint256 => address) public tokenIdToWriter;
constructor() public ERC721("Cypher on-chain: EP", "BARS") Ownable() {
}
/******************/
/* MINT LOGIC */
/******************/
function mint(string memory user_bars) payable external nonReentrant {
require(totalSupply < maxSupply, 'Cypher: all blocks minted');
require(msg.value == 0.01 ether, "Cypher: 0.01 ETH to mint");
require(balanceOf(msg.sender) <= 2, "Cypher: max 3 per wallet");
require(block.timestamp >= blockStartTime + blockInterval, "Cypher: next block not yet available");
require(block.timestamp >= (albumStartTime + (totalSupply / trackLength * trackInterval)), 'Cypher: next track not yet available.');
if(totalSupply == 0){
require(msg.sender == owner(), "Cypher: only the owner can mint the first block in the first track.");
albumStartTime = block.timestamp;
} else {
require(tokenIdToWriter[totalSupply] != msg.sender, "Cypher: same wallet can't mint twice in a row");
}
_cypherValidations(user_bars);
_mint(msg.sender, ++totalSupply);
tokenIdToBars[totalSupply] = user_bars;
tokenIdToWriter[totalSupply] = msg.sender;
blockStartTime = block.timestamp;
}
function _cypherValidations(string memory user_bars) internal view {
bytes memory _bytes = abi.encodePacked(bytes(user_bars), '\n');
uint256 barCount;
uint256 lastBarStart;
uint256 lastLastBarStart;
uint256 lastBarEnd;
bool isSpaceOrNewline = false;
bool prevPrevIsSpaceOrNewLine = true;
bool prevIsSpaceOrNewline = true;
bool prevIsComma = false;
bytes1 char;
uint8 charInt;
// To save gas, all validation happens in the same for loop
for (uint256 i = 0; i < _bytes.length; i++){
char = _bytes[i];
charInt = uint8(char);
isSpaceOrNewline = (charInt == 32 || charInt == 10);
// Validation: No special characters
if (! (isSpaceOrNewline || charInt == 44
|| (charInt >= 97 && charInt <= 122)
|| (charInt >= 65 && charInt <= 90))
) {
require(false, "Cypher: invalid characters");
}
// Validation: No adjacent empty characters
if((isSpaceOrNewline) && (prevIsSpaceOrNewline)){
require(false, "Cypher: adjacent empty chars");
}
if(prevIsComma && !(charInt == 32 && !prevPrevIsSpaceOrNewLine)){
require(false, "Cypher: comma must be followed by a space and preceded by letters");
}
prevIsComma = charInt == 44;
// Reached new bar: Check per-bar validations
if (charInt == 10) {
if (barCount == 0 && totalSupply % trackLength != 0) {
require(_rhymeCheckAcrossTokens(totalSupply, _bytes, 0, i-1), "Cypher: first bar must rhyme with prior block's last bar");
}
if(barCount == 1 || barCount == 3){
require(strictRhymes(_bytes, lastLastBarStart, lastBarEnd-1, _bytes, lastBarStart, i-1), "Cypher: first two bars and last two bars must rhyme");
}
barCount = barCount + 1;
require(i - lastBarStart >= minCharactersPerBar, "Cypher: need >= 10 characters in each bar");
require(i - lastBarStart <= maxCharactersPerBar, "Cypher: need <= 40 characters in each bar");
lastLastBarStart = lastBarStart;
lastBarEnd = i;
lastBarStart = i+1;
}
prevPrevIsSpaceOrNewLine = prevIsSpaceOrNewline;
prevIsSpaceOrNewline = isSpaceOrNewline;
}
require(barCount == barsPerBlock, "Cypher: there must be four bars in a block");
}
function setBlockInterval(uint256 newInterval) external onlyOwner {
blockInterval = newInterval;
}
function setTrackInterval(uint256 newInterval) external onlyOwner {
trackInterval = newInterval;
}
function withdrawAll() public payable onlyOwner {
require(payable(_msgSender()).send(address(this).balance));
}
function _isVowel(bytes1 char) internal view virtual returns (bool) {
return (uint8(char) == 97 || uint8(char) == 101 || uint8(char) == 105 || uint8(char) == 111 || uint8(char) == 117 || uint8(char) == 121 || uint8(char) == 65 || uint8(char) == 69 || uint8(char) == 73 || uint8(char) == 79 || uint8(char) == 85 || uint8(char) == 89);
}
function lower(bytes1 char) internal view virtual returns (bytes1){
if(uint8(char) >= 65 && uint8(char) <= 90) {
return bytes1(uint8(char) + 32);
} else {
return char;
}
}
function _rhymeCheckAcrossTokens(uint256 tokenId, bytes memory user_bars, uint256 start, uint256 end) internal view virtual returns (bool) {
string memory prevBarsString = tokenIdToBars[tokenId];
bytes memory prev_bars = bytes(prevBarsString);
uint256 index = prev_bars.length-1;
while(index >= 0){
if(prev_bars[index] == '\n'){
break;
}
index -= 1;
}
return strictRhymes(prev_bars, index+1, prev_bars.length-1, user_bars, start, end);
}
function strictRhymes(bytes memory s1, uint256 s1Start, uint256 s1End, bytes memory s2, uint256 s2Start, uint256 s2End) internal view returns (bool) {
uint256 s1Ind = s1End;
uint256 s2Ind = s2End;
bool vowelSeen = false;
uint256 consecutive = 0;
uint256 checked = 0;
uint256 vowelCt = 10000;
bool consec = true;
while(s1Ind >= s1Start && s2Ind >= s2Start){
bytes1 s1Char = s1[s1Ind];
bytes1 s2Char = s2[s2Ind];
if(uint8(s1Char) == 32 || uint8(s2Char) == 32){
break;
}
if(!vowelSeen || vowelSeen && checked < 2) {
if(lower(s1Char) == lower(s2Char) && consec){
consecutive += 1;
} else {
consec = false;
}
}
vowelSeen = vowelSeen || _isVowel(s1Char) || _isVowel(s2Char);
if(vowelSeen && vowelCt == 10000){
vowelCt = checked;
}
checked += 1;
if(s1Ind == s1Start || s2Ind == s2Start){
break;
}
s1Ind -=1;
s2Ind -=1;
}
if(!vowelSeen || vowelCt == 0){
return consecutive >= 2 || consecutive >= checked;
} else {
return consecutive > vowelCt || consecutive >= checked;
}
}
/*************/
/* TOKEN URI */
/*************/
function tokenURI(uint256 tokenId) public override view returns(string memory) {
string memory lyric = tokenIdToBars[tokenId];
string[barsPerBlock] memory bars = splitOnChar(lyric, '\n');
address writer = tokenIdToWriter[tokenId];
string memory writerAscii = toAsciiString(writer);
uint256 colorScheme = trackColor(tokenId);
bytes memory tokenName;
bytes memory jsonEscapedBars;
for(uint256 i = 0; i < barsPerBlock; i++){
tokenName = abi.encodePacked(tokenName, substring(bytes(bars[i]), 0, firstCharIndex(bars[i], ' ')), ' ');
jsonEscapedBars = abi.encodePacked(jsonEscapedBars, bars[i], i != barsPerBlock - 1 ? '\\n' : '');
}
bytes memory jsonSvg = abi.encodePacked(
'{"name":"',
'#',
Strings.toString(tokenId),
' - ',
string(tokenName),
'", "description":"Cypher on-chain is a smart contract that conducts a rap cypher on Ethereum. Cypher EP is its first collectively written album with 10 tracks. Each track contains 20 blocks, comprised of 4 bars each. A block is an NFT.", ',
'"bars": "', jsonEscapedBars, '", '
);
jsonSvg = abi.encodePacked(jsonSvg, '"attributes": [{',
'"trait_type": "Track", "value":"',
Strings.toString(trackNumber(tokenId)),
'"}, {',
'"trait_type": "Block", "value":"',
Strings.toString(trackBlockNumber(tokenId)),
'"}',
',{',
'"trait_type": "Writer", "value":"0x',
writerAscii,
'"}',
']',
', "image": "'
'data:image/svg+xml;base64,',
Base64.encode(svgImage(tokenId, bars, colorScheme, writer, bytes(writerAscii))),
'"}'
);
return string(
abi.encodePacked(
'data:application/json;base64,',
Base64.encode(
jsonSvg
)
)
);
}
function svgImage(uint256 tokenId, string[barsPerBlock] memory bars, uint256 colorScheme, address writer, bytes memory writerAscii) internal view returns (bytes memory){
bytes memory writerAddr = abi.encodePacked(tokenIdToWriter[tokenId]);
return abi.encodePacked(
'<svg version="1.1" shape-rendering="optimizeSpeed" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"',
' x="0px" y="0px" width="300" height="300" viewBox="0 0 10 10" xml:space="preserve">',
styles(),
svgGrid(colorScheme, writer),
svgText(colorScheme, writer, bars),
abi.encodePacked('<text x="0" y="1" fill="',
string(abi.encodePacked('hsl(', Strings.toString(colorScheme),',95%,40%)')),
'">Track: ', Strings.toString(trackNumber(tokenId)),
' - Block: ', Strings.toString(trackBlockNumber(tokenId)), '</text>'),
'</svg>'
);
}
function styles() internal view returns (string memory) {
bytes memory styles = abi.encodePacked('<style type="text/css">',
'rect{width: 1px; height: 1px;}text{font-size: 0.42px; alignment-baseline:text-after-edge}',
'.c1{fill:#000000;}.writerText{font-size: 0.25px;}</style>');
return string(styles);
}
function trackColor(uint256 tokenId) public view returns (uint256){
uint16[10] memory colorSchemes = [180, 160, 36, 72, 96, 0, 206, 270, 288, 312];
uint256 h = trackNumber(tokenId) - 1;
return colorSchemes[h];
}
function trackNumber(uint256 tokenId) public view returns (uint256){
return (tokenId-1)/(trackLength) + 1;
}
function trackBlockNumber(uint256 tokenId) public view returns (uint256){
return ((tokenId-1) % trackLength) + 1;
}
function svgText(uint256 colorScheme, address writer, string[barsPerBlock] memory bars) internal view returns (string memory) {
bytes memory lyricSvgs;
for (uint256 i = 0; i < barsPerBlock; i++){
lyricSvgs = abi.encodePacked(lyricSvgs, '<text x="0" y="', Strings.toString(i+1+1), '" fill="white">', bytes(bars[i]), '</text>');
}
lyricSvgs = abi.encodePacked(lyricSvgs,
'<text x="0" y="6" fill="',
string(abi.encodePacked('hsl(', Strings.toString(colorScheme),',95%,40%)')),
'" class="writerText">0x', toAsciiString(writer), '</text>');
return string(lyricSvgs);
}
function svgGrid(uint256 colorScheme, address writer) internal view returns (string memory) {
bytes memory rectString;
rectString = abi.encodePacked(
svgLyricCanvasRow(0),
svgLyricCanvasRow(1),
svgLyricCanvasRow(2),
svgLyricCanvasRow(3),
svgLyricCanvasRow(4),
svgLyricCanvasRow(5)
);
for(uint256 i=0; i < barsPerBlock; i++){
rectString = abi.encodePacked(rectString, svgSignatureRow(abi.encodePacked(writer), 6+i, colorScheme));
}
return string(rectString);
}
function svgSignatureRow(bytes memory writer, uint256 rowIdx, uint256 colorScheme) internal view returns (string memory) {
bytes memory rectString;
uint256 addrInd = 0;
uint256 stepSize = 2;
// parts of color band that have less variance nearby
if(colorScheme == 206 || colorScheme == 312 || colorScheme == 270 || colorScheme == 0 || colorScheme == 144){
stepSize = 3;
} else if (colorScheme == 72 || colorScheme == 96) {
stepSize = 5;
} else {
}
for(uint256 i=0; i<10; i++){
if (writer.length != 0){
uint256 addrOffset = rowIdx >= 6 ? (rowIdx-6)*(10/5) : 0;
uint256 walletInt;
if (i % 2 == 0){
walletInt = uint(uint8(writer[addrInd + addrOffset] >> 4));
} else {
walletInt = uint(uint8(writer[addrInd + addrOffset] & 0x0f));
addrInd += 1;
}
rectString = abi.encodePacked(rectString,
'<rect x="', Strings.toString(i), '" y="', Strings.toString(rowIdx),
'" fill="',string(abi.encodePacked('hsl(', Strings.toString(colorScheme + walletInt*stepSize),',95%,40%)')) ,'"></rect>');
}
}
return string(rectString);
}
function svgLyricCanvasRow(uint256 rowIdx) internal view returns (string memory) {
bytes memory rectString;
for(uint256 i=0; i<10; i++){
rectString = abi.encodePacked(rectString, '<rect x="', Strings.toString(i), '" y="', Strings.toString(rowIdx), '" class="c1 s"/>');
}
return string(rectString);
}
function firstCharIndex (string memory base, bytes1 char) internal view virtual returns (uint) {
bytes memory _bytes = bytes(base);
uint256 i = 0;
while (i < _bytes.length){
if (_bytes[i] == char) {
return i;
}
i += 1;
}
return 0;
}
function splitOnChar(string memory lyric, bytes1 char) internal view returns (string[barsPerBlock] memory bars) {
bytes memory b_lyrics = bytes(lyric);
uint256 splits = 0;
uint256 start_index = 0;
for(uint256 i = 0; i < b_lyrics.length; i++){
if (b_lyrics[i] == char) {
bars[splits] = string(substring(b_lyrics, start_index, i));
splits += 1;
start_index = i+1;
}
}
bars[barsPerBlock-1] = string(substring(b_lyrics, start_index, b_lyrics.length));
return bars;
}
function substring(bytes memory in_string, uint256 start_index, uint256 end_index) internal view virtual returns (bytes memory) {
bytes memory new_str = new bytes(end_index-start_index);
for(uint256 i = 0; i < end_index-start_index; i++) {
new_str[i] = in_string[start_index+i];
}
return new_str;
}
function toAsciiString(address x) internal view returns (string memory) {
bytes memory s = new bytes(40);
for (uint256 i = 0; i < 20; i++) {
bytes1 b = bytes1(uint8(uint(uint160(x)) / (2**(8*(19 - i)))));
bytes1 hi = bytes1(uint8(b) / 16);
bytes1 lo = bytes1(uint8(b) - 16 * uint8(hi));
s[2*i] = addressChar(hi);
s[2*i+1] = addressChar(lo);
}
return string(s);
}
function addressChar(bytes1 b) internal view returns (bytes1 c) {
if (uint8(b) < 10) return bytes1(uint8(b) + 0x30);
else return bytes1(uint8(b) + 0x57);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "IERC721.sol";
import "IERC721Receiver.sol";
import "IERC721Metadata.sol";
import "Address.sol";
import "Context.sol";
import "Strings.sol";
import "ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
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 {}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "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;
/**
* @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;
/**
* @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;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
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;
import "Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
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);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: MIT
/// @title Base64
/// @author Brecht Devos - <[email protected]>
/// @notice Provides a function for encoding some bytes in base64
pragma solidity ^0.8.0;
library Base64 {
string internal constant TABLE = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
function encode(bytes memory data) internal pure returns (string memory) {
if (data.length == 0) return '';
// load the table into memory
string memory table = TABLE;
// multiply by 4/3 rounded up
uint256 encodedLen = 4 * ((data.length + 2) / 3);
// add some extra buffer at the end required for the writing
string memory result = new string(encodedLen + 32);
assembly {
// set the actual output length
mstore(result, encodedLen)
// prepare the lookup table
let tablePtr := add(table, 1)
// input ptr
let dataPtr := data
let endPtr := add(dataPtr, mload(data))
// result ptr, jump over length
let resultPtr := add(result, 32)
// run over the input, 3 bytes at a time
for {} lt(dataPtr, endPtr) {}
{
dataPtr := add(dataPtr, 3)
// read 3 bytes
let input := mload(dataPtr)
// write 4 characters
mstore(resultPtr, shl(248, mload(add(tablePtr, and(shr(18, input), 0x3F)))))
resultPtr := add(resultPtr, 1)
mstore(resultPtr, shl(248, mload(add(tablePtr, and(shr(12, input), 0x3F)))))
resultPtr := add(resultPtr, 1)
mstore(resultPtr, shl(248, mload(add(tablePtr, and(shr( 6, input), 0x3F)))))
resultPtr := add(resultPtr, 1)
mstore(resultPtr, shl(248, mload(add(tablePtr, and( input, 0x3F)))))
resultPtr := add(resultPtr, 1)
}
// padding with '='
switch mod(mload(data), 3)
case 1 { mstore(sub(resultPtr, 2), shl(240, 0x3d3d)) }
case 2 { mstore(sub(resultPtr, 1), shl(248, 0x3d)) }
}
return result;
}
} | parts of color band that have less variance nearby | function svgSignatureRow(bytes memory writer, uint256 rowIdx, uint256 colorScheme) internal view returns (string memory) {
bytes memory rectString;
uint256 addrInd = 0;
uint256 stepSize = 2;
if(colorScheme == 206 || colorScheme == 312 || colorScheme == 270 || colorScheme == 0 || colorScheme == 144){
stepSize = 3;
stepSize = 5;
}
for(uint256 i=0; i<10; i++){
if (writer.length != 0){
uint256 addrOffset = rowIdx >= 6 ? (rowIdx-6)*(10/5) : 0;
uint256 walletInt;
if (i % 2 == 0){
walletInt = uint(uint8(writer[addrInd + addrOffset] >> 4));
walletInt = uint(uint8(writer[addrInd + addrOffset] & 0x0f));
addrInd += 1;
}
rectString = abi.encodePacked(rectString,
'<rect x="', Strings.toString(i), '" y="', Strings.toString(rowIdx),
'" fill="',string(abi.encodePacked('hsl(', Strings.toString(colorScheme + walletInt*stepSize),',95%,40%)')) ,'"></rect>');
}
}
return string(rectString);
}
| 6,069,370 | [
1,
6019,
434,
2036,
8937,
716,
1240,
5242,
12380,
13378,
1637,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
9804,
5374,
1999,
12,
3890,
3778,
2633,
16,
2254,
5034,
1027,
4223,
16,
2254,
5034,
2036,
9321,
13,
2713,
1476,
1135,
261,
1080,
3778,
13,
288,
203,
3639,
1731,
3778,
4917,
780,
31,
203,
3639,
2254,
5034,
3091,
3866,
273,
374,
31,
203,
3639,
2254,
5034,
2235,
1225,
273,
576,
31,
203,
203,
3639,
309,
12,
3266,
9321,
422,
4200,
26,
747,
2036,
9321,
422,
890,
2138,
747,
2036,
9321,
422,
29966,
747,
2036,
9321,
422,
374,
747,
2036,
9321,
422,
30457,
15329,
203,
5411,
2235,
1225,
273,
890,
31,
203,
5411,
2235,
1225,
273,
1381,
31,
203,
203,
3639,
289,
203,
203,
3639,
364,
12,
11890,
5034,
277,
33,
20,
31,
277,
32,
2163,
31,
277,
27245,
95,
203,
5411,
309,
261,
6299,
18,
2469,
480,
374,
15329,
203,
7734,
2254,
5034,
3091,
2335,
273,
1027,
4223,
1545,
1666,
692,
261,
492,
4223,
17,
26,
17653,
12,
2163,
19,
25,
13,
294,
374,
31,
203,
7734,
2254,
5034,
9230,
1702,
31,
203,
203,
7734,
309,
261,
77,
738,
576,
422,
374,
15329,
203,
10792,
9230,
1702,
273,
2254,
12,
11890,
28,
12,
6299,
63,
4793,
3866,
397,
3091,
2335,
65,
1671,
1059,
10019,
203,
10792,
9230,
1702,
273,
2254,
12,
11890,
28,
12,
6299,
63,
4793,
3866,
397,
3091,
2335,
65,
473,
374,
92,
20,
74,
10019,
203,
10792,
3091,
3866,
1011,
404,
31,
203,
7734,
289,
203,
7734,
4917,
780,
273,
24126,
18,
3015,
4420,
329,
12,
2607,
780,
16,
7010,
10792,
2368,
2607,
619,
1546,
2187,
8139,
18,
10492,
2
] |
./partial_match/1/0x4f252cFd54aa500BAe69EA405fd30B8D6F31fA6d/sources/ImmortalsStaking.sol | * @dev Destroys `tokenId`. The approval is cleared when the token is burned. This is an internal function that does not check if the sender is authorized to operate on the token. Requirements: - `tokenId` must exist. Emits a {Transfer} event./ Update ownership in case tokenId was transferred by `_beforeTokenTransfer` hook Clear approvals Cannot overflow, as that would require more tokens to be burned/transferred out than the owner initially received through minting and transferring in. | function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId, 1);
owner = ERC721.ownerOf(tokenId);
delete _tokenApprovals[tokenId];
unchecked {
_balances[owner] -= 1;
}
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
_afterTokenTransfer(owner, address(0), tokenId, 1);
}
| 2,586,642 | [
1,
9378,
28599,
1375,
2316,
548,
8338,
1021,
23556,
353,
16054,
1347,
326,
1147,
353,
18305,
329,
18,
1220,
353,
392,
2713,
445,
716,
1552,
486,
866,
309,
326,
5793,
353,
10799,
358,
20829,
603,
326,
1147,
18,
29076,
30,
300,
1375,
2316,
548,
68,
1297,
1005,
18,
7377,
1282,
279,
288,
5912,
97,
871,
18,
19,
2315,
23178,
316,
648,
1147,
548,
1703,
906,
4193,
635,
1375,
67,
5771,
1345,
5912,
68,
3953,
10121,
6617,
4524,
14143,
9391,
16,
487,
716,
4102,
2583,
1898,
2430,
358,
506,
18305,
329,
19,
2338,
4193,
596,
2353,
326,
3410,
22458,
5079,
3059,
312,
474,
310,
471,
906,
74,
20245,
316,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
565,
445,
389,
70,
321,
12,
11890,
5034,
1147,
548,
13,
2713,
5024,
288,
203,
3639,
1758,
3410,
273,
4232,
39,
27,
5340,
18,
8443,
951,
12,
2316,
548,
1769,
203,
203,
3639,
389,
5771,
1345,
5912,
12,
8443,
16,
1758,
12,
20,
3631,
1147,
548,
16,
404,
1769,
203,
203,
3639,
3410,
273,
4232,
39,
27,
5340,
18,
8443,
951,
12,
2316,
548,
1769,
203,
203,
3639,
1430,
389,
2316,
12053,
4524,
63,
2316,
548,
15533,
203,
203,
3639,
22893,
288,
203,
5411,
389,
70,
26488,
63,
8443,
65,
3947,
404,
31,
203,
3639,
289,
203,
3639,
1430,
389,
995,
414,
63,
2316,
548,
15533,
203,
540,
203,
3639,
3626,
12279,
12,
8443,
16,
1758,
12,
20,
3631,
1147,
548,
1769,
203,
203,
3639,
389,
5205,
1345,
5912,
12,
8443,
16,
1758,
12,
20,
3631,
1147,
548,
16,
404,
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
] |
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.0;
/**
* @dev ERC20 Contract Implementation
*/
contract ERC20 {
mapping(address => uint256) internal _balances;
mapping(address => mapping(address => uint256)) internal _allowances;
uint256 internal _totalSupply;
string public constant name = 'Doom Cult Society DAO';
string public constant symbol = 'CUL';
uint256 public constant decimals = 18;
uint256 public constant CURRENCY_MULTIPLIER = 1000000000000000000;
uint256 internal constant ERROR_SIG = 0x08c379a000000000000000000000000000000000000000000000000000000000;
bytes32 internal constant TRANSFER_SIG = 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef;
bytes32 internal constant APPROVAL_SIG = 0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925;
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
constructor() {}
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) public view returns (uint256) {
return _balances[account];
}
function transfer(address recipient, uint256 amount) public returns (bool) {
_transfer(msg.sender, recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns (uint256 result) {
assembly {
mstore(0x00, owner)
mstore(0x20, _allowances.slot)
mstore(0x20, keccak256(0x00, 0x40))
mstore(0x00, spender)
result := sload(keccak256(0x00, 0x40))
}
}
function approve(address spender, uint256 amount) public returns (bool) {
_approve(msg.sender, spender, amount);
return true;
}
function transferFrom(
address sender,
address recipient,
uint256 amount
) public returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance;
assembly {
// currentAllowance = _allowances[sender][msg.sender]
mstore(0x00, sender)
mstore(0x20, _allowances.slot)
mstore(0x20, keccak256(0x00, 0x40))
mstore(0x00, caller())
let currentAllowanceSlot := keccak256(0x00, 0x40)
currentAllowance := sload(currentAllowanceSlot)
if gt(amount, currentAllowance) {
mstore(0x00, ERROR_SIG)
mstore(0x04, 0x20)
mstore(0x24, 23)
mstore(0x44, 'ERC20: amount>allowance')
revert(0x00, 0x64)
}
}
unchecked {
_approve(sender, msg.sender, currentAllowance - amount);
}
return true;
}
function _transfer(
address sender,
address recipient,
uint256 amount
) internal {
assembly {
mstore(0x00, sender)
mstore(0x20, _balances.slot)
let balancesSlot := keccak256(0x00, 0x40)
let senderBalance := sload(balancesSlot)
if or(or(iszero(sender), iszero(recipient)), gt(amount, senderBalance)) {
mstore(0x00, ERROR_SIG)
mstore(0x04, 0x20)
mstore(0x24, 32)
mstore(0x44, 'ERC20: amount>balance or from==0')
revert(0x00, 0x64)
}
sstore(balancesSlot, sub(senderBalance, amount))
mstore(0x00, recipient)
balancesSlot := keccak256(0x00, 0x40)
// skip overflow check as we only have 30,000 tokens
sstore(balancesSlot, add(sload(balancesSlot), amount))
mstore(0x00, amount)
log3(0x00, 0x20, TRANSFER_SIG, sender, recipient)
}
}
function _approve(
address owner,
address spender,
uint256 amount
) internal {
assembly {
if or(iszero(owner), iszero(spender)) {
mstore(0x00, ERROR_SIG)
mstore(0x04, 0x20)
mstore(0x24, 29)
mstore(0x44, 'ERC20: approve from 0 address')
revert(0x00, 0x64)
}
// _allowances[owner][spender] = amount
mstore(0x00, owner)
mstore(0x20, _allowances.slot)
mstore(0x20, keccak256(0x00, 0x40))
mstore(0x00, spender)
sstore(keccak256(0x00, 0x40), amount)
// emit Approval(owner, spender, amount)
mstore(0x00, amount)
log3(0x00, 0x20, APPROVAL_SIG, owner, spender)
}
}
}
/**
* @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);
}
/**
* @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;
}
/**
* @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);
}
/**
* @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);
}
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension but not the Enumerable extension
*/
contract ERC721 is IERC165, IERC721, IERC721Metadata {
// Token name
string public constant override name = 'Doom Cult Society';
// Token symbol
string public constant override symbol = 'DCS';
uint256 internal constant ERROR_SIG = 0x08c379a000000000000000000000000000000000000000000000000000000000;
// event signatures
uint256 private constant APPROVAL_FOR_ALL_SIG = 0x17307eab39ab6107e8899845ad3d59bd9653f200f220920489ca2b5937696c31;
bytes32 internal constant TRANSFER_SIG = 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef;
bytes32 internal constant APPROVAL_SIG = 0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925;
// Mapping from token ID to owner address
mapping(uint256 => address) internal _owners;
// Mapping owner address to token count
mapping(address => uint256) internal _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() {}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
interfaceId == type(IERC165).interfaceId;
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256 res) {
assembly {
if iszero(owner) {
mstore(0x00, ERROR_SIG)
mstore(0x04, 0x20)
mstore(0x24, 42)
mstore(0x44, 'ERC721: balance query for the ze')
mstore(0x64, 'ro address')
revert(0x00, 0x84)
}
mstore(0x00, owner)
mstore(0x20, _balances.slot)
res := sload(keccak256(0x00, 0x40))
}
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address owner) {
assembly {
mstore(0x00, tokenId)
mstore(0x20, _owners.slot)
// no need to mask address if we ensure everything written into _owners is an address
owner := sload(keccak256(0x00, 0x40))
if iszero(owner) {
mstore(0x00, ERROR_SIG)
mstore(0x04, 0x20)
mstore(0x24, 41)
mstore(0x44, 'ERC721: owner query for nonexist')
mstore(0x64, 'ent token')
revert(0x00, 0x84)
}
}
return owner;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256) public view virtual override returns (string memory) {
return '';
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ownerOf(tokenId);
bool approvedForAll = isApprovedForAll(owner, msg.sender);
/**
* Failure cases
* 1. to == owner (if ya wanna approve yourself go stare in a mirror!)
* 2. !(msg.sender == owner OR approvedForAll == 1)
*/
assembly {
if or(eq(to, owner), iszero(or(eq(caller(), owner), approvedForAll))) {
mstore(0x00, ERROR_SIG)
mstore(0x04, 0x20)
mstore(0x24, 19)
mstore(0x44, 'ERC721: bad approve')
revert(0x00, 0x64)
}
mstore(0x00, tokenId)
mstore(0x20, _tokenApprovals.slot)
sstore(keccak256(0x00, 0x40), to)
log3(0x00, 0x20, APPROVAL_SIG, owner, to)
}
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address res) {
assembly {
mstore(0x00, tokenId)
mstore(0x20, _owners.slot)
if iszero(sload(keccak256(0x00, 0x40))) {
mstore(0x00, ERROR_SIG)
mstore(0x04, 0x20)
mstore(0x24, 19)
mstore(0x44, 'ERC721: bad approve')
revert(0x00, 0x64)
}
mstore(0x00, tokenId)
mstore(0x20, _tokenApprovals.slot)
res := sload(keccak256(0x00, 0x40))
}
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
assembly {
if eq(operator, caller()) {
mstore(0x00, ERROR_SIG)
mstore(0x04, 0x20)
mstore(0x24, 25)
mstore(0x44, 'ERC721: approve to caller')
revert(0x00, 0x64)
}
// _operatorApprovals[_msgSender()][operator] = approved
mstore(0x00, caller())
mstore(0x20, _operatorApprovals.slot)
mstore(0x20, keccak256(0x00, 0x40))
mstore(0x00, operator)
sstore(keccak256(0x00, 0x40), approved)
log4(0, 0, APPROVAL_FOR_ALL_SIG, caller(), operator, approved)
}
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool res) {
assembly {
mstore(0x00, owner)
mstore(0x20, _operatorApprovals.slot)
mstore(0x20, keccak256(0x00, 0x40))
mstore(0x00, operator)
res := sload(keccak256(0x00, 0x40))
}
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
_isApprovedOrOwner(msg.sender, tokenId);
_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 {
_isApprovedOrOwner(msg.sender, tokenId);
_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);
bool isContract;
assembly {
isContract := gt(extcodesize(to), 0)
}
if (isContract) {
_checkOnERC721ReceivedContract(from, to, tokenId, _data);
}
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual {
address owner;
bool approvedForAll = isApprovedForAll(owner, spender);
assembly {
mstore(0x00, tokenId)
mstore(0x20, _owners.slot)
owner := sload(keccak256(0x00, 0x40))
mstore(0x20, _tokenApprovals.slot)
let approved := sload(keccak256(0x00, 0x40))
/**
* Success Conditions
* 1. spender = owner
* 2. spender = approved
* 3. approvedForAll = true
* Also owner must NOT be 0
*/
if or(iszero(or(or(eq(spender, owner), eq(approved, spender)), approvedForAll)), iszero(owner)) {
mstore(0x00, ERROR_SIG)
mstore(0x04, 0x20)
mstore(0x24, 44)
mstore(0x44, 'ERC721: operator query for nonex')
mstore(0x64, 'istent token')
revert(0x00, 0x84)
}
}
}
/**
* @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 {
// address owner = ownerOf(tokenId);
assembly {
mstore(0x00, tokenId)
mstore(0x20, _owners.slot)
let owner := sload(keccak256(0x00, 0x40))
// Clear approvals from the previous owner
mstore(0x00, tokenId)
mstore(0x20, _tokenApprovals.slot)
sstore(keccak256(0x00, 0x40), 0)
log3(0x00, 0x20, APPROVAL_SIG, owner, 0)
log3(0x00, 0x20, TRANSFER_SIG, from, to)
// _owners[tokenId] = to
mstore(0x20, _owners.slot)
sstore(keccak256(0x00, 0x40), to)
// _balances[from] -= 1
mstore(0x00, from)
mstore(0x20, _balances.slot)
let slot := keccak256(0x00, 0x40)
let fromBalance := sload(slot)
sstore(slot, sub(fromBalance, 0x01))
// _balances[to] += 1
mstore(0x00, to)
slot := keccak256(0x00, 0x40)
sstore(slot, add(sload(slot), 1))
/**
* Failure cases...
* 1. owner != from
* 2. to == 0
* 3. owner == 0
* 4. balances[from] == 0
*/
if or(or(iszero(owner), iszero(fromBalance)), or(iszero(to), sub(owner, from))) {
mstore(0x00, ERROR_SIG)
mstore(0x04, 0x20)
mstore(0x24, 20)
mstore(0x44, 'ERC721: bad transfer')
revert(0x00, 0x64)
}
}
}
/**
* @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
*/
function _checkOnERC721ReceivedContract(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal {
try IERC721Receiver(to).onERC721Received(msg.sender, from, tokenId, _data) returns (bytes4 retval) {
require(
retval == IERC721Receiver(to).onERC721Received.selector,
'ERC721: transfer to non ERC721Receiver implementer'
);
} catch (bytes memory reason) {
if (reason.length == 0) {
revert('ERC721: transfer to non ERC721Receiver implementer');
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
}
}
/**
* @dev DoomCultSocietyDAO
* Decentralized Autonomous Doom! Doooooooooooooooooooooooom!
*
* The DAO controls cultist tokens: CUL
* Cultist tokens are sacrificed in order to mint DoomCultSociety NFTs
*/
contract DoomCultSocietyDAO is ERC20 {
uint256 internal constant WEEKS_UNTIL_OBLIVION = 52;
uint256 internal constant SECONDS_PER_WEEK = 604800;
uint256 public sleepTimer; // can wake up once block.timestamp > sleepTimer
uint256 public doomCounter; // number of weeks until contract is destroyed
uint256 public timestampUntilNextEpoch; // countdown timer can decrease once block.timestamp > timestampUntilNextEpoch
// potential max cultists (incl. currency multiplier. This is 30,000 CUL)
uint256 internal constant MAX_CULTISTS = 30000000000000000000000;
// how many do we actually start with? (phase 2 starts after 4 weeks regardless)
uint256 public numStartingCultists;
// If currentEpochTotalSacrificed <= lastEpocTotalSacrificed when epoch ends...kaboom!
uint256 public currentEpochTotalSacrificed;
uint256 public lastEpochTotalSacrificed;
// How many times this week has the DAO been placated
uint256 public placationCount;
// How much does the cost increase by each time we placate?
uint256 private constant PLACATE_INTERVAL = 100000000000000000; // 0.1 eth in wei
// What is the current cost to placate?
uint256 public placateThreshold = PLACATE_INTERVAL;
uint256 private constant IT_HAS_AWOKEN_SIG = 0x21807e0b842b099372e0a04f56a3c00df1f88de6af9d3e3ebb06d4d6fac76a8d;
event ItHasAwoken(uint256 startNumCultists);
uint256 private constant COUNTDOWN_SIG = 0x11d2d22584d0bb23681c07ce6959f34dfc15469ad3546712ab96e3a945c6f603;
event Countdown(uint256 weeksRemaining);
uint256 private constant OBLITERATE_SIG = 0x03d6576f6c77df8600e2667de4d5c1fbc7cb69b42d5eaa80345d8174d80af46b;
event Obliterate(uint256 endNumCultists);
bool public isAwake;
DoomCultSociety public doomCultSociety;
modifier onlyAwake() {
assembly {
if iszero(and(sload(isAwake.slot), 1)) {
mstore(0x00, ERROR_SIG)
mstore(0x04, 0x20)
mstore(0x24, 14)
mstore(0x44, 'It Is Sleeping')
revert(0x00, 0x64)
}
}
_;
}
modifier onlyAsleep() {
assembly {
if and(sload(isAwake.slot), 1) {
mstore(0x00, ERROR_SIG)
mstore(0x04, 0x20)
mstore(0x24, 12)
mstore(0x44, 'It Has Woken')
revert(0x00, 0x64)
}
}
_;
}
constructor() ERC20() {
doomCultSociety = new DoomCultSociety();
assembly {
sstore(sleepTimer.slot, add(timestamp(), mul(4, SECONDS_PER_WEEK)))
}
// Mmmmmmmmmmm slightly corrupt cheeky premine aka 6.66% founder reward
_balances[address(0x24065d97424687EB9c83c87729fc1b916266F637)] = 898 * CURRENCY_MULTIPLIER; // some extra for givaways
_balances[address(0x1E11a16335E410EB5f4e7A781C6f069609E5946A)] = 100 * CURRENCY_MULTIPLIER; // om
_balances[address(0x9436630F6475D04E1d396a255f1321e00171aBFE)] = 100 * CURRENCY_MULTIPLIER; // nom
_balances[address(0x001aBc8196c60C2De9f9a2EdBdf8Db00C1Fa35ef)] = 100 * CURRENCY_MULTIPLIER; // nom
_balances[address(0x53DF4Fc15BdAfd4c01ca289797A85D00cC791810)] = 100 * CURRENCY_MULTIPLIER; // nom
_balances[address(0x10715Db3d70bBB01f39B6A6CA817cbcf2F6e9B5f)] = 100 * CURRENCY_MULTIPLIER; // nom
_balances[address(0x4a4866086D4b74521624Dbaec9478C9973Ff2C8e)] = 100 * CURRENCY_MULTIPLIER; // nom
_balances[address(0xB658bF75C8968e8C9a577D5c8814803A1dDD0939)] = 100 * CURRENCY_MULTIPLIER; // nom
_balances[address(0x99A94D55417aaCC993889d5C574B07F01Ad35920)] = 100 * CURRENCY_MULTIPLIER; // nom
_balances[address(0xE71f18D8F2e874AD3284C1A432A38fD158e35D70)] = 100 * CURRENCY_MULTIPLIER; // nom
_balances[address(0x31102499a64BEc6dC5Cc22FFDCBDc0551b2687Ab)] = 100 * CURRENCY_MULTIPLIER; // nom
_balances[address(0x934a19c7f2cD41D330d00C02884504fb59a33F36)] = 100 * CURRENCY_MULTIPLIER; // *burp*
_totalSupply = 1998 * CURRENCY_MULTIPLIER;
emit Transfer(address(0), address(0x24065d97424687EB9c83c87729fc1b916266F637), 898 * CURRENCY_MULTIPLIER);
emit Transfer(address(0), address(0x1E11a16335E410EB5f4e7A781C6f069609E5946A), 100 * CURRENCY_MULTIPLIER);
emit Transfer(address(0), address(0x9436630F6475D04E1d396a255f1321e00171aBFE), 100 * CURRENCY_MULTIPLIER);
emit Transfer(address(0), address(0x001aBc8196c60C2De9f9a2EdBdf8Db00C1Fa35ef), 100 * CURRENCY_MULTIPLIER);
emit Transfer(address(0), address(0x53DF4Fc15BdAfd4c01ca289797A85D00cC791810), 100 * CURRENCY_MULTIPLIER);
emit Transfer(address(0), address(0x10715Db3d70bBB01f39B6A6CA817cbcf2F6e9B5f), 100 * CURRENCY_MULTIPLIER);
emit Transfer(address(0), address(0x4a4866086D4b74521624Dbaec9478C9973Ff2C8e), 100 * CURRENCY_MULTIPLIER);
emit Transfer(address(0), address(0xB658bF75C8968e8C9a577D5c8814803A1dDD0939), 100 * CURRENCY_MULTIPLIER);
emit Transfer(address(0), address(0x99A94D55417aaCC993889d5C574B07F01Ad35920), 100 * CURRENCY_MULTIPLIER);
emit Transfer(address(0), address(0xE71f18D8F2e874AD3284C1A432A38fD158e35D70), 100 * CURRENCY_MULTIPLIER);
emit Transfer(address(0), address(0x31102499a64BEc6dC5Cc22FFDCBDc0551b2687Ab), 100 * CURRENCY_MULTIPLIER);
emit Transfer(address(0), address(0x934a19c7f2cD41D330d00C02884504fb59a33F36), 100 * CURRENCY_MULTIPLIER);
}
/**
* @dev Acquire cultists!
*/
function attractCultists() public onlyAsleep {
assembly {
if lt(MAX_CULTISTS, add(1, sload(_totalSupply.slot))) {
mstore(0x00, ERROR_SIG)
mstore(0x04, 0x20)
mstore(0x24, 22)
mstore(0x44, 'No remaining cultists!')
revert(0x00, 0x64)
}
let numTokens := mul(3, CURRENCY_MULTIPLIER)
mstore(0x00, caller())
mstore(0x20, _balances.slot)
let balanceSlot := keccak256(0x00, 0x40)
// _balances[msg.sender] += 3
sstore(balanceSlot, add(sload(balanceSlot), numTokens))
// _totalSupply += 3
sstore(_totalSupply.slot, add(sload(_totalSupply.slot), numTokens))
// emit Transfer(0, msg.sender, 3)
mstore(0x00, numTokens)
log3(0x00, 0x20, TRANSFER_SIG, 0, caller())
}
}
/**
* @dev Awaken the wrath of the Doom Cult Society DAO!
*/
function wakeUp() public onlyAsleep {
assembly {
if iszero(
or(gt(add(sload(_totalSupply.slot), 1), MAX_CULTISTS), gt(add(timestamp(), 1), sload(sleepTimer.slot)))
) {
mstore(0x00, ERROR_SIG)
mstore(0x04, 0x20)
mstore(0x24, 17)
mstore(0x44, 'Still Sleeping...')
revert(0x00, 0x64)
}
sstore(isAwake.slot, or(sload(isAwake.slot), 1))
sstore(timestampUntilNextEpoch.slot, add(timestamp(), SECONDS_PER_WEEK))
sstore(doomCounter.slot, 1)
let total := sload(_totalSupply.slot)
sstore(numStartingCultists.slot, div(total, CURRENCY_MULTIPLIER))
// emit ItHasAwoken(_totalSupply)
mstore(0x00, total)
log1(0x00, 0x20, IT_HAS_AWOKEN_SIG)
}
}
function obliterate() internal onlyAwake {
assembly {
if iszero(eq(sload(doomCounter.slot), add(WEEKS_UNTIL_OBLIVION, 1))) {
mstore(0x00, ERROR_SIG)
mstore(0x04, 0x20)
mstore(0x24, 22)
mstore(0x44, 'Too Soon To Obliterate')
revert(0x00, 0x64)
}
// emit Obliterate(_totalSupply)
mstore(0x00, sload(_totalSupply.slot))
log1(0x00, 0x20, OBLITERATE_SIG)
selfdestruct(0x00) // so long and thanks for all the fish!
}
}
/**
* @dev This function will only generate ONE NFT regardless of how many you sacrifice!!!!!
* If you want lots of NFTs call `sacrifice()` multiple times
* This function is for those who just want to run those numbers up for maximum chaos
* @param num number of cultists to sacrifice!
*/
function sacrificeManyButOnlyMintOneNFT(
uint256 num,
string memory /*message*/
) public onlyAwake {
uint256 totalRemainingCultists;
uint256 totalSacrificedCultists;
uint256 requiredTokens;
assembly {
requiredTokens := mul(CURRENCY_MULTIPLIER, num)
mstore(0x00, caller())
mstore(0x20, _balances.slot)
let slot := keccak256(0x00, 0x40)
let userBal := sload(slot)
if or(lt(userBal, requiredTokens), iszero(num)) {
mstore(0x00, ERROR_SIG)
mstore(0x04, 0x20)
mstore(0x24, 21)
mstore(0x44, 'Insufficient Cultists')
revert(0x00, 0x64)
}
sstore(slot, sub(userBal, requiredTokens))
sstore(currentEpochTotalSacrificed.slot, add(sload(currentEpochTotalSacrificed.slot), num))
let remainingTokens := sub(sload(_totalSupply.slot), requiredTokens)
totalRemainingCultists := div(remainingTokens, CURRENCY_MULTIPLIER)
sstore(_totalSupply.slot, remainingTokens)
totalSacrificedCultists := sub(sload(numStartingCultists.slot), totalRemainingCultists)
}
doomCultSociety.mint(doomCounter, totalRemainingCultists, totalSacrificedCultists, msg.sender);
assembly {
// emit Transfer(msg.sender, 0, num)
mstore(0x00, requiredTokens)
log3(0x00, 0x20, TRANSFER_SIG, caller(), 0)
}
}
/**
* @dev BLOOD FOR THE BLOOD GOD!
*
* @param message commemorate your sacrifice with a message to be recorded for all eternity
*/
function sacrifice(string memory message) public onlyAwake {
sacrificeManyButOnlyMintOneNFT(1, message);
}
/**
* @dev Stuff the DAO with gold to soothe its wrath! When money talks, there are few interruptions.
*
* HOW IT WORKS
* Users can push the required sacrifices down by 1 with some RAW ULTRA SOUND MONEY
* Placate starts at 0.1 Eth, cost increases by 0.1 Eth per placation.
* Yes, this gets stupid expensive very quickly!
*
* What do we do with these funds? Well, we could fairly redistribute them
* to the DAO's stakeholders...but who has time to bother with writing that code? Certainly not me!
* Instead send it to charity lol. Cults are supposed to take money from their supporters, not give it back!
*/
function placate() public payable onlyAwake {
require(msg.value >= placateThreshold, 'TOO POOR');
uint256 numPlacations = msg.value / placateThreshold;
placationCount += numPlacations;
placateThreshold += (numPlacations * PLACATE_INTERVAL);
// GiveDirectly Eth address
(bool sent, ) = payable(0x750EF1D7a0b4Ab1c97B7A623D7917CcEb5ea779C).call{value: msg.value}('');
require(sent, 'Failed to send Ether');
}
/**
* @dev KNEEL PEON! KNEEL BEFORE YOUR MASTER!
*/
function worship() public payable onlyAwake {
assembly {
if gt(sload(timestampUntilNextEpoch.slot), add(timestamp(), 1)) {
mstore(0x00, ERROR_SIG)
mstore(0x04, 0x20)
mstore(0x24, 8)
mstore(0x44, 'Too Soon')
revert(0x00, 0x64)
}
}
uint256 score = currentEpochTotalSacrificed + placationCount;
if (lastEpochTotalSacrificed >= score) {
assembly {
// emit Obliterate(_totalSupply)
mstore(0x00, sload(_totalSupply.slot))
log1(0x00, 0x20, OBLITERATE_SIG)
selfdestruct(0x00) // womp womp
}
}
assembly {
sstore(lastEpochTotalSacrificed.slot, sload(currentEpochTotalSacrificed.slot))
sstore(currentEpochTotalSacrificed.slot, 0)
sstore(timestampUntilNextEpoch.slot, add(timestamp(), SECONDS_PER_WEEK))
sstore(doomCounter.slot, add(sload(doomCounter.slot), 1))
sstore(placationCount.slot, 0)
}
if (doomCounter == (WEEKS_UNTIL_OBLIVION + 1)) {
obliterate();
}
// emit Countdown(doomCounter)
assembly {
mstore(0x00, sload(doomCounter.slot))
log1(0x00, 0x20, COUNTDOWN_SIG)
}
}
}
/**
* @dev DoomCultSociety
* It's more than a cult, it's a society!
* We have culture, economic theories and heaps of dead cultists
*/
contract DoomCultSociety is ERC721 {
address public doomCultSocietyDAO;
uint256 private constant SPLIT_PHRASE_ACROSS_LINES = 31;
constructor() ERC721() {
assembly {
sstore(doomCultSocietyDAO.slot, caller())
}
mint(0, 30000, 0, address(this));
}
// Not enumerable but hey we have enough info for this method...so why not
// (until the DAO blows up that is!)
function totalSupply() public view returns (uint256) {
DoomCultSocietyDAO dao = DoomCultSocietyDAO(doomCultSocietyDAO);
return dao.numStartingCultists() - (dao.totalSupply() / 1000000000000000000);
}
function mint(
uint256 countdown,
uint256 remainingCultists,
uint256 sacrificedCultists,
address owner
) public {
uint256 tokenId;
assembly {
if iszero(eq(caller(), sload(doomCultSocietyDAO.slot))) {
mstore(0x00, ERROR_SIG)
mstore(0x04, 0x20)
mstore(0x24, 10)
mstore(0x44, 'Bad Caller')
revert(0x00, 0x64)
}
tokenId := add(add(mul(remainingCultists, 100000000), mul(countdown, 1000000)), sacrificedCultists)
mstore(0x00, owner)
mstore(0x20, _balances.slot)
let slot := keccak256(0x00, 0x40)
// no need to check overflow, there are only 30,000 tokens!
sstore(slot, add(sload(slot), 1))
mstore(0x00, tokenId)
mstore(0x20, _owners.slot)
sstore(keccak256(0x00, 0x40), owner)
mstore(0x00, tokenId)
log3(0x00, 0x20, TRANSFER_SIG, 0, owner)
}
}
function getImgData(uint256 tokenId) internal pure returns (string memory res) {
// we make some assumptions when this function is called...
// 1: a max of 480 bytes of RAM have been used so far (i.e. `getImgData` is called at start of call context!)
// 2: setting the free memory pointer to 20000 won't cause any problems!
assembly {
{
let t0 := '<use transform="'
let t1 := ' transform="'
let t2 := 'rotate'
let t3 := ' fill="#f57914"'
let t4 := ' fill="#ed1c24"'
let t5 := ' fill="#8c1b85"'
let t6 := ' fill="#0994d3"'
let t7 := ' fill="#9addf0"'
let t8 := ' fill="#312b5d"'
let t9 := ' fill="#fff" '
let t10 := 'xlink:href="#'
let t11 := '<circle cx="'
let t12 := '<path id="'
let t13 := '"/><use '
let t14 := '"><use '
let t15 := '="http://www.w3.org/'
mstore(512, '<svg viewBox="0 0 700 800" xmlns')
mstore(544, t15)
mstore(564, '2000/svg" xmlns:xlink')
mstore(585, t15)
mstore(605, '1999/xlink"><style>.soft{font:70')
mstore(637, '0 20px sans-serif;fill:#ffffff88')
mstore(669, '}.heavy{font:700 29px sans-serif')
mstore(701, ';fill:#fff}.superheavy{font:700 ')
mstore(733, '40px sans-serif;fill:#fff}@-webk')
mstore(765, 'it-keyframes shine {from {-webki')
mstore(797, 't-filter: hue-')
mstore(811, t2)
mstore(817, '(0deg);}to { -webkit-filter: hue')
mstore(849, '-')
mstore(850, t2)
mstore(856, '(360deg); } }g { -webkit-animati')
mstore(888, 'on: shine 5s ease-in-out infinit')
mstore(920, 'e; }</style><path d="M0 0h700v08')
mstore(952, '00H0z"/><g')
mstore(962, t1)
mstore(974, 'matrix(.1 0 0 -.1 -350 660)"><de')
mstore(1006, 'fs><g id="g">')
mstore(1019, t11)
mstore(1031, '-20" cy="210" r="100')
mstore(1051, t13)
mstore(1059, t10)
mstore(1072, 'd')
mstore(1073, t13)
mstore(1081, 'transform="')
mstore(1092, t2)
mstore(1098, '(45 30.71 267.28)" ')
mstore(1117, t10)
mstore(1130, 'd')
mstore(1131, t13)
mstore(1139, 'transform="')
mstore(1150, t2)
mstore(1156, '(90 -20 240)" ')
mstore(1170, t10)
mstore(1183, 'd"/></g><g id="f')
mstore(1199, t14)
mstore(1206, t10)
mstore(1219, 'c')
mstore(1220, t13)
mstore(1228, 'transform="')
mstore(1239, t2)
mstore(1245, '(45 -19.645 218.14)" ')
mstore(1266, t10)
mstore(1279, 'c')
mstore(1280, t13)
mstore(1288, 'transform="')
mstore(1299, t2)
mstore(1305, '(90 -30 230)" ')
mstore(1319, t10)
mstore(1332, 'c')
mstore(1333, t13)
mstore(1341, 'transform="')
mstore(1352, t2)
mstore(1358, '(-48 -37.302 218.45)" ')
mstore(1380, t10)
mstore(1393, 'c"/></g><g id="1')
mstore(1409, t14)
mstore(1416, 'fill="#f57914" ')
mstore(1431, t10)
mstore(1444, 'l')
mstore(1445, t13)
mstore(1453, 'transform="matrix(.44463 1.2216 ')
mstore(1485, '-1.0337 .37622 7471.6 -2470.6)" ')
mstore(1517, 'x="-2000"')
mstore(1526, t8)
mstore(1541, ' ')
mstore(1542, t10)
mstore(1555, 'e"/></g><g id="2"')
mstore(1572, t1)
mstore(1584, 'translate(5150 4100)')
mstore(1604, t14)
mstore(1611, 'fill="#ed1c24" ')
mstore(1626, t10)
mstore(1639, 'g')
mstore(1640, t13)
mstore(1648, 'fill="#8c1b85" ')
mstore(1663, t10)
mstore(1676, 'f"/></g><g id="3')
mstore(1692, t14)
mstore(1699, 'transform="scale(.9 -.7)" x="960')
mstore(1731, '" y="-4400"')
mstore(1742, t6)
mstore(1757, ' ')
mstore(1758, t10)
mstore(1771, 'a')
mstore(1772, t13)
mstore(1780, 'transform="scale(.7 -.7) ')
mstore(1805, t2)
mstore(1811, '(40 14283 5801)"')
mstore(1827, t4)
mstore(1842, ' ')
mstore(1843, t10)
mstore(1856, 'a"/></g><g id="4"')
mstore(1873, t1)
mstore(1885, t2)
mstore(1891, '(125 3495.9 1947) scale(.6)')
mstore(1918, t14)
mstore(1925, 'fill="#f57914" ')
mstore(1940, t10)
mstore(1953, 'g')
mstore(1954, t13)
mstore(1962, 'fill="#8c1b85" ')
mstore(1977, t10)
mstore(1990, 'f"/></g><g id="5')
mstore(2006, t14)
mstore(2013, 'transform="matrix(-1.4095 .51303')
mstore(2045, ' .0684 -1.4083 12071 6071.6)" x=')
mstore(2077, '"-2100" y="1650"')
mstore(2093, t9)
mstore(2106, t10)
mstore(2119, 'e"/>')
mstore(2123, t11)
mstore(2135, '6470" cy="1780" r="130"')
mstore(2158, t6)
mstore(2173, '/>')
mstore(2175, t11)
mstore(2187, '5770" cy="1350" r="70"')
mstore(2209, t4)
mstore(2224, '/>')
mstore(2226, t11)
mstore(2238, '5820" cy="1150" r="70"')
mstore(2260, t4)
mstore(2275, '/>')
mstore(2277, t11)
mstore(2289, '5720" cy="1550" r="70"')
mstore(2311, t4)
mstore(2326, '/>')
mstore(2328, t11)
mstore(2340, '6190" cy="1700" r="80"')
mstore(2362, t4)
mstore(2377, '/></g><g id="6">')
mstore(2393, t11)
mstore(2405, '6000" cy="1650" r="80"')
mstore(2427, t6)
mstore(2442, '/>')
mstore(2444, t11)
mstore(2456, '6370" cy="200" r="80"')
mstore(2477, t3)
mstore(2492, '/><path d="M6300 1710c-7-13-6-26')
mstore(2524, '-4-41s9-26 17-37c6-11 22-17 41-2')
mstore(2556, '4 17-4 44 9 79 41 35 33 63 131 8')
mstore(2588, '5 299-92-124-153-194-183-207-4-2')
mstore(2620, '-9-4-13-6-10-4-17-13-22-24m-470-')
mstore(2652, '161c-26 2-50-6-72-26-19-17-33-39')
mstore(2684, '-39-65-4-13 20-164 72-452 50-286')
mstore(2716, ' 181-530 393-731-201 421-292 709')
mstore(2748, '-277 860 15 150 20 247 13 284-6 ')
mstore(2780, '37-17 68-28 90-15 24-37 39-61 41')
mstore(2812, '"')
mstore(2813, t4)
mstore(2828, '/></g><g id="7')
mstore(2842, t14)
mstore(2849, 'transform="scale(.9 1.6)" x="960')
mstore(2881, '" y="-840"')
mstore(2891, t6)
mstore(2906, ' ')
mstore(2907, t10)
mstore(2920, 'a')
mstore(2921, t13)
mstore(2929, 'transform="')
mstore(2940, t2)
mstore(2946, '(-50 6340 4600)"')
mstore(2962, t9)
mstore(2975, t10)
mstore(2988, 'h')
mstore(2989, t13)
mstore(2997, 'transform="scale(.9 1.3) ')
mstore(3022, t2)
mstore(3028, '(30 6740 4300)" x="400" y="-530"')
mstore(3060, t4)
mstore(3075, ' ')
mstore(3076, t10)
mstore(3089, 'a"/></g><g id="8"')
mstore(3106, t1)
mstore(3118, 'translate(7100 5100)')
mstore(3138, t14)
mstore(3145, 'transform="')
mstore(3156, t2)
mstore(3162, '(-100 -158.56 64.887) scale(.6)"')
mstore(3194, t4)
mstore(3209, ' ')
mstore(3210, t10)
mstore(3223, 'd')
mstore(3224, t13)
mstore(3232, 'transform="')
mstore(3243, t2)
mstore(3249, '(125) scale(.6)" ')
mstore(3266, t10)
mstore(3279, 'j')
mstore(3280, t13)
mstore(3288, 'transform="scale(-.6 .6) ')
mstore(3313, t2)
mstore(3319, '(-55 -272.14 -141.67)" ')
mstore(3342, t10)
mstore(3355, 'j"/></g><g id="j')
mstore(3371, t14)
mstore(3378, 'fill="#0994d3" ')
mstore(3393, t10)
mstore(3406, 'g')
mstore(3407, t13)
mstore(3415, 'fill="#8c1b85" ')
mstore(3430, t10)
mstore(3443, 'f"/></g><g id="l">')
mstore(3461, t11)
mstore(3473, '5630" cy="4060" r="140"/>')
mstore(3498, t11)
mstore(3510, '5400" cy="3850" r="110"/>')
mstore(3535, t11)
mstore(3547, '5270" cy="3600" r="90"/>')
mstore(3571, t11)
mstore(3583, '5180" cy="3350" r="70"/>')
mstore(3607, t11)
mstore(3619, '5150" cy="3150" r="60"/></g><g i')
mstore(3651, 'd="q">')
mstore(3657, t11)
mstore(3669, '6840" cy="3060" r="165" style="f')
mstore(3701, 'ill:#ed1344"/>')
mstore(3715, t11)
mstore(3727, '6770" cy="3335" r="165" style="f')
mstore(3759, 'ill:#ed1344"/>')
mstore(3773, t11)
mstore(3785, '6640" cy="3535" r="165" style="f')
mstore(3817, 'ill:#ed1344"/>')
mstore(3831, t11)
mstore(3843, '6395" cy="3690" r="165" style="f')
mstore(3875, 'ill:#ed1344"/>')
mstore(3889, t11)
mstore(3901, '6840" cy="3060" r="80" style="fi')
mstore(3933, 'll:#0994d3"/>')
mstore(3946, t11)
mstore(3958, '6770" cy="3335" r="80" style="fi')
mstore(3990, 'll:#0994d3"/>')
mstore(4003, t11)
mstore(4015, '6640" cy="3535" r="80" style="fi')
mstore(4047, 'll:#0994d3"/>')
mstore(4060, t11)
mstore(4072, '6395" cy="3690" r="80" style="fi')
mstore(4104, 'll:#0994d3"/></g><g id="p')
mstore(4129, t14)
mstore(4136, t10)
mstore(4149, 'q')
mstore(4150, t13)
mstore(4158, t10)
mstore(4171, 'q"')
mstore(4173, t1)
mstore(4185, t2)
mstore(4191, '(180 6150 3060)')
mstore(4206, t13)
mstore(4214, t10)
mstore(4227, 'q"')
mstore(4229, t1)
mstore(4241, t2)
mstore(4247, '(270 6150 3060)')
mstore(4262, t13)
mstore(4270, t10)
mstore(4283, 'q"')
mstore(4285, t1)
mstore(4297, t2)
mstore(4303, '(90 6150 3060)"/></g>')
mstore(4324, t12)
mstore(4334, 'n" d="M7507 5582c-168 33-340 50-')
mstore(4366, '517 52-177-2-349-20-517-52-345-6')
mstore(4398, '8-659-244-941-530-284-286-469-55')
mstore(4430, '6-556-814-20-57-35-116-50-175-33')
mstore(4462, '-138-48-284-46-436 0-452 74-803 ')
mstore(4494, '220-1056 98-168 133-334 102-495-')
mstore(4526, '30-159 20-308 148-441 68-68 122-')
mstore(4558, '127 166-177 41-46 74-85 96-116 4')
mstore(4590, '4-255 120-526 229-807 109-282 30')
mstore(4622, '1-443 576-489 39-6 76-11 111-18 ')
mstore(4654, '308-37 613-37 921 0 35 7 72 11 1')
mstore(4686, '13 17 273 46 465 207 574 489 109')
mstore(4718, ' 281 185 552 229 807 46 63 133 1')
mstore(4750, '59 262 292s179 282 148 441c-30 1')
mstore(4782, '61 4 327 103 495 146 253 220 605')
mstore(4814, ' 223 1056-2 218-35 421-98 611-89')
mstore(4846, ' 258-275 528-556 814-283 286-598')
mstore(4878, ' 463-941 530" fill="#fcca07"/>')
mstore(4908, t12)
mstore(4918, 'm" d="M7243 1429c-2 24-10 43-26 ')
mstore(4950, '61-15 17-34 26-54 26h-67c-21 0-4')
mstore(4982, '1-9-57-26-15-17-24-37-22-61v-260')
mstore(5014, 'c-2-24 6-44 22-61 15-17 35-26 57')
mstore(5046, '-26h68c20 0 39 9 54 26s24 37 26 ')
mstore(5078, '61v260m-9-487c-2 22-9 41-24 57-1')
mstore(5110, '5 17-33 26-52 26h-65c-20 0-37-9-')
mstore(5142, '52-26-15-15-22-35-22-57V695c0-22')
mstore(5174, ' 6-41 22-57 15-15 33-24 52-24h65')
mstore(5206, 'c20 0 37 8 52 24 15 15 22 35 24 ')
mstore(5238, '57v246m82 86c-15-20-22-39-22-63l')
mstore(5270, '.01-260c0-24 6-41 22-57 15-13 30')
mstore(5302, '-17 50-13l59 13c20 4 35 15 50 35')
mstore(5334, ' 6 11 13 24 15.34 37 2 9 4 17 4 ')
mstore(5366, '24v242c0 24-6 41-20 57-15 15-30 ')
mstore(5398, '22-50 19m263 60h-59c-20 0-37-9-5')
mstore(5430, '4-24-15-15-22-33-22-52V816c0-17 ')
mstore(5462, '6-35 22-48 15-11 31-15 46-13h9l5')
mstore(5494, '8 15c17 4 32 13 46 28 13 17 20 3')
mstore(5526, '5 20 52v204c0 20-6 35-20 48-13 1')
mstore(5558, '3-28 20-46 20m294 373c-11 11-24 ')
mstore(5590, '17-39 17h-50c-17 0-33-6-48-20-13')
mstore(5622, '-13-20-28-20-48v-201c0-15 6-28 2')
mstore(5654, '0-39 11-9 24-13 39-13h9l50 13c15')
mstore(5686, ' 2 28 11 39 26s17 31 17 46v177c0')
mstore(5718, ' 15-6 31-17 41m-480-65c0 22-7 41')
mstore(5750, '-20 57-15 18-30 26-48 26h-58c-20')
mstore(5782, ' 0-37-9-52-26s-22-37-22-61v-260c')
mstore(5814, '0-24 6-43 22-59 15-15 33-20 52-1')
mstore(5846, '7l59 6c17 2 33 13 48 33 13 17 20')
mstore(5878, ' 37 20 59v242m381-262c-17-2-33-9')
mstore(5910, '-48-24-13-15-20-30-17-50V892c-2-')
mstore(5942, '15 4-28 17-37s26-13 41-11c2 2 4 ')
mstore(5974, '2 6 2l52 17c15 7 28 15 39 31 11 ')
mstore(6006, '15 17 33 17 48v178c0 15-6 28-17 ')
mstore(6038, '39s-24 15-39 13l-52-4M7584 1488c')
mstore(6070, '-15-15-22-33-22-52v-229c0-20 6-3')
mstore(6102, '5 22-48 13-11 28-15 44-13h11l57 ')
mstore(6134, '15c17 4 33 13 48 28 13 17 20 35 ')
mstore(6166, '20 52v203c0 19-6 35-20 48-15 13-')
mstore(6198, '30 20-48 20h-57c-20 0-39-9-55-24')
mstore(6230, '"/>')
mstore(6233, t12)
mstore(6243, 'd" d="M0 0c4-54-1-112-17-177-9-4')
mstore(6275, '0-18-73-31-103 7-32 21-61 36-83 ')
mstore(6307, '28-48 53-71 78-73 22 4 39 31 54 ')
mstore(6339, '81 8 34 12 75 11 115-19 22-36 47')
mstore(6371, '-51 74C43-107 14-51 0 0"/>')
mstore(6397, t12)
mstore(6407, 'c" d="M250-340c41-36 75-48 96-40')
mstore(6439, ' 21 12 25 46 14 95-5 30-15 59-28')
mstore(6471, ' 88-8 17-14 37-25 56-8 17-20 34-')
mstore(6503, '30 54-44 68-91 124-140 163-20 16')
mstore(6535, '-40 28-55 36-15 4-27 7-37 4l-2-2')
mstore(6567, 'c-4 0-7-5-9-7-7-9-10-21-12-38 0-')
mstore(6599, '14 1-30 6-52 12-58 40-124 83-194')
mstore(6631, ' 5-7 12-13 17-20 10-19 23-40 39-')
mstore(6663, '57 28-33 56-63 85-86"/>')
mstore(6686, t12)
mstore(6696, 'o" d="M5960 3720c-33 9-76 20-127')
mstore(6728, ' 33-94 28-150 35-166 24-17-11-28')
mstore(6760, '-65-33-159-4-59-9-109-11-148-33-')
mstore(6792, '11-72-26-122-46-92-33-142-61-150')
mstore(6824, '-81-7-17 17-68 68-148 33-50 59-9')
mstore(6856, '2 78-124-20-28-44-65-72-111-55-8')
mstore(6888, '1-78-131-72-150 4-20 50-46 140-7')
mstore(6920, '8 55-22 100-41 138-57 2-26 4-59 ')
mstore(6952, '7-96v-35c4-98 15-153 31-164 15-1')
mstore(6984, '1 68-6 161 17 57 15 105 26 142 3')
mstore(7016, '5 22-26 50-61 83-103 61-76 102-1')
mstore(7048, '13 122-116 20 0 59 37 120 109 37')
mstore(7080, ' 46 68 85 94 113 33-7 76-20 129-')
mstore(7112, '35 94-24 148-33 166-22 15 11 26 ')
mstore(7144, '65 33 159 0 15 0 28 2 39 2 41 4 ')
mstore(7176, '79 6 107 33 13 74 28 124 48 92 3')
mstore(7208, '5 140 61 146 79 6 20-17 68-68 14')
mstore(7240, '8-33 50-57 92-76 124 18 30 41 68')
mstore(7272, ' 72 111 52 81 76 131 72 150-6 20')
mstore(7304, '-52 48-142 81-54 22-100 39-135 5')
mstore(7336, '4-2 35-4 78-6 133-4 98-15 153-30')
mstore(7368, ' 164-15 13-70 6-161-17-59-15-107')
mstore(7400, '-26-144-35-22 26-50 61-83 103-61')
mstore(7432, ' 76-100 116-120 116s-61-37-120-1')
mstore(7464, '11c-37-46-70-83-96-111"/>')
mstore(7489, t12)
mstore(7499, 'e" d="M6500 4100c-25 8-53 6-79-3')
mstore(7531, '-31-8-53-28-62-53-11-25-8-53 5-7')
mstore(7563, '8 11-22 31-39 56-53 11-6 25-11 3')
mstore(7595, '9-17 87-31 182-90 289-177-53 213')
mstore(7627, '-120 336-205 367-14 6-31 11-45 1')
mstore(7659, '4"/>')
mstore(7663, t12)
mstore(7673, 'h" d="M5769 4876c274 21 415 85 6')
mstore(7705, '92-127-115 159-241 266-379 326-8')
mstore(7737, '9 36-218 80-316 63-70-13-117-37-')
mstore(7769, '136-65-25-33-34-68-26-103s29-62 ')
mstore(7801, '66-80c28-16 62-22 100-14"/>')
mstore(7828, t12)
mstore(7838, 'a" d="M6740 4300c-17-22-25-48-28')
mstore(7870, '-78v-50c-3-98 34-230 109-401 62 ')
mstore(7902, '168 93 303 92 400v50c-3 31-14 56')
mstore(7934, '-31 78-20 25-45 39-70 39-28 0-53')
mstore(7966, '-14-73-39"/><g id="z')
mstore(7986, t14)
mstore(7993, 'transform="')
mstore(8004, t2)
mstore(8010, '(130 6130 3100)"')
mstore(8026, t7)
mstore(8041, ' ')
mstore(8042, t10)
mstore(8055, 'l"/>')
mstore(8059, t11)
mstore(8071, '6665" cy="4440" r="80"')
mstore(8093, t6)
mstore(8108, '/>')
mstore(8110, t11)
mstore(8122, '6370" cy="4510" r="80"')
mstore(8144, t6)
mstore(8159, '/>')
mstore(8161, t11)
mstore(8173, '6480" cy="4360" r="60"')
mstore(8195, t6)
mstore(8210, '/><use')
mstore(8216, t6)
mstore(8231, ' ')
mstore(8232, t10)
mstore(8245, 'a"/>')
mstore(8249, t11)
mstore(8261, '7000" cy="3900" r="50"')
mstore(8283, t6)
mstore(8298, '/>')
mstore(8300, t0)
mstore(8316, t2)
mstore(8322, '(-20 6500 4100)" x="110" y="50"')
mstore(8353, t4)
mstore(8368, ' ')
mstore(8369, t10)
mstore(8382, 'e')
mstore(8383, t13)
mstore(8391, 'fill="#ed1c24" ')
mstore(8406, t10)
mstore(8419, 'h"/>')
mstore(8423, t11)
mstore(8435, '5350" cy="2550" r="80"')
mstore(8457, t4)
mstore(8472, '/>')
mstore(8474, t11)
mstore(8486, '5420" cy="2280" r="130"')
mstore(8509, t4)
mstore(8524, '/>')
mstore(8526, t11)
mstore(8538, '5950" cy="4500" r="50"')
mstore(8560, t4)
mstore(8575, '/><path d="M5844 4593c36 36 81 5')
mstore(8607, '3 134 56s90-17 109-53c20-36 14-7')
mstore(8639, '3-17-104s-39-62-25-90c11-25 42-3')
mstore(8671, '4 92-20s79 53 81 118c3 68-20 118')
mstore(8703, '-73 151-53 34-109 50-174 50s-120')
mstore(8735, '-22-168-70-70-104-70-168 22-120 ')
mstore(8767, '70-168 140-90 280-132c126-42 252')
mstore(8799, '-115 379-221-126 208-235 322-325')
mstore(8831, ' 348-93 25-171 48-241 67s-106 56')
mstore(8863, '-106 106 17 93 53 129"')
mstore(8885, t6)
mstore(8900, '/>')
mstore(8902, t11)
mstore(8914, '6160" cy="3050" r="600"')
mstore(8937, t8)
mstore(8952, '/><path d="M7145 1722c59 0 109 2')
mstore(8984, '6 151 76 41 50 61 113 61 185s-19')
mstore(9016, ' 135-61 185c-41 50-120 144-236 2')
mstore(9048, '79-22 26-41 46-59 59-17-13-37-33')
mstore(9080, '-59-59-116-135-194-229-236-279-4')
mstore(9112, '1-50-63-113-61-185-2-72 20-135 6')
mstore(9144, '1-186 41-50 92-76 151-76 55 0 10')
mstore(9176, '3 24 144 70"')
mstore(9188, t8)
mstore(9203, '/><use')
mstore(9209, t9)
mstore(9222, t10)
mstore(9235, 'm')
mstore(9236, t13)
mstore(9244, t10)
}
res := 480
mstore(0x40, 30000)
// Token information
// tokenId % 1,000,000 = index of token (i.e. how many were minted before this token)
// (tokenId / 1,000,000) % 100 = week in which sacrificed occured (from game start)
// (tokenId / 100,000,000) = number of cultists remaining after sacrifice
let countdown := mod(div(tokenId, 1000000), 100)
// SHINY???
if lt(countdown, 52) {
// NO SHINY FOR YOU
mstore8(898, 0x30)
}
mstore(0x00, tokenId)
mstore(0x20, 5148293888310004) // some salt for your token
let seed := keccak256(0x00, 0x40)
// Store num living cultists at 0x00, not enough vars
mstore(0x00, div(tokenId, 100000000))
let table1 := mload(0x40)
let table2 := add(0x500, table1)
let phrase1Seed := seed
let phrase2Seed := shr(16, seed)
let phrase3Seed := shr(32, seed)
let phrase4Seed := shr(48, seed)
let descSeed := shr(64, seed)
let eyeSeed := shr(128, seed)
let rare1Seed := shr(144, seed)
let hueSeed := shr(160, seed)
let p := 9257
mstore8(p, 0x30) // "0"
if mod(descSeed, 3) {
mstore8(p, add(0x30, mod(descSeed, 3))) // "1" or "2"
}
p := add(p, 0x01)
let temp := '"/><use xlink:href="#'
mstore(p, temp)
p := add(p, 21)
mstore8(p, 0x30) // "0"
if mod(shr(16, descSeed), 3) {
mstore8(p, add(0x32, mod(shr(16, descSeed), 3))) // "3" or "4"
}
p := add(p, 0x01)
mstore(p, temp)
p := add(p, 21)
mstore8(p, 0x30) // "0"
if mod(shr(32, descSeed), 3) {
mstore8(p, add(0x34, mod(shr(32, descSeed), 3))) // "5" or "6"
}
p := add(p, 0x01)
mstore(p, temp)
p := add(p, 21)
mstore8(p, 0x30) // "0"
if mod(shr(48, descSeed), 3) {
mstore8(p, add(0x36, mod(shr(48, descSeed), 3))) // "7" or "8"
}
p := add(p, 1)
mstore(p, '"/></g></defs><g>')
p := add(p, 17)
// ARE WE BOUNCY???!!
{
/**
IF LIVINGCULTISTS > 20000 ROLL 1%
IF LIVINGCULTISTS < 20000 ROLL 2%
IF LIVINGCULTISTS < 10000 ROLL 4%
IF LIVINGCULTISTS < 2500 ROLL 8%
IF LIVINGCULTISTS < 1250 ROLL 16%
IF LIVINGCULTISTS < 625 ROLL 33%
IF LIVINGCULTISTS < 200 ROLL 100%
*/
let isBouncy := eq(mod(shr(176, seed), 100), 0)
if lt(mload(0x00), 20000) {
isBouncy := eq(mod(shr(176, seed), 50), 0)
}
if lt(mload(0x00), 10000) {
isBouncy := eq(mod(shr(176, seed), 25), 0)
}
if lt(mload(0x00), 2500) {
isBouncy := eq(mod(shr(176, seed), 12), 0)
}
if lt(mload(0x00), 1250) {
isBouncy := eq(mod(shr(176, seed), 6), 0)
}
if lt(mload(0x00), 625) {
isBouncy := eq(mod(shr(176, seed), 3), 0)
}
if lt(mload(0x00), 200) {
isBouncy := 1
}
if isBouncy {
// YESSSS WE BOUNCY
let anim1 := '<animateTransform id="anim1" att'
let anim2 := 'ributeName="transform" attribute'
let anim3 := 'Type="XML" type="rotate" from="'
let anim5 := ' repeatCount="repeat" dur="1s" b'
let anim6 := 'egin="0s;anim2.end"/>'
mstore(p, anim1)
mstore(add(p, 32), anim2)
mstore(add(p, 64), anim3)
mstore(add(p, 96), '-20 6000 5000" to="20 8000 5000"')
mstore(add(p, 128), anim5)
mstore(add(p, 160), anim6)
mstore(add(p, 181), anim1)
mstore8(add(p, 207), 0x32)
mstore(add(p, 213), anim2)
mstore(add(p, 245), anim3)
mstore(add(p, 277), '20 8000 5000" to="-20 6000 5000"')
mstore(add(p, 309), anim5)
mstore(add(p, 341), 'egin="anim1.end"/>')
p := add(p, 359)
}
mstore(p, '<g filter="invert(')
p := add(p, 18)
}
{
// 1% change of inverting colours
// increases to 50% iff week counter is 10 or greater
let isWeekTenYet := gt(countdown, 9)
let invertProbInv := add(mul(isWeekTenYet, 2), mul(iszero(isWeekTenYet), 100))
let inverted := eq(mod(rare1Seed, invertProbInv), 0)
mstore8(p, add(0x30, inverted)) // "0" or "1"
mstore(add(p, 1), ') hue-rotate(')
let hue := mul(30, mod(hueSeed, 12)) // 0 to 360 in steps of 12
mstore8(add(p, 0xe), add(0x30, mod(div(hue, 100), 10)))
mstore8(add(p, 0xf), add(0x30, mod(div(hue, 10), 10)))
mstore8(add(p, 0x10), add(0x30, mod(hue, 10)))
}
p := add(p, 17)
let eye2
{
let eye1 := add(0x6f, and(eyeSeed, 1)) // "o" or "p"
{
let hasMixedEyes := eq(mod(shr(1, eyeSeed), 10), 0)
switch hasMixedEyes
case 1 {
switch eq(eye1, 0x6f)
case 1 {
eye2 := 0x70
}
case 0 {
eye2 := 0x6f
}
}
case 0 {
eye2 := eye1
}
}
mstore(p, 'deg)"><use xlink:href="#n')
mstore(add(p, 25), temp)
p := add(p, 46)
mstore8(p, eye1) // "o" or "p"
mstore(add(p, 1), '" style="fill:#')
mstore(0x00, 'ed1c24')
mstore(0x20, '9addf0')
mstore(add(p, 16), mload(shl(5, and(shr(2, eyeSeed), 1))))
p := add(p, 22)
}
/**
Eye1 Animation
*/
{
/**
* ARE THE EYES SPINNY OR NOT?
* IF NOT YET WEEK 12 ROLL AT 0.5%
* IF AT LEAST WEEK 12 ROLL AT 2%
* IF AT LEAST WEEK 24 ROLL AT 5%
* IF AT LEAST WEEK 36 ROLL AT 20%
* IF AT LEAST WEEK 48 ROLL AT 33%
* IF WEEK 52 100% CONGRATULATIONS YOU ARE VERY SPINNY
*/
let rotatingEyes := mul(lt(countdown, 13), eq(mod(shr(3, eyeSeed), 200), 0))
rotatingEyes := add(rotatingEyes, mul(gt(countdown, 11), eq(0, mod(shr(3, eyeSeed), 50))))
rotatingEyes := add(rotatingEyes, mul(gt(countdown, 23), eq(0, mod(shr(3, eyeSeed), 20))))
rotatingEyes := add(rotatingEyes, mul(gt(countdown, 35), eq(0, mod(shr(3, eyeSeed), 5))))
rotatingEyes := add(rotatingEyes, mul(gt(countdown, 47), eq(0, mod(shr(3, eyeSeed), 3))))
rotatingEyes := add(rotatingEyes, gt(countdown, 51))
rotatingEyes := mul(5, gt(rotatingEyes, 0)) // set to 5s duration if any of the above triggers are hit
let anim1 := '"><animateTransform attributeNam'
let anim2 := 'e="transform" attributeType="XML'
let anim3 := '" type="rotate" from="360 6160 3'
let anim4 := '050" to="0 6160 3050" repeatCoun'
let anim5 := 't="indefinite" dur="'
mstore(p, anim1)
mstore(add(p, 32), anim2)
mstore(add(p, 64), anim3)
mstore(add(p, 96), anim4)
mstore(add(p, 128), anim5)
mstore8(add(p, 148), add(0x30, rotatingEyes))
mstore(add(p, 149), 's" /></use><use xlink:href="#')
// 179
p := add(p, 157)
mstore(add(p, 21), 'z"/><g transform="matrix(-1 0 0 ')
mstore(add(p, 53), '1 14000 0)"><use xlink:href="#')
p := add(p, 83)
mstore8(p, eye2) // "1" or "2"
mstore(add(p, 1), '" style="fill:#')
mstore(add(p, 16), mload(shl(5, and(shr(11, eyeSeed), 1))))
p := add(p, 22)
mstore(p, anim1)
mstore(add(p, 32), anim2)
mstore(add(p, 64), anim3)
mstore(add(p, 96), anim4)
mstore(add(p, 128), anim5)
mstore8(add(p, 148), add(0x30, rotatingEyes))
mstore(add(p, 149), 's"/></use><use xlink:href="#')
}
p := add(p, 156)
mstore(add(p, 21), 'z"/></g></g></g></g><text x="10"')
mstore(add(p, 53), ' y="25" class="soft">')
p := add(p, 74)
mstore(p, 'Week ')
p := add(p, 5)
switch gt(countdown, 9)
case 1 {
mstore8(p, add(0x30, mod(div(countdown, 10), 10))) // 0 or 1
mstore8(add(p, 1), add(0x30, mod(countdown, 10))) // 0 or 1
p := add(p, 2)
}
case 0 {
mstore8(p, add(0x30, mod(countdown, 10))) // 0 or 1
p := add(p, 1)
}
mstore(p, '</text><text x="690" y="25" clas')
mstore(add(p, 32), 's="soft" text-anchor="end">')
p := add(p, 59)
{
let livingCultists := div(tokenId, 100000000) // 100 million
switch eq(livingCultists, 0)
case 1 {
mstore8(p, 0x30)
p := add(p, 1)
}
default {
let t := livingCultists
let len := 0
for {
} t {
} {
t := div(t, 10)
len := add(len, 1)
}
for {
let i := 0
} lt(i, len) {
i := add(i, 1)
} {
mstore8(add(p, sub(sub(len, 1), i)), add(mod(livingCultists, 10), 0x30))
livingCultists := div(livingCultists, 10)
}
p := add(p, len)
}
// mstore(p, ' Cultist')
// mstore(add(p, 8), mul(iszero(oneCultist), 's'))
// p := add(p, iszero(oneCultist))
// mstore(add(p, 8), ' Remaining')
// p := add(p, 18)
}
mstore(p, '</text><text x="350" y="70" clas')
mstore(add(p, 32), 's="heavy" text-anchor="middle">')
p := add(p, 63)
mstore(table1, 0)
mstore(add(table1, 32), 'Willingly ')
mstore(add(table1, 64), 'Enthusiastically ')
mstore(add(table1, 96), 'Cravenly ')
mstore(add(table1, 128), 'Gratefully ')
mstore(add(table1, 160), 'Vicariously ')
mstore(add(table1, 192), 'Shockingly ')
mstore(add(table1, 224), 'Gruesomly ')
mstore(add(table1, 256), 'Confusingly ')
mstore(add(table1, 288), 'Angrily ')
mstore(add(table1, 320), 'Mysteriously ')
mstore(add(table1, 352), 'Shamefully ')
mstore(add(table1, 384), 'Allegedly ')
mstore(table2, 0)
mstore(add(table2, 32), 10)
mstore(add(table2, 64), 17)
mstore(add(table2, 96), 9)
mstore(add(table2, 128), 11)
mstore(add(table2, 160), 12)
mstore(add(table2, 192), 11)
mstore(add(table2, 224), 10)
mstore(add(table2, 256), 12)
mstore(add(table2, 288), 8)
mstore(add(table2, 320), 13)
mstore(add(table2, 352), 11)
mstore(add(table2, 384), 10)
let idx := mul(iszero(mod(phrase1Seed, 10)), add(0x20, shl(5, mod(shr(8, phrase1Seed), 12))))
mstore(p, mload(add(table1, idx)))
p := add(p, mload(add(table2, idx)))
mstore(add(table1, 32), 'Banished To The Void Using')
mstore(add(table1, 64), 'Crushed Under The Weight Of')
mstore(add(table1, 96), 'Devoured By')
mstore(add(table1, 128), 'Erased From Existence By')
mstore(add(table1, 160), 'Extinguished By')
mstore(add(table1, 192), 'Squished Into Nothingness By')
mstore(add(table1, 224), 'Obliterated By')
mstore(add(table1, 256), 'Ripped Apart By')
mstore(add(table1, 288), 'Sacrificed In The Service Of')
mstore(add(table1, 320), 'Slaughtered Defending')
mstore(add(table1, 352), 'Suffered 3rd Degree Burns From')
mstore(add(table1, 384), 'Torn To Shreds By')
mstore(add(table1, 416), 'Vanished At A Party Hosted By')
mstore(add(table1, 448), 'Vivisected Via')
mstore(add(table1, 480), 'Lost Everything To')
mstore(add(table1, 512), "Just Couldn't Cope With")
mstore(add(table1, 544), 'Tried To Mess With')
mstore(add(table1, 576), 'Scared To Death By')
mstore(add(table1, 608), '"Dissapeared" For Sharing')
mstore(add(table1, 640), 'Caught Red-Handed With')
mstore(add(table1, 672), 'Caught Stealing')
mstore(add(table1, 704), 'Lost A Fatal Game Of')
mstore(add(table2, 32), 26)
mstore(add(table2, 64), 27)
mstore(add(table2, 96), 11)
mstore(add(table2, 128), 24)
mstore(add(table2, 160), 15)
mstore(add(table2, 192), 28)
mstore(add(table2, 224), 14)
mstore(add(table2, 256), 15)
mstore(add(table2, 288), 28)
mstore(add(table2, 320), 21)
mstore(add(table2, 352), 30)
mstore(add(table2, 384), 17)
mstore(add(table2, 416), 29)
mstore(add(table2, 448), 14)
mstore(add(table2, 480), 18)
mstore(add(table2, 512), 23)
mstore(add(table2, 544), 18)
mstore(add(table2, 576), 18)
mstore(add(table2, 608), 25)
mstore(add(table2, 640), 22)
mstore(add(table2, 672), 15)
mstore(add(table2, 704), 20)
idx := add(0x20, shl(5, mod(phrase2Seed, 22)))
mstore(p, mload(add(table1, idx)))
p := add(p, mload(add(table2, idx)))
let lengthByte := add(p, 25)
mstore(p, '</text><text x="350" y="720" cla')
mstore(add(p, 32), 'ss="superheavy" text-anchor="mid')
mstore(add(p, 64), 'dle">')
p := add(p, 69)
mstore(add(table1, 32), 'Anarcho-Capitalist ')
mstore(add(table1, 64), 'Artificial ')
mstore(add(table1, 96), 'Another Round Of ')
mstore(add(table1, 128), 'Extreme ')
mstore(add(table1, 160), 'Ferocious ')
mstore(add(table1, 192), 'French ')
mstore(add(table1, 224), 'Funkadelic ')
mstore(add(table1, 256), 'Grossly Incompetent ')
mstore(add(table1, 288), 'Hysterical ')
mstore(add(table1, 320), 'Award-Winning ')
mstore(add(table1, 352), 'Morally Bankrupt ')
mstore(add(table1, 384), 'Overcollateralized ')
mstore(add(table1, 416), 'Politically Indiscreet ')
mstore(add(table1, 448), 'Punch-Drunk ')
mstore(add(table1, 480), 'Punk ')
mstore(add(table1, 512), 'Time-Travelling ')
mstore(add(table1, 544), 'Unsophisticated ')
mstore(add(table1, 576), 'Volcanic ')
mstore(add(table1, 608), 'Voracious ')
mstore(add(table1, 640), "Grandmother's Leftover ")
mstore(add(table1, 672), "M. Night Shyamalan's ")
mstore(add(table1, 704), 'Emergency British ')
mstore(add(table1, 736), 'Oecumenical ')
mstore(add(table1, 768), 'Another Round Of ')
mstore(add(table1, 800), 'Self-Obsessed ')
mstore(add(table1, 832), 'Number-Theoretic ')
mstore(add(table1, 864), 'Award-Winning ')
mstore(add(table1, 896), 'Chemically Enriched ')
mstore(add(table1, 928), 'Winnie-The-Pooh Themed ')
mstore(add(table1, 960), 'Gratuitously Violent ')
mstore(add(table1, 992), 'Extremely Aggressive ')
mstore(add(table1, 1024), 'Enraged ')
mstore(add(table2, 32), 19)
mstore(add(table2, 64), 11)
mstore(add(table2, 96), 17)
mstore(add(table2, 128), 8)
mstore(add(table2, 160), 10)
mstore(add(table2, 192), 7)
mstore(add(table2, 224), 11)
mstore(add(table2, 256), 20)
mstore(add(table2, 288), 11)
mstore(add(table2, 320), 14)
mstore(add(table2, 352), 17)
mstore(add(table2, 384), 19)
mstore(add(table2, 416), 23)
mstore(add(table2, 448), 12)
mstore(add(table2, 480), 5)
mstore(add(table2, 512), 16)
mstore(add(table2, 544), 16)
mstore(add(table2, 576), 9)
mstore(add(table2, 608), 10)
mstore(add(table2, 640), 23)
mstore(add(table2, 672), 21)
mstore(add(table2, 704), 18)
mstore(add(table2, 736), 12)
mstore(add(table2, 768), 17)
mstore(add(table2, 800), 14)
mstore(add(table2, 832), 17)
mstore(add(table2, 864), 14)
mstore(add(table2, 896), 20)
mstore(add(table2, 928), 23)
mstore(add(table2, 960), 21)
mstore(add(table2, 992), 21)
mstore(add(table2, 1024), 8)
let rare := eq(mod(rare1Seed, 100), 0) // mmmm rare communism...
idx := mul(iszero(rare), add(0x20, shl(5, mod(phrase3Seed, 32))))
let phrase3 := mload(add(table1, idx))
let phrase3Len := mload(add(table2, idx))
mstore(table1, 'The Communist Manifesto')
mstore(add(table1, 32), 'Ballroom Dancing Fever')
mstore(add(table1, 64), 'Canadians')
mstore(add(table1, 96), 'Electric Jazz')
mstore(add(table1, 128), 'Explosions')
mstore(add(table1, 160), 'Insurance Fraud')
mstore(add(table1, 192), 'Giant Gummy Bears')
mstore(add(table1, 224), 'Gigawatt Lasers')
mstore(add(table1, 256), 'Heavy Metal')
mstore(add(table1, 288), 'Lifestyle Vloggers')
mstore(add(table1, 320), 'Memes')
mstore(add(table1, 352), 'Mathematicians')
mstore(add(table1, 384), 'Rum Runners')
mstore(add(table1, 416), 'Swine Flu')
mstore(add(table1, 448), 'Theatre Critics')
mstore(add(table1, 480), 'Trainee Lawyers')
mstore(add(table1, 512), 'Twitterati')
mstore(add(table1, 544), 'Velociraptors')
mstore(add(table1, 576), 'Witches')
mstore(add(table1, 608), 'Wizards')
mstore(add(table1, 640), 'Z-List Celebrities')
mstore(add(table1, 672), 'High-Stakes Knitting')
mstore(add(table1, 704), 'Hardtack And Whiskey')
mstore(add(table1, 736), 'Melodramatic Bullshit')
mstore(add(table1, 768), '"Kidney Surprise"')
mstore(add(table1, 800), 'Budget Cuts')
mstore(add(table1, 832), 'Scurvy')
mstore(add(table1, 864), 'Knife-Wielding Geese')
mstore(add(table1, 896), 'Venture Capitalists')
mstore(table2, 23)
mstore(add(table2, 32), 22)
mstore(add(table2, 64), 9)
mstore(add(table2, 96), 13)
mstore(add(table2, 128), 10)
mstore(add(table2, 160), 15)
mstore(add(table2, 192), 17)
mstore(add(table2, 224), 15)
mstore(add(table2, 256), 11)
mstore(add(table2, 288), 18)
mstore(add(table2, 320), 5)
mstore(add(table2, 352), 14)
mstore(add(table2, 384), 11)
mstore(add(table2, 416), 9)
mstore(add(table2, 448), 15)
mstore(add(table2, 480), 15)
mstore(add(table2, 512), 10)
mstore(add(table2, 544), 13)
mstore(add(table2, 576), 7)
mstore(add(table2, 608), 7)
mstore(add(table2, 640), 18)
mstore(add(table2, 672), 20)
mstore(add(table2, 704), 20)
mstore(add(table2, 736), 21)
mstore(add(table2, 768), 17)
mstore(add(table2, 800), 11)
mstore(add(table2, 832), 6)
mstore(add(table2, 864), 20)
mstore(add(table2, 896), 19)
idx := mul(iszero(rare), add(0x20, shl(5, mod(phrase4Seed, 28))))
let phrase4 := mload(add(table1, idx))
let phrase4Len := mload(add(table2, idx))
switch gt(add(phrase3Len, phrase4Len), SPLIT_PHRASE_ACROSS_LINES)
case 1 {
mstore(p, '<tspan>')
mstore(add(p, 7), phrase3)
p := add(add(p, 7), phrase3Len)
mstore(p, '</tspan><tspan x="350" dy="1.2em')
mstore(add(p, 32), '">')
mstore(add(p, 34), phrase4)
p := add(p, add(34, phrase4Len))
mstore(p, '</tspan>')
p := add(p, 8)
}
default {
mstore(p, phrase3)
mstore(add(p, phrase3Len), phrase4)
p := add(p, add(phrase3Len, phrase4Len))
mstore8(lengthByte, 0x35)
}
// mstore(p, )
// p := add(p, )
mstore(p, '</text></svg>')
p := add(p, 13)
mstore(res, sub(sub(p, res), 0x20))
}
}
function tokenURI(uint256 tokenId) public pure override returns (string memory) {
// 191 + length of tokenId
uint256 strLen;
uint256 tokenLen;
uint256 id;
assembly {
id := mod(div(tokenId, 100000000), 1000000)
let x := id
for {
} x {
} {
tokenLen := add(tokenLen, 1)
x := div(x, 10)
}
tokenLen := add(tokenLen, iszero(id))
strLen := add(tokenLen, 191)
}
string memory innerData = Base64.encode(getImgData(tokenId), strLen, 2);
assembly {
let ptr := add(innerData, 0x20)
mstore(ptr, '{"name": "Cultist #')
ptr := add(ptr, 19)
switch iszero(id)
case 1 {
mstore8(ptr, 0x30)
ptr := add(ptr, 1)
}
case 0 {
let i := tokenLen
for {
} id {
} {
i := sub(i, 1)
mstore8(add(ptr, i), add(mod(id, 10), 0x30))
id := div(id, 10)
}
ptr := add(ptr, tokenLen)
}
mstore(ptr, '", "description": "Doom Cult Soc')
mstore(add(ptr, 0x20), 'iety is an interactive cult simu')
mstore(add(ptr, 0x40), 'lator. Acquire and sacrifice cul')
mstore(add(ptr, 0x60), 'tists to hasten the end of the w')
mstore(add(ptr, 0x80), 'orld.", "image": "data:image/svg')
mstore(
add(ptr, 0xa0),
or('+xml;base64,', and(0xffffffffffffffffffffffffffffffffffffffff, mload(add(ptr, 0xa0))))
)
mstore(innerData, add(mload(innerData), strLen))
ptr := add(innerData, add(0x20, mload(innerData)))
mstore(ptr, '"}')
mstore(innerData, add(mload(innerData), 2))
}
return string(abi.encodePacked('data:application/json;base64,', Base64.encode(innerData, 0, 0)));
}
function imageURI(uint256 tokenId) public pure returns (string memory) {
string memory result = Base64.encode(getImgData(tokenId), 26, 0);
assembly {
let ptr := add(result, 0x20)
mstore(ptr, or('data:image/svg+xml;base64,', and(0xffffffffffff, mload(ptr))))
mstore(result, add(mload(result), 26))
}
return result;
}
}
/// [MIT License]
/// @title Base64
/// @notice Provides a function for encoding some bytes in base64
/// @author Original author Brecht Devos <[email protected]>
/// @notice alterations have been made to this code
library Base64 {
/// @notice Encodes some bytes to the base64 representation
// bytesBefore = prepend this many bytes to the output string
// bytesAfter = append this many bytes to the output string
function encode(
string memory data,
uint256 bytesBefore,
uint256 bytesAfter
) internal pure returns (string memory result) {
assembly {
// ignore case where len = 0, shoudln't' happen with this contract
let len := mload(data)
// multiply by 4/3 rounded up
let encodedLen := shl(2, div(add(len, 2), 3))
// Add some extra buffer at the end
result := mload(0x40)
mstore(0x40, add(add(result, encodedLen), add(0x20, add(bytesBefore, bytesAfter))))
let tablePtr := mload(0x40)
mstore(add(tablePtr, 0x1f), 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdef')
mstore(add(tablePtr, 0x3f), 'ghijklmnopqrstuvwxyz0123456789+/')
let resultPtr := add(result, add(32, bytesBefore))
for {
let i := 0
} lt(i, len) {
} {
i := add(i, 3)
let input := and(mload(add(data, i)), 0xffffff)
let out := mload(add(tablePtr, and(shr(18, input), 0x3F)))
out := shl(8, out)
out := add(out, and(mload(add(tablePtr, and(shr(12, input), 0x3F))), 0xFF))
out := shl(8, out)
out := add(out, and(mload(add(tablePtr, and(shr(6, input), 0x3F))), 0xFF))
out := shl(8, out)
out := add(out, and(mload(add(tablePtr, and(input, 0x3F))), 0xFF))
out := shl(224, out)
mstore(resultPtr, out)
resultPtr := add(resultPtr, 4)
}
switch mod(len, 3)
case 1 {
mstore(sub(resultPtr, 2), shl(240, 0x3d3d))
}
case 2 {
mstore(sub(resultPtr, 1), shl(248, 0x3d))
}
mstore(result, encodedLen)
}
}
} | Mmmmmmmmmmm slightly corrupt cheeky premine aka 6.66% founder reward | _totalSupply = 1998 * CURRENCY_MULTIPLIER;
| 629,316 | [
1,
49,
7020,
7020,
7020,
7020,
7020,
21980,
16899,
462,
3317,
93,
675,
3081,
28105,
1666,
18,
6028,
9,
284,
465,
765,
19890,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
3639,
389,
4963,
3088,
1283,
273,
23673,
28,
380,
4706,
25231,
67,
24683,
2053,
654,
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
] |
pragma solidity ^0.4.23;
contract ERC20Interface {
function totalSupply() public view returns (uint);
function balanceOf(address _owner) public view returns (uint balance);
function transfer(address _to, uint _value) public returns (bool success);
function transferFrom(address _from, address _to, uint _value) public returns (bool success);
function approve(address _spender, uint _value) public returns (bool success);
function allowance(address _owner, address _spender) public view returns (uint remaining);
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
}
/**
* @title Ownable
* 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;
// The Ownable constructor sets the original `owner`
// of the contract to the sender account.
constructor() public {
owner = msg.sender;
}
// Throw if called by any account other than the current owner
modifier onlyOwner {
require(msg.sender == owner);
_;
}
// Allow the current owner to transfer control of the contract to a newOwner
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
owner = newOwner;
}
}
contract RAcoinToken is Ownable, ERC20Interface {
string public constant symbol = "RAC";
string public constant name = "RAcoinToken";
uint private _totalSupply;
uint public constant decimals = 18;
uint private unmintedTokens = 20000000000*uint(10)**decimals;
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
//Struct to hold lockup records
struct LockupRecord {
uint amount;
uint unlockTime;
}
// Balances for each account
mapping(address => uint) balances;
// Owner of account approves the transfer of an amount to another account
mapping(address => mapping (address => uint)) allowed;
// Balances for lockup accounts
mapping(address => LockupRecord)balancesLockup;
/**
====== JACKPOT IMPLEMENTATION ======
*/
// Percentage for jackpot reserving during tokens transfer
uint public reservingPercentage = 1;
// Minimum amount of jackpot, before reaching it jackpot cannot be distributed.
// Default value is 100,000 RAC
uint public jackpotMinimumAmount = 100000 * uint(10)**decimals;
// reservingStep is used for calculating how many times a user will be added to jackpot participants list:
// times user will be added to jackpotParticipants list = transfer amount / reservingStep
// the more user transfer tokens using transferWithReserving function the more times he will be added and,
// as a result, more chances to win the jackpot. Default value is 10,000 RAC
uint public reservingStep = 10000 * uint(10)**decimals;
// The seed is used each time Jackpot is distributing for generating a random number.
// First seed has some value, after the every turn of the jackpot distribution will be changed
uint private seed = 1; // Default seed
// The maximum allowed times when jackpot amount and distribution time will be set by owner,
// Used only for token sale jackpot distribution
int public maxAllowedManualDistribution = 111;
// Either or not clear the jackpot participants list after the Jackpot distribution
bool public clearJackpotParticipantsAfterDistribution = false;
// Variable that holds last actual index of jackpotParticipants collection
uint private index = 0;
// The list with Jackpot participants. The more times address is in the list, the more chances to win the Jackpot
address[] private jackpotParticipants;
event SetReservingPercentage(uint _value);
event SetReservingStep(uint _value);
event SetJackpotMinimumAmount(uint _value);
event AddAddressToJackpotParticipants(address indexed _sender, uint _times);
//Setting the reservingPercentage value, allowed only for owner
function setReservingPercentage(uint _value) public onlyOwner returns (bool success) {
assert(_value > 0 && _value < 100);
reservingPercentage = _value;
emit SetReservingPercentage(_value);
return true;
}
//Setting the reservingStep value, allowed only for owner
function setReservingStep(uint _value) public onlyOwner returns (bool success) {
assert(_value > 0);
reservingStep = _value;
emit SetReservingStep(_value);
return true;
}
//Setting the setJackpotMinimumAmount value, allowed only for owner
function setJackpotMinimumAmount(uint _value) public onlyOwner returns (bool success) {
jackpotMinimumAmount = _value;
emit SetJackpotMinimumAmount(_value);
return true;
}
//Setting the clearJackpotParticipantsAfterDistribution value, allowed only for owner
function setPoliticsForJackpotParticipantsList(bool _clearAfterDistribution) public onlyOwner returns (bool success) {
clearJackpotParticipantsAfterDistribution = _clearAfterDistribution;
return true;
}
// Empty the jackpot participants list
function clearJackpotParticipants() public onlyOwner returns (bool success) {
index = 0;
return true;
}
// Using this function a user transfers tokens and participates in operating jackpot
// User sets the total transfer amount that includes the Jackpot reserving deposit
function transferWithReserving(address _to, uint _totalTransfer) public returns (bool success) {
uint netTransfer = _totalTransfer * (100 - reservingPercentage) / 100;
require(balances[msg.sender] >= _totalTransfer && (_totalTransfer > netTransfer));
if (transferMain(msg.sender, _to, netTransfer) && (_totalTransfer >= reservingStep)) {
processJackpotDeposit(_totalTransfer, netTransfer, msg.sender);
}
return true;
}
// Using this function a user transfers tokens and participates in operating jackpot
// User sets the net value of transfer without the Jackpot reserving deposit amount
function transferWithReservingNet(address _to, uint _netTransfer) public returns (bool success) {
uint totalTransfer = _netTransfer * (100 + reservingPercentage) / 100;
require(balances[msg.sender] >= totalTransfer && (totalTransfer > _netTransfer));
if (transferMain(msg.sender, _to, _netTransfer) && (totalTransfer >= reservingStep)) {
processJackpotDeposit(totalTransfer, _netTransfer, msg.sender);
}
return true;
}
// Using this function a spender transfers tokens and make an owner of funds a participant of the operating Jackpot
// User sets the total transfer amount that includes the Jackpot reserving deposit
function transferFromWithReserving(address _from, address _to, uint _totalTransfer) public returns (bool success) {
uint netTransfer = _totalTransfer * (100 - reservingPercentage) / 100;
require(balances[_from] >= _totalTransfer && (_totalTransfer > netTransfer));
if (transferFrom(_from, _to, netTransfer) && (_totalTransfer >= reservingStep)) {
processJackpotDeposit(_totalTransfer, netTransfer, _from);
}
return true;
}
// Using this function a spender transfers tokens and make an owner of funds a participatants of the operating Jackpot
// User set the net value of transfer without the Jackpot reserving deposit amount
function transferFromWithReservingNet(address _from, address _to, uint _netTransfer) public returns (bool success) {
uint totalTransfer = _netTransfer * (100 + reservingPercentage) / 100;
require(balances[_from] >= totalTransfer && (totalTransfer > _netTransfer));
if (transferFrom(_from, _to, _netTransfer) && (totalTransfer >= reservingStep)) {
processJackpotDeposit(totalTransfer, _netTransfer, _from);
}
return true;
}
// Withdraw deposit of Jackpot amount and add address to Jackpot Participants List according to transaction amount
function processJackpotDeposit(uint _totalTransfer, uint _netTransfer, address _participant) private returns (bool success) {
addAddressToJackpotParticipants(_participant, _totalTransfer);
uint jackpotDeposit = _totalTransfer - _netTransfer;
balances[_participant] -= jackpotDeposit;
balances[0] += jackpotDeposit;
emit Transfer(_participant, 0, jackpotDeposit);
return true;
}
// Add address to Jackpot Participants List
function addAddressToJackpotParticipants(address _participant, uint _transactionAmount) private returns (bool success) {
uint timesToAdd = _transactionAmount / reservingStep;
for (uint i = 0; i < timesToAdd; i++){
if(index == jackpotParticipants.length) {
jackpotParticipants.length += 1;
}
jackpotParticipants[index++] = _participant;
}
emit AddAddressToJackpotParticipants(_participant, timesToAdd);
return true;
}
// Distribute jackpot. For finding a winner we use random number that is produced by multiplying a previous seed
// received from previous jackpot distribution and casted to uint last available block hash.
// Remainder from the received random number and total number of participants will give an index of a winner in the Jackpot participants list
function distributeJackpot(uint _nextSeed) public onlyOwner returns (bool success) {
assert(balances[0] >= jackpotMinimumAmount);
assert(_nextSeed > 0);
uint additionalSeed = uint(blockhash(block.number - 1));
uint rnd = 0;
while(rnd < index) {
rnd += additionalSeed * seed;
}
uint winner = rnd % index;
balances[jackpotParticipants[winner]] += balances[0];
emit Transfer(0, jackpotParticipants[winner], balances[0]);
balances[0] = 0;
seed = _nextSeed;
if (clearJackpotParticipantsAfterDistribution) {
clearJackpotParticipants();
}
return true;
}
// Distribute Token Sale Jackpot by minting token sale jackpot directly to 0x0 address and calling distributeJackpot function
function distributeTokenSaleJackpot(uint _nextSeed, uint _amount) public onlyOwner returns (bool success) {
require (maxAllowedManualDistribution > 0);
if (mintTokens(0, _amount) && distributeJackpot(_nextSeed)) {
maxAllowedManualDistribution--;
}
return true;
}
/**
====== ERC20 IMPLEMENTATION ======
*/
// Return total supply of tokens including locked-up funds and current Jackpot deposit
function totalSupply() public view returns (uint) {
return _totalSupply;
}
// Get the balance of the specified address
function balanceOf(address _owner) public view returns (uint balance) {
return balances[_owner];
}
// Transfer token to a specified address
function transfer(address _to, uint _value) public returns (bool success) {
require(balances[msg.sender] >= _value);
return transferMain(msg.sender, _to, _value);
}
// Transfer tokens from one address to another
function transferFrom(address _from, address _to, uint _value) public returns (bool success) {
require(balances[_from] >= _value);
require(allowed[_from][msg.sender] >= _value);
if (transferMain(_from, _to, _value)){
allowed[_from][msg.sender] -= _value;
return true;
} else {
return false;
}
}
// Main transfer function. Checking of balances is made in calling function
function transferMain(address _from, address _to, uint _value) private returns (bool success) {
require(_to != address(0));
assert(balances[_to] + _value >= balances[_to]);
balances[_from] -= _value;
balances[_to] += _value;
emit Transfer(_from, _to, _value);
return true;
}
// Approve the passed address to spend the specified amount of tokens on behalf of msg.sender
function approve(address _spender, uint _value) public returns (bool success) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
// Function to check the amount of tokens than an owner allowed to a spender
function allowance(address _owner, address _spender) public view returns (uint remaining) {
return allowed[_owner][_spender];
}
/**
====== LOCK-UP IMPLEMENTATION ======
*/
function unlockOwnFunds() public returns (bool success) {
return unlockFunds(msg.sender);
}
function unlockSupervisedFunds(address _from) public onlyOwner returns (bool success) {
return unlockFunds(_from);
}
function unlockFunds(address _owner) private returns (bool success) {
require(balancesLockup[_owner].unlockTime < now && balancesLockup[_owner].amount > 0);
balances[_owner] += balancesLockup[_owner].amount;
emit Transfer(_owner, _owner, balancesLockup[_owner].amount);
balancesLockup[_owner].amount = 0;
return true;
}
function balanceOfLockup(address _owner) public view returns (uint balance, uint unlockTime) {
return (balancesLockup[_owner].amount, balancesLockup[_owner].unlockTime);
}
/**
====== TOKENS MINTING IMPLEMENTATION ======
*/
// Mint RAcoin tokens. No more than 20,000,000,000 RAC can be minted
function mintTokens(address _target, uint _mintedAmount) public onlyOwner returns (bool success) {
require(_mintedAmount <= unmintedTokens);
balances[_target] += _mintedAmount;
unmintedTokens -= _mintedAmount;
_totalSupply += _mintedAmount;
emit Transfer(1, _target, _mintedAmount);
return true;
}
// Mint RAcoin locked-up tokens
// Using different types of minting functions has no effect on total limit of 20,000,000,000 RAC that can be created
function mintLockupTokens(address _target, uint _mintedAmount, uint _unlockTime) public onlyOwner returns (bool success) {
require(_mintedAmount <= unmintedTokens);
balancesLockup[_target].amount += _mintedAmount;
balancesLockup[_target].unlockTime = _unlockTime;
unmintedTokens -= _mintedAmount;
_totalSupply += _mintedAmount;
emit Transfer(1, _target, _mintedAmount); //TODO
return true;
}
// Mint RAcoin tokens for token sale participants and add them to Jackpot list
// Using different types of minting functions has no effect on total limit of 20,000,000,000 RAC that can be created
function mintTokensWithIncludingInJackpot(address _target, uint _mintedAmount) public onlyOwner returns (bool success) {
require(maxAllowedManualDistribution > 0);
if (mintTokens(_target, _mintedAmount)) {
addAddressToJackpotParticipants(_target, _mintedAmount);
}
return true;
}
// Mint RAcoin tokens and approve the passed address to spend the minted amount of tokens
// Using different types of minting functions has no effect on total limit of 20,000,000,000 RAC that can be created
function mintTokensWithApproval(address _target, uint _mintedAmount, address _spender) public onlyOwner returns (bool success) {
require(_mintedAmount <= unmintedTokens);
balances[_target] += _mintedAmount;
unmintedTokens -= _mintedAmount;
_totalSupply += _mintedAmount;
allowed[_target][_spender] += _mintedAmount;
emit Transfer(1, _target, _mintedAmount);
return true;
}
// After firing this function no more tokens can be created
function stopTokenMinting() public onlyOwner returns (bool success) {
unmintedTokens = 0;
return true;
}
} | Setting the reservingStep value, allowed only for owner | function setReservingStep(uint _value) public onlyOwner returns (bool success) {
assert(_value > 0);
reservingStep = _value;
emit SetReservingStep(_value);
return true;
}
| 7,952,821 | [
1,
5568,
326,
400,
264,
6282,
4160,
460,
16,
2935,
1338,
364,
3410,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
607,
264,
6282,
4160,
12,
11890,
389,
1132,
13,
1071,
1338,
5541,
1135,
261,
6430,
2216,
13,
288,
203,
3639,
1815,
24899,
1132,
405,
374,
1769,
203,
3639,
400,
264,
6282,
4160,
273,
389,
1132,
31,
203,
3639,
3626,
1000,
607,
264,
6282,
4160,
24899,
1132,
1769,
203,
3639,
327,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/42220/0xE0EE7Cd0890e8f290A1A1e5E2300658A4016EEd9/sources/SuperVault_flat.sol | * @notice Custom logic for how much the vault allows to be borrowed @dev The contract puts 100% of the tokens to work./ | function available() public view returns (uint256) {
return STAKED_TOKEN.balanceOf(address(this));
}
| 16,330,046 | [
1,
3802,
4058,
364,
3661,
9816,
326,
9229,
5360,
358,
506,
29759,
329,
225,
1021,
6835,
8200,
2130,
9,
434,
326,
2430,
358,
1440,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
2319,
1435,
1071,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
327,
2347,
14607,
2056,
67,
8412,
18,
12296,
951,
12,
2867,
12,
2211,
10019,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
pragma experimental ABIEncoderV2;
library Internal_Merkle_Library_Sorted_Hash {
// Hashes a and b in the order they are passed
function hash_node(bytes32 a, bytes32 b) internal pure returns (bytes32 hash) {
assembly {
mstore(0x00, a)
mstore(0x20, b)
hash := keccak256(0x00, 0x40)
}
}
// Hashes a and b in sorted order
function hash_pair(bytes32 a, bytes32 b) internal pure returns (bytes32 hash) {
hash = a < b ? hash_node(a, b) : hash_node(b, a);
}
// Counts number of set bits (1's) in 32-bit unsigned integer
function bit_count_32(uint32 n) internal pure returns (uint32) {
n = n - ((n >> 1) & 0x55555555);
n = (n & 0x33333333) + ((n >> 2) & 0x33333333);
return (((n + (n >> 4)) & 0xF0F0F0F) * 0x1010101) >> 24;
}
// Round 32-bit unsigned integer up to the nearest power of 2
function round_up_to_power_of_2(uint32 n) internal pure returns (uint32) {
if (bit_count_32(n) == 1) return n;
n |= n >> 1;
n |= n >> 2;
n |= n >> 4;
n |= n >> 8;
n |= n >> 16;
return n + 1;
}
// Get the Element Merkle Root for a tree with just a single bytes element in calldata
function get_root_from_one_c(bytes calldata element) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(bytes1(0), element));
}
// Get the Element Merkle Root for a tree with just a single bytes element in memory
function get_root_from_one_m(bytes memory element) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(bytes1(0), element));
}
// Get the Element Merkle Root for a tree with just a single bytes32 element in calldata
function get_root_from_one(bytes32 element) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(bytes1(0), element));
}
// Get nodes (parent of leafs) from bytes elements in calldata
function get_nodes_from_elements_c(bytes[] calldata elements) internal pure returns (bytes32[] memory nodes) {
uint256 element_count = elements.length;
uint256 node_count = (element_count >> 1) + (element_count & 1);
nodes = new bytes32[](node_count);
uint256 write_index;
uint256 left_index;
while (write_index < node_count) {
left_index = write_index << 1;
if (left_index == element_count - 1) {
nodes[write_index] = keccak256(abi.encodePacked(bytes1(0), elements[left_index]));
break;
}
nodes[write_index++] = hash_pair(
keccak256(abi.encodePacked(bytes1(0), elements[left_index])),
keccak256(abi.encodePacked(bytes1(0), elements[left_index + 1]))
);
}
}
// Get nodes (parent of leafs) from bytes elements in memory
function get_nodes_from_elements_m(bytes[] memory elements) internal pure returns (bytes32[] memory nodes) {
uint256 element_count = elements.length;
uint256 node_count = (element_count >> 1) + (element_count & 1);
nodes = new bytes32[](node_count);
uint256 write_index;
uint256 left_index;
while (write_index < node_count) {
left_index = write_index << 1;
if (left_index == element_count - 1) {
nodes[write_index] = keccak256(abi.encodePacked(bytes1(0), elements[left_index]));
break;
}
nodes[write_index++] = hash_pair(
keccak256(abi.encodePacked(bytes1(0), elements[left_index])),
keccak256(abi.encodePacked(bytes1(0), elements[left_index + 1]))
);
}
}
// Get nodes (parent of leafs) from bytes32 elements in calldata
function get_nodes_from_elements_c(bytes32[] calldata elements) internal pure returns (bytes32[] memory nodes) {
uint256 element_count = elements.length;
uint256 node_count = (element_count >> 1) + (element_count & 1);
nodes = new bytes32[](node_count);
uint256 write_index;
uint256 left_index;
while (write_index < node_count) {
left_index = write_index << 1;
if (left_index == element_count - 1) {
nodes[write_index] = keccak256(abi.encodePacked(bytes1(0), elements[left_index]));
break;
}
nodes[write_index++] = hash_pair(
keccak256(abi.encodePacked(bytes1(0), elements[left_index])),
keccak256(abi.encodePacked(bytes1(0), elements[left_index + 1]))
);
}
}
// Get nodes (parent of leafs) from bytes32 elements in memory
function get_nodes_from_elements_m(bytes32[] memory elements) internal pure returns (bytes32[] memory nodes) {
uint256 element_count = elements.length;
uint256 node_count = (element_count >> 1) + (element_count & 1);
nodes = new bytes32[](node_count);
uint256 write_index;
uint256 left_index;
while (write_index < node_count) {
left_index = write_index << 1;
if (left_index == element_count - 1) {
nodes[write_index] = keccak256(abi.encodePacked(bytes1(0), elements[left_index]));
break;
}
nodes[write_index++] = hash_pair(
keccak256(abi.encodePacked(bytes1(0), elements[left_index])),
keccak256(abi.encodePacked(bytes1(0), elements[left_index + 1]))
);
}
}
// Get the Element Merkle Root given nodes (parent of leafs)
function get_root_from_nodes(bytes32[] memory nodes) internal pure returns (bytes32) {
uint256 node_count = nodes.length;
uint256 write_index;
uint256 left_index;
while (node_count > 1) {
left_index = write_index << 1;
if (left_index == node_count - 1) {
nodes[write_index] = nodes[left_index];
write_index = 0;
node_count = (node_count >> 1) + (node_count & 1);
continue;
}
if (left_index >= node_count) {
write_index = 0;
node_count = (node_count >> 1) + (node_count & 1);
continue;
}
nodes[write_index++] = hash_pair(nodes[left_index], nodes[left_index + 1]);
}
return nodes[0];
}
// Get the Element Merkle Root for a tree with several bytes elements in calldata
function get_root_from_many_c(bytes[] calldata elements) internal pure returns (bytes32) {
return get_root_from_nodes(get_nodes_from_elements_c(elements));
}
// Get the Element Merkle Root for a tree with several bytes elements in memory
function get_root_from_many_m(bytes[] memory elements) internal pure returns (bytes32) {
return get_root_from_nodes(get_nodes_from_elements_m(elements));
}
// Get the Element Merkle Root for a tree with several bytes32 elements in calldata
function get_root_from_many_c(bytes32[] calldata elements) internal pure returns (bytes32) {
return get_root_from_nodes(get_nodes_from_elements_c(elements));
}
// Get the Element Merkle Root for a tree with several bytes32 elements in memory
function get_root_from_many_m(bytes32[] memory elements) internal pure returns (bytes32) {
return get_root_from_nodes(get_nodes_from_elements_m(elements));
}
// get_root_from_size_proof cannot be implemented with sorted hashed pairs
// Get the original Element Merkle Root, given an index, a leaf, and a Single Proof
function get_root_from_leaf_and_single_proof(
uint256 index,
bytes32 leaf,
bytes32[] calldata proof
) internal pure returns (bytes32) {
uint256 proof_index = proof.length - 1;
uint256 upper_bound = uint256(proof[0]) - 1;
while (proof_index > 0) {
if (index != upper_bound || (index & 1 == 1)) {
leaf = hash_pair(proof[proof_index], leaf);
proof_index -= 1;
}
index >>= 1;
upper_bound >>= 1;
}
return leaf;
}
// Get the original Element Merkle Root, given an index, a bytes element in calldata, and a Single Proof
function get_root_from_single_proof_c(
uint256 index,
bytes calldata element,
bytes32[] calldata proof
) internal pure returns (bytes32 hash) {
hash = keccak256(abi.encodePacked(bytes1(0), element));
hash = get_root_from_leaf_and_single_proof(index, hash, proof);
}
// Get the original Element Merkle Root, given an index, a bytes element in memory, and a Single Proof
function get_root_from_single_proof_m(
uint256 index,
bytes memory element,
bytes32[] calldata proof
) internal pure returns (bytes32 hash) {
hash = keccak256(abi.encodePacked(bytes1(0), element));
hash = get_root_from_leaf_and_single_proof(index, hash, proof);
}
// Get the original Element Merkle Root, given an index, a bytes32 element, and a Single Proof
function get_root_from_single_proof(
uint256 index,
bytes32 element,
bytes32[] calldata proof
) internal pure returns (bytes32 hash) {
hash = keccak256(abi.encodePacked(bytes1(0), element));
hash = get_root_from_leaf_and_single_proof(index, hash, proof);
}
// Get the original and updated Element Merkle Root, given an index, a leaf, an update leaf, and a Single Proof
function get_roots_from_leaf_and_single_proof_update(
uint256 index,
bytes32 leaf,
bytes32 update_leaf,
bytes32[] calldata proof
) internal pure returns (bytes32 scratch, bytes32) {
uint256 proof_index = proof.length - 1;
uint256 upper_bound = uint256(proof[0]) - 1;
while (proof_index > 0) {
if ((index != upper_bound) || (index & 1 == 1)) {
scratch = proof[proof_index];
proof_index -= 1;
leaf = hash_pair(scratch, leaf);
update_leaf = hash_pair(scratch, update_leaf);
}
index >>= 1;
upper_bound >>= 1;
}
return (leaf, update_leaf);
}
// Get the original and updated Element Merkle Root,
// given an index, a bytes element in calldata, a bytes update element in calldata, and a Single Proof
function get_roots_from_single_proof_update_c(
uint256 index,
bytes calldata element,
bytes calldata update_element,
bytes32[] calldata proof
) internal pure returns (bytes32 hash, bytes32 update_hash) {
hash = keccak256(abi.encodePacked(bytes1(0), element));
update_hash = keccak256(abi.encodePacked(bytes1(0), update_element));
return get_roots_from_leaf_and_single_proof_update(index, hash, update_hash, proof);
}
// Get the original and updated Element Merkle Root,
// given an index, a bytes element in calldata, a bytes update element in memory, and a Single Proof
function get_roots_from_single_proof_update_m(
uint256 index,
bytes calldata element,
bytes memory update_element,
bytes32[] calldata proof
) internal pure returns (bytes32 hash, bytes32 update_hash) {
hash = keccak256(abi.encodePacked(bytes1(0), element));
update_hash = keccak256(abi.encodePacked(bytes1(0), update_element));
return get_roots_from_leaf_and_single_proof_update(index, hash, update_hash, proof);
}
// Get the original and updated Element Merkle Root, given an index, a bytes32 element, a bytes32 update element, and a Single Proof
function get_roots_from_single_proof_update(
uint256 index,
bytes32 element,
bytes32 update_element,
bytes32[] calldata proof
) internal pure returns (bytes32 hash, bytes32 update_hash) {
hash = keccak256(abi.encodePacked(bytes1(0), element));
update_hash = keccak256(abi.encodePacked(bytes1(0), update_element));
return get_roots_from_leaf_and_single_proof_update(index, hash, update_hash, proof);
}
// get_indices_from_multi_proof cannot be implemented with sorted hashed pairs
// Get leafs from bytes elements in calldata, in reverse order
function get_reversed_leafs_from_elements_c(bytes[] calldata elements)
internal
pure
returns (bytes32[] memory leafs)
{
uint256 element_count = elements.length;
leafs = new bytes32[](element_count);
uint256 read_index = element_count - 1;
uint256 write_index;
while (write_index < element_count) {
leafs[write_index] = keccak256(abi.encodePacked(bytes1(0), elements[read_index]));
write_index += 1;
read_index -= 1;
}
}
// Get leafs from bytes elements in memory, in reverse order
function get_reversed_leafs_from_elements_m(bytes[] memory elements) internal pure returns (bytes32[] memory leafs) {
uint256 element_count = elements.length;
leafs = new bytes32[](element_count);
uint256 read_index = element_count - 1;
uint256 write_index;
while (write_index < element_count) {
leafs[write_index] = keccak256(abi.encodePacked(bytes1(0), elements[read_index]));
write_index += 1;
read_index -= 1;
}
}
// Get leafs from bytes32 elements in calldata, in reverse order
function get_reversed_leafs_from_elements_c(bytes32[] calldata elements)
internal
pure
returns (bytes32[] memory leafs)
{
uint256 element_count = elements.length;
leafs = new bytes32[](element_count);
uint256 read_index = element_count - 1;
uint256 write_index;
while (write_index < element_count) {
leafs[write_index] = keccak256(abi.encodePacked(bytes1(0), elements[read_index]));
write_index += 1;
read_index -= 1;
}
}
// Get leafs from bytes32 elements in memory, in reverse order
function get_reversed_leafs_from_elements_m(bytes32[] memory elements)
internal
pure
returns (bytes32[] memory leafs)
{
uint256 element_count = elements.length;
leafs = new bytes32[](element_count);
uint256 read_index = element_count - 1;
uint256 write_index;
while (write_index < element_count) {
leafs[write_index] = keccak256(abi.encodePacked(bytes1(0), elements[read_index]));
write_index += 1;
read_index -= 1;
}
}
// Get the original Element Merkle Root, given leafs and an Existence Multi Proof
function get_root_from_leafs_and_multi_proof(bytes32[] memory leafs, bytes32[] calldata proof)
internal
pure
returns (bytes32 right)
{
uint256 leaf_count = leafs.length;
uint256 read_index;
uint256 write_index;
uint256 proof_index = 3;
bytes32 bit_check = 0x0000000000000000000000000000000000000000000000000000000000000001;
bytes32 flags = proof[1];
bytes32 skips = proof[2];
while (true) {
if (skips & bit_check == bit_check) {
if (flags & bit_check == bit_check) return leafs[(write_index == 0 ? leaf_count : write_index) - 1];
leafs[write_index] = leafs[read_index];
read_index = (read_index + 1) % leaf_count;
write_index = (write_index + 1) % leaf_count;
bit_check <<= 1;
continue;
}
right = (flags & bit_check == bit_check) ? leafs[read_index++] : proof[proof_index++];
read_index %= leaf_count;
leafs[write_index] = hash_pair(right, leafs[read_index]);
read_index = (read_index + 1) % leaf_count;
write_index = (write_index + 1) % leaf_count;
bit_check <<= 1;
}
}
// Get the original Element Merkle Root, given bytes elements in calldata and an Existence Multi Proof
function get_root_from_multi_proof_c(bytes[] calldata elements, bytes32[] calldata proof)
internal
pure
returns (bytes32)
{
return get_root_from_leafs_and_multi_proof(get_reversed_leafs_from_elements_c(elements), proof);
}
// Get the original Element Merkle Root, given bytes elements in memory and an Existence Multi Proof
function get_root_from_multi_proof_m(bytes[] memory elements, bytes32[] calldata proof)
internal
pure
returns (bytes32)
{
return get_root_from_leafs_and_multi_proof(get_reversed_leafs_from_elements_m(elements), proof);
}
// Get the original Element Merkle Root, given bytes32 elements in calldata and an Existence Multi Proof
function get_root_from_multi_proof_c(bytes32[] calldata elements, bytes32[] calldata proof)
internal
pure
returns (bytes32)
{
return get_root_from_leafs_and_multi_proof(get_reversed_leafs_from_elements_c(elements), proof);
}
// Get the original Element Merkle Root, given bytes32 elements in memory and an Existence Multi Proof
function get_root_from_multi_proof_m(bytes32[] memory elements, bytes32[] calldata proof)
internal
pure
returns (bytes32)
{
return get_root_from_leafs_and_multi_proof(get_reversed_leafs_from_elements_m(elements), proof);
}
// Get current and update leafs from current bytes elements in calldata and update bytes elements in calldata, in reverse order
function get_reversed_leafs_from_current_and_update_elements_c(
bytes[] calldata elements,
bytes[] calldata update_elements
) internal pure returns (bytes32[] memory leafs, bytes32[] memory update_leafs) {
uint256 element_count = elements.length;
require(update_elements.length == element_count, "LENGTH_MISMATCH");
leafs = new bytes32[](element_count);
update_leafs = new bytes32[](element_count);
uint256 read_index = element_count - 1;
uint256 write_index;
while (write_index < element_count) {
leafs[write_index] = keccak256(abi.encodePacked(bytes1(0), elements[read_index]));
update_leafs[write_index] = keccak256(abi.encodePacked(bytes1(0), update_elements[read_index]));
write_index += 1;
read_index -= 1;
}
}
// Get current and update leafs from current bytes elements in calldata and update bytes elements in memory, in reverse order
function get_reversed_leafs_from_current_and_update_elements_m(
bytes[] calldata elements,
bytes[] memory update_elements
) internal pure returns (bytes32[] memory leafs, bytes32[] memory update_leafs) {
uint256 element_count = elements.length;
require(update_elements.length == element_count, "LENGTH_MISMATCH");
leafs = new bytes32[](element_count);
update_leafs = new bytes32[](element_count);
uint256 read_index = element_count - 1;
uint256 write_index;
while (write_index < element_count) {
leafs[write_index] = keccak256(abi.encodePacked(bytes1(0), elements[read_index]));
update_leafs[write_index] = keccak256(abi.encodePacked(bytes1(0), update_elements[read_index]));
write_index += 1;
read_index -= 1;
}
}
// Get current and update leafs from current bytes32 elements in calldata and update bytes32 elements in calldata, in reverse order
function get_reversed_leafs_from_current_and_update_elements_c(
bytes32[] calldata elements,
bytes32[] calldata update_elements
) internal pure returns (bytes32[] memory leafs, bytes32[] memory update_leafs) {
uint256 element_count = elements.length;
require(update_elements.length == element_count, "LENGTH_MISMATCH");
leafs = new bytes32[](element_count);
update_leafs = new bytes32[](element_count);
uint256 read_index = element_count - 1;
uint256 write_index;
while (write_index < element_count) {
leafs[write_index] = keccak256(abi.encodePacked(bytes1(0), elements[read_index]));
update_leafs[write_index] = keccak256(abi.encodePacked(bytes1(0), update_elements[read_index]));
write_index += 1;
read_index -= 1;
}
}
// Get current and update leafs from current bytes32 elements in calldata and update bytes32 elements in memory, in reverse order
function get_reversed_leafs_from_current_and_update_elements_m(
bytes32[] calldata elements,
bytes32[] memory update_elements
) internal pure returns (bytes32[] memory leafs, bytes32[] memory update_leafs) {
uint256 element_count = elements.length;
require(update_elements.length == element_count, "LENGTH_MISMATCH");
leafs = new bytes32[](element_count);
update_leafs = new bytes32[](element_count);
uint256 read_index = element_count - 1;
uint256 write_index;
while (write_index < element_count) {
leafs[write_index] = keccak256(abi.encodePacked(bytes1(0), elements[read_index]));
update_leafs[write_index] = keccak256(abi.encodePacked(bytes1(0), update_elements[read_index]));
write_index += 1;
read_index -= 1;
}
}
// Get the original and updated Element Merkle Root, given leafs, update leafs, and an Existence Multi Proof
function get_roots_from_leafs_and_multi_proof_update(
bytes32[] memory leafs,
bytes32[] memory update_leafs,
bytes32[] calldata proof
) internal pure returns (bytes32 flags, bytes32 skips) {
uint256 leaf_count = update_leafs.length;
uint256 read_index;
uint256 write_index;
uint256 proof_index = 3;
bytes32 bit_check = 0x0000000000000000000000000000000000000000000000000000000000000001;
flags = proof[1];
skips = proof[2];
bytes32 scratch;
uint256 scratch_2;
while (true) {
if (skips & bit_check == bit_check) {
if (flags & bit_check == bit_check) {
read_index = (write_index == 0 ? leaf_count : write_index) - 1;
return (leafs[read_index], update_leafs[read_index]);
}
leafs[write_index] = leafs[read_index];
update_leafs[write_index] = update_leafs[read_index];
read_index = (read_index + 1) % leaf_count;
write_index = (write_index + 1) % leaf_count;
bit_check <<= 1;
continue;
}
if (flags & bit_check == bit_check) {
scratch_2 = (read_index + 1) % leaf_count;
leafs[write_index] = hash_pair(leafs[read_index], leafs[scratch_2]);
update_leafs[write_index] = hash_pair(update_leafs[read_index], update_leafs[scratch_2]);
read_index += 2;
} else {
scratch = proof[proof_index++];
leafs[write_index] = hash_pair(scratch, leafs[read_index]);
update_leafs[write_index] = hash_pair(scratch, update_leafs[read_index]);
read_index += 1;
}
read_index %= leaf_count;
write_index = (write_index + 1) % leaf_count;
bit_check <<= 1;
}
}
// Get the original and updated Element Merkle Root,
// given bytes elements in calldata, bytes update elements in calldata, and an Existence Multi Proof
function get_roots_from_multi_proof_update_c(
bytes[] calldata elements,
bytes[] calldata update_elements,
bytes32[] calldata proof
) internal pure returns (bytes32, bytes32) {
(bytes32[] memory leafs, bytes32[] memory update_leafs) = get_reversed_leafs_from_current_and_update_elements_c(
elements,
update_elements
);
return get_roots_from_leafs_and_multi_proof_update(leafs, update_leafs, proof);
}
// Get the original and updated Element Merkle Root,
// given bytes elements in calldata, bytes update elements in memory, and an Existence Multi Proof
function get_roots_from_multi_proof_update_m(
bytes[] calldata elements,
bytes[] memory update_elements,
bytes32[] calldata proof
) internal pure returns (bytes32, bytes32) {
(bytes32[] memory leafs, bytes32[] memory update_leafs) = get_reversed_leafs_from_current_and_update_elements_m(
elements,
update_elements
);
return get_roots_from_leafs_and_multi_proof_update(leafs, update_leafs, proof);
}
// Get the original and updated Element Merkle Root,
// given bytes32 elements in calldata, bytes32 update elements in calldata, and an Existence Multi Proof
function get_roots_from_multi_proof_update_c(
bytes32[] calldata elements,
bytes32[] calldata update_elements,
bytes32[] calldata proof
) internal pure returns (bytes32, bytes32) {
(bytes32[] memory leafs, bytes32[] memory update_leafs) = get_reversed_leafs_from_current_and_update_elements_c(
elements,
update_elements
);
return get_roots_from_leafs_and_multi_proof_update(leafs, update_leafs, proof);
}
// Get the original and updated Element Merkle Root,
// given bytes32 elements in calldata, bytes32 update elements in memory, and an Existence Multi Proof
function get_roots_from_multi_proof_update_m(
bytes32[] calldata elements,
bytes32[] memory update_elements,
bytes32[] calldata proof
) internal pure returns (bytes32, bytes32) {
(bytes32[] memory leafs, bytes32[] memory update_leafs) = get_reversed_leafs_from_current_and_update_elements_m(
elements,
update_elements
);
return get_roots_from_leafs_and_multi_proof_update(leafs, update_leafs, proof);
}
// Get the original Element Merkle Root, given an Append Proof
function get_root_from_append_proof(bytes32[] calldata proof) internal pure returns (bytes32 hash) {
uint256 proof_index = bit_count_32(uint32(uint256(proof[0])));
hash = proof[proof_index];
while (proof_index > 1) {
proof_index -= 1;
hash = hash_pair(proof[proof_index], hash);
}
}
// Get the original and updated Element Merkle Root, given append leaf and an Append Proof
function get_roots_from_leaf_and_append_proof_single_append(bytes32 append_leaf, bytes32[] calldata proof)
internal
pure
returns (bytes32 hash, bytes32 scratch)
{
uint256 proof_index = bit_count_32(uint32(uint256(proof[0])));
hash = proof[proof_index];
append_leaf = hash_pair(hash, append_leaf);
while (proof_index > 1) {
proof_index -= 1;
scratch = proof[proof_index];
append_leaf = hash_pair(scratch, append_leaf);
hash = hash_pair(scratch, hash);
}
return (hash, append_leaf);
}
// Get the original and updated Element Merkle Root, given a bytes append element in calldata and an Append Proof
function get_roots_from_append_proof_single_append_c(bytes calldata append_element, bytes32[] calldata proof)
internal
pure
returns (bytes32 append_leaf, bytes32)
{
append_leaf = keccak256(abi.encodePacked(bytes1(0), append_element));
return get_roots_from_leaf_and_append_proof_single_append(append_leaf, proof);
}
// Get the original and updated Element Merkle Root, given a bytes append element in memory and an Append Proof
function get_roots_from_append_proof_single_append_m(bytes memory append_element, bytes32[] calldata proof)
internal
pure
returns (bytes32 append_leaf, bytes32)
{
append_leaf = keccak256(abi.encodePacked(bytes1(0), append_element));
return get_roots_from_leaf_and_append_proof_single_append(append_leaf, proof);
}
// Get the original and updated Element Merkle Root, given a bytes32 append element in calldata and an Append Proof
function get_roots_from_append_proof_single_append(bytes32 append_element, bytes32[] calldata proof)
internal
pure
returns (bytes32 append_leaf, bytes32)
{
append_leaf = keccak256(abi.encodePacked(bytes1(0), append_element));
return get_roots_from_leaf_and_append_proof_single_append(append_leaf, proof);
}
// Get leafs from bytes elements in calldata
function get_leafs_from_elements_c(bytes[] calldata elements) internal pure returns (bytes32[] memory leafs) {
uint256 element_count = elements.length;
leafs = new bytes32[](element_count);
while (element_count > 0) {
element_count -= 1;
leafs[element_count] = keccak256(abi.encodePacked(bytes1(0), elements[element_count]));
}
}
// Get leafs from bytes elements in memory
function get_leafs_from_elements_m(bytes[] memory elements) internal pure returns (bytes32[] memory leafs) {
uint256 element_count = elements.length;
leafs = new bytes32[](element_count);
while (element_count > 0) {
element_count -= 1;
leafs[element_count] = keccak256(abi.encodePacked(bytes1(0), elements[element_count]));
}
}
// Get leafs from bytes32 elements in calldata
function get_leafs_from_elements_c(bytes32[] calldata elements) internal pure returns (bytes32[] memory leafs) {
uint256 element_count = elements.length;
leafs = new bytes32[](element_count);
while (element_count > 0) {
element_count -= 1;
leafs[element_count] = keccak256(abi.encodePacked(bytes1(0), elements[element_count]));
}
}
// Get leafs from bytes32 elements in memory
function get_leafs_from_elements_m(bytes32[] memory elements) internal pure returns (bytes32[] memory leafs) {
uint256 element_count = elements.length;
leafs = new bytes32[](element_count);
while (element_count > 0) {
element_count -= 1;
leafs[element_count] = keccak256(abi.encodePacked(bytes1(0), elements[element_count]));
}
}
// Get the original and updated Element Merkle Root, given append leafs and an Append Proof
function get_roots_from_leafs_and_append_proof_multi_append(bytes32[] memory append_leafs, bytes32[] calldata proof)
internal
pure
returns (bytes32 hash, bytes32)
{
uint256 leaf_count = append_leafs.length;
uint256 write_index;
uint256 read_index;
uint256 offset = uint256(proof[0]);
uint256 index = offset;
// reuse leaf_count variable as upper_bound, since leaf_count no longer needed
leaf_count += offset;
leaf_count -= 1;
uint256 proof_index = bit_count_32(uint32(offset));
hash = proof[proof_index];
while (leaf_count > 0) {
if ((write_index == 0) && (index & 1 == 1)) {
append_leafs[0] = hash_pair(proof[proof_index], append_leafs[read_index]);
proof_index -= 1;
read_index += 1;
if (proof_index > 0) {
hash = hash_pair(proof[proof_index], hash);
}
write_index = 1;
index += 1;
} else if (index < leaf_count) {
append_leafs[write_index++] = hash_pair(append_leafs[read_index++], append_leafs[read_index]);
read_index += 1;
index += 2;
}
if (index >= leaf_count) {
if (index == leaf_count) {
append_leafs[write_index] = append_leafs[read_index];
}
read_index = 0;
write_index = 0;
leaf_count >>= 1;
offset >>= 1;
index = offset;
}
}
return (hash, append_leafs[0]);
}
// Get the original and updated Element Merkle Root, given bytes append elements in calldata and an Append Proof
function get_roots_from_append_proof_multi_append_c(bytes[] calldata append_elements, bytes32[] calldata proof)
internal
pure
returns (bytes32, bytes32)
{
return get_roots_from_leafs_and_append_proof_multi_append(get_leafs_from_elements_c(append_elements), proof);
}
// Get the original and updated Element Merkle Root, given bytes append elements in memory and an Append Proof
function get_roots_from_append_proof_multi_append_m(bytes[] memory append_elements, bytes32[] calldata proof)
internal
pure
returns (bytes32, bytes32)
{
return get_roots_from_leafs_and_append_proof_multi_append(get_leafs_from_elements_m(append_elements), proof);
}
// Get the original and updated Element Merkle Root, given bytes32 append elements in calldata and an Append Proof
function get_roots_from_append_proof_multi_append_c(bytes32[] calldata append_elements, bytes32[] calldata proof)
internal
pure
returns (bytes32, bytes32)
{
return get_roots_from_leafs_and_append_proof_multi_append(get_leafs_from_elements_c(append_elements), proof);
}
// Get the original and updated Element Merkle Root, given bytes32 append elements in memory and an Append Proof
function get_roots_from_append_proof_multi_append_m(bytes32[] memory append_elements, bytes32[] calldata proof)
internal
pure
returns (bytes32, bytes32)
{
return get_roots_from_leafs_and_append_proof_multi_append(get_leafs_from_elements_m(append_elements), proof);
}
// Get the updated Element Merkle Root, given an append leaf and an Append Proof
function get_new_root_from_leafs_and_append_proof_single_append(bytes32 append_leaf, bytes32[] memory proof)
internal
pure
returns (bytes32 append_hash)
{
uint256 proof_index = bit_count_32(uint32(uint256(proof[0])));
append_hash = hash_pair(proof[proof_index], append_leaf);
while (proof_index > 1) {
proof_index -= 1;
append_hash = hash_pair(proof[proof_index], append_hash);
}
}
// Get the updated Element Merkle Root, given a bytes append elements in calldata and an Append Proof
function get_new_root_from_append_proof_single_append_c(bytes calldata append_element, bytes32[] memory proof)
internal
pure
returns (bytes32 append_leaf)
{
append_leaf = keccak256(abi.encodePacked(bytes1(0), append_element));
return get_new_root_from_leafs_and_append_proof_single_append(append_leaf, proof);
}
// Get the updated Element Merkle Root, given a bytes append elements in memory and an Append Proof
function get_new_root_from_append_proof_single_append_m(bytes memory append_element, bytes32[] memory proof)
internal
pure
returns (bytes32 append_leaf)
{
append_leaf = keccak256(abi.encodePacked(bytes1(0), append_element));
return get_new_root_from_leafs_and_append_proof_single_append(append_leaf, proof);
}
// Get the updated Element Merkle Root, given a bytes32 append elements in calldata and an Append Proof
function get_new_root_from_append_proof_single_append(bytes32 append_element, bytes32[] memory proof)
internal
pure
returns (bytes32 append_leaf)
{
append_leaf = keccak256(abi.encodePacked(bytes1(0), append_element));
return get_new_root_from_leafs_and_append_proof_single_append(append_leaf, proof);
}
// Get the updated Element Merkle Root, given append leafs and an Append Proof
function get_new_root_from_leafs_and_append_proof_multi_append(bytes32[] memory append_leafs, bytes32[] memory proof)
internal
pure
returns (bytes32)
{
uint256 leaf_count = append_leafs.length;
uint256 write_index;
uint256 read_index;
uint256 offset = uint256(proof[0]);
uint256 index = offset;
// reuse leaf_count variable as upper_bound, since leaf_count no longer needed
leaf_count += offset;
leaf_count -= 1;
uint256 proof_index = proof.length - 1;
while (leaf_count > 0) {
if ((write_index == 0) && (index & 1 == 1)) {
append_leafs[0] = hash_pair(proof[proof_index], append_leafs[read_index]);
read_index += 1;
proof_index -= 1;
write_index = 1;
index += 1;
} else if (index < leaf_count) {
append_leafs[write_index++] = hash_pair(append_leafs[read_index++], append_leafs[read_index++]);
index += 2;
}
if (index >= leaf_count) {
if (index == leaf_count) {
append_leafs[write_index] = append_leafs[read_index];
}
read_index = 0;
write_index = 0;
leaf_count >>= 1;
offset >>= 1;
index = offset;
}
}
return append_leafs[0];
}
// Get the updated Element Merkle Root, given bytes append elements in calldata and an Append Proof
function get_new_root_from_append_proof_multi_append_c(bytes[] calldata append_elements, bytes32[] memory proof)
internal
pure
returns (bytes32)
{
return get_new_root_from_leafs_and_append_proof_multi_append(get_leafs_from_elements_c(append_elements), proof);
}
// Get the updated Element Merkle Root, given bytes append elements in memory and an Append Proof
function get_new_root_from_append_proof_multi_append_m(bytes[] memory append_elements, bytes32[] memory proof)
internal
pure
returns (bytes32)
{
return get_new_root_from_leafs_and_append_proof_multi_append(get_leafs_from_elements_m(append_elements), proof);
}
// Get the updated Element Merkle Root, given bytes32 append elements in calldata and an Append Proof
function get_new_root_from_append_proof_multi_append_c(bytes32[] calldata append_elements, bytes32[] memory proof)
internal
pure
returns (bytes32)
{
return get_new_root_from_leafs_and_append_proof_multi_append(get_leafs_from_elements_c(append_elements), proof);
}
// Get the updated Element Merkle Root, given bytes32 append elements in memory and an Append Proof
function get_new_root_from_append_proof_multi_append_m(bytes32[] memory append_elements, bytes32[] memory proof)
internal
pure
returns (bytes32)
{
return get_new_root_from_leafs_and_append_proof_multi_append(get_leafs_from_elements_m(append_elements), proof);
}
// Get the original Element Merkle Root and derive Append Proof, given an index, an append leaf, and a Single Proof
function get_append_proof_from_leaf_and_single_proof(
uint256 index,
bytes32 leaf,
bytes32[] calldata proof
) internal pure returns (bytes32 append_hash, bytes32[] memory append_proof) {
uint256 proof_index = proof.length - 1;
uint256 append_node_index = uint256(proof[0]);
uint256 upper_bound = append_node_index - 1;
uint256 append_proof_index = bit_count_32(uint32(append_node_index)) + 1;
append_proof = new bytes32[](append_proof_index);
append_proof[0] = bytes32(append_node_index);
bytes32 scratch;
while (proof_index > 0) {
if (index != upper_bound || (index & 1 == 1)) {
scratch = proof[proof_index];
leaf = hash_pair(scratch, leaf);
if (append_node_index & 1 == 1) {
append_proof_index -= 1;
append_proof[append_proof_index] = scratch;
append_hash = hash_pair(scratch, append_hash);
}
proof_index -= 1;
} else if (append_node_index & 1 == 1) {
append_proof_index -= 1;
append_proof[append_proof_index] = leaf;
append_hash = leaf;
}
index >>= 1;
upper_bound >>= 1;
append_node_index >>= 1;
}
require(append_proof_index == 2 || append_hash == leaf, "INVALID_PROOF");
if (append_proof_index == 2) {
append_proof[1] = leaf;
}
}
// Get the original Element Merkle Root and derive Append Proof, given an index, a bytes element in calldata, and a Single Proof
function get_append_proof_from_single_proof(
uint256 index,
bytes calldata element,
bytes32[] calldata proof
) internal pure returns (bytes32 leaf, bytes32[] memory) {
leaf = keccak256(abi.encodePacked(bytes1(0), element));
return get_append_proof_from_leaf_and_single_proof(index, leaf, proof);
}
// Get the original Element Merkle Root and derive Append Proof, given an index, a bytes32 element, and a Single Proof
function get_append_proof_from_single_proof(
uint256 index,
bytes32 element,
bytes32[] calldata proof
) internal pure returns (bytes32 leaf, bytes32[] memory) {
leaf = keccak256(abi.encodePacked(bytes1(0), element));
return get_append_proof_from_leaf_and_single_proof(index, leaf, proof);
}
// Get the original Element Merkle Root and derive Append Proof, given an index, a leaf, an update leaf, and a Single Proof
function get_append_proof_from_leaf_and_single_proof_update(
uint256 index,
bytes32 leaf,
bytes32 update_leaf,
bytes32[] calldata proof
) internal pure returns (bytes32 append_hash, bytes32[] memory append_proof) {
uint256 proof_index = proof.length - 1;
uint256 append_node_index = uint256(proof[0]);
uint256 upper_bound = append_node_index - 1;
uint256 append_proof_index = bit_count_32(uint32(append_node_index)) + 1;
append_proof = new bytes32[](append_proof_index);
append_proof[0] = bytes32(append_node_index);
bytes32 scratch;
while (proof_index > 0) {
if (index != upper_bound || (index & 1 == 1)) {
scratch = proof[proof_index];
leaf = hash_pair(scratch, leaf);
update_leaf = hash_pair(scratch, update_leaf);
if (append_node_index & 1 == 1) {
append_proof_index -= 1;
append_proof[append_proof_index] = scratch;
append_hash = hash_pair(scratch, append_hash);
}
proof_index -= 1;
} else if (append_node_index & 1 == 1) {
append_proof_index -= 1;
append_proof[append_proof_index] = update_leaf;
append_hash = leaf;
}
index >>= 1;
upper_bound >>= 1;
append_node_index >>= 1;
}
require(append_proof_index == 2 || append_hash == leaf, "INVALID_PROOF");
if (append_proof_index == 2) {
append_proof[1] = update_leaf;
}
}
// Get the original Element Merkle Root and derive Append Proof,
// given an index, a bytes element in calldata, a bytes update element in calldata, and a Single Proof
function get_append_proof_from_single_proof_update_c(
uint256 index,
bytes calldata element,
bytes calldata update_element,
bytes32[] calldata proof
) internal pure returns (bytes32 leaf, bytes32[] memory) {
leaf = keccak256(abi.encodePacked(bytes1(0), element));
bytes32 update_leaf = keccak256(abi.encodePacked(bytes1(0), update_element));
return get_append_proof_from_leaf_and_single_proof_update(index, leaf, update_leaf, proof);
}
// Get the original Element Merkle Root and derive Append Proof,
// given an index, a bytes element in calldata, a bytes update element in memory, and a Single Proof
function get_append_proof_from_single_proof_update_m(
uint256 index,
bytes calldata element,
bytes memory update_element,
bytes32[] calldata proof
) internal pure returns (bytes32 leaf, bytes32[] memory) {
leaf = keccak256(abi.encodePacked(bytes1(0), element));
bytes32 update_leaf = keccak256(abi.encodePacked(bytes1(0), update_element));
return get_append_proof_from_leaf_and_single_proof_update(index, leaf, update_leaf, proof);
}
// Get the original Element Merkle Root and derive Append Proof,
// given an index, a bytes32 element, a bytes32 update element, and a Single Proof
function get_append_proof_from_single_proof_update(
uint256 index,
bytes32 element,
bytes32 update_element,
bytes32[] calldata proof
) internal pure returns (bytes32 leaf, bytes32[] memory) {
leaf = keccak256(abi.encodePacked(bytes1(0), element));
bytes32 update_leaf = keccak256(abi.encodePacked(bytes1(0), update_element));
return get_append_proof_from_leaf_and_single_proof_update(index, leaf, update_leaf, proof);
}
// Hashes leaf at read index and next index (circular) to write index
function hash_within_leafs(
bytes32[] memory leafs,
uint256 write_index,
uint256 read_index,
uint256 leaf_count
) internal pure {
leafs[write_index] = hash_pair(leafs[read_index], leafs[(read_index + 1) % leaf_count]);
}
// Hashes value with leaf at read index to write index
function hash_with_leafs(
bytes32[] memory leafs,
bytes32 value,
uint256 write_index,
uint256 read_index
) internal pure {
leafs[write_index] = hash_pair(value, leafs[read_index]);
}
// Get the original Element Merkle Root and derive Append Proof, given leafs and an Existence Multi Proof
function get_append_proof_from_leafs_and_multi_proof(bytes32[] memory leafs, bytes32[] calldata proof)
internal
pure
returns (bytes32 append_hash, bytes32[] memory append_proof)
{
uint256 leaf_count = leafs.length;
uint256 read_index;
uint256 write_index;
uint256 proof_index = 3;
uint256 append_node_index = uint256(proof[0]);
uint256 append_proof_index = uint256(bit_count_32(uint32(append_node_index))) + 1;
append_proof = new bytes32[](append_proof_index);
append_proof[0] = bytes32(append_node_index);
bytes32 bit_check = 0x0000000000000000000000000000000000000000000000000000000000000001;
bytes32 flags = proof[1];
bytes32 skips = proof[2];
uint256 read_index_of_append_node;
while (true) {
if (skips & bit_check == bit_check) {
if (flags & bit_check == bit_check) {
read_index = (write_index == 0 ? leaf_count : write_index) - 1;
// reuse flags as scratch variable
flags = leafs[read_index];
require(append_proof_index == 2 || append_hash == flags, "INVALID_PROOF");
if (append_proof_index == 2) {
append_proof[1] = flags;
}
return (append_hash, append_proof);
}
if (append_node_index & 1 == 1) {
append_proof_index -= 1;
append_hash = leafs[read_index]; // TODO scratch this leafs[read_index] above
append_proof[append_proof_index] = leafs[read_index];
}
read_index_of_append_node = write_index;
append_node_index >>= 1;
leafs[write_index] = leafs[read_index];
read_index = (read_index + 1) % leaf_count;
write_index = (write_index + 1) % leaf_count;
bit_check <<= 1;
continue;
}
if (read_index_of_append_node == read_index) {
if (append_node_index & 1 == 1) {
append_proof_index -= 1;
if (flags & bit_check == bit_check) {
// reuse read_index_of_append_node as temporary scratch variable
read_index_of_append_node = (read_index + 1) % leaf_count;
append_hash = hash_pair(leafs[read_index_of_append_node], append_hash);
append_proof[append_proof_index] = leafs[read_index_of_append_node];
} else {
append_hash = hash_pair(proof[proof_index], append_hash);
append_proof[append_proof_index] = proof[proof_index];
}
}
read_index_of_append_node = write_index;
append_node_index >>= 1;
}
if (flags & bit_check == bit_check) {
hash_within_leafs(leafs, write_index, read_index, leaf_count);
read_index += 2;
} else {
hash_with_leafs(leafs, proof[proof_index], write_index, read_index);
proof_index += 1;
read_index += 1;
}
read_index %= leaf_count;
write_index = (write_index + 1) % leaf_count;
bit_check <<= 1;
}
}
// Get the original Element Merkle Root and derive Append Proof, given bytes elements in calldata and an Existence Multi Proof
function get_append_proof_from_multi_proof(bytes[] calldata elements, bytes32[] calldata proof)
internal
pure
returns (bytes32, bytes32[] memory)
{
return get_append_proof_from_leafs_and_multi_proof(get_reversed_leafs_from_elements_c(elements), proof);
}
// Get the original Element Merkle Root and derive Append Proof, given bytes32 elements in calldata and an Existence Multi Proof
function get_append_proof_from_multi_proof(bytes32[] calldata elements, bytes32[] calldata proof)
internal
pure
returns (bytes32, bytes32[] memory)
{
return get_append_proof_from_leafs_and_multi_proof(get_reversed_leafs_from_elements_c(elements), proof);
}
// Get combined current and update leafs from current bytes elements in calldata and update bytes elements in calldata, in reverse order
function get_reversed_combined_leafs_from_current_and_update_elements_c(
bytes[] calldata elements,
bytes[] calldata update_elements
) internal pure returns (bytes32[] memory combined_leafs) {
uint256 element_count = elements.length;
require(update_elements.length == element_count, "LENGTH_MISMATCH");
combined_leafs = new bytes32[](element_count << 1);
uint256 read_index = element_count - 1;
uint256 write_index;
while (write_index < element_count) {
combined_leafs[write_index] = keccak256(abi.encodePacked(bytes1(0), elements[read_index]));
combined_leafs[element_count + write_index] = keccak256(abi.encodePacked(bytes1(0), update_elements[read_index]));
write_index += 1;
read_index -= 1;
}
}
// Get combined current and update leafs from current bytes elements in calldata and update bytes elements in memory, in reverse order
function get_reversed_combined_leafs_from_current_and_update_elements_m(
bytes[] calldata elements,
bytes[] memory update_elements
) internal pure returns (bytes32[] memory combined_leafs) {
uint256 element_count = elements.length;
require(update_elements.length == element_count, "LENGTH_MISMATCH");
combined_leafs = new bytes32[](element_count << 1);
uint256 read_index = element_count - 1;
uint256 write_index;
while (write_index < element_count) {
combined_leafs[write_index] = keccak256(abi.encodePacked(bytes1(0), elements[read_index]));
combined_leafs[element_count + write_index] = keccak256(abi.encodePacked(bytes1(0), update_elements[read_index]));
write_index += 1;
read_index -= 1;
}
}
// Get combined current and update leafs from current bytes32 elements in calldata and update bytes32 elements in calldata, in reverse order
function get_reversed_combined_leafs_from_current_and_update_elements_c(
bytes32[] calldata elements,
bytes32[] calldata update_elements
) internal pure returns (bytes32[] memory combined_leafs) {
uint256 element_count = elements.length;
require(update_elements.length == element_count, "LENGTH_MISMATCH");
combined_leafs = new bytes32[](element_count << 1);
uint256 read_index = element_count - 1;
uint256 write_index;
while (write_index < element_count) {
combined_leafs[write_index] = keccak256(abi.encodePacked(bytes1(0), elements[read_index]));
combined_leafs[element_count + write_index] = keccak256(abi.encodePacked(bytes1(0), update_elements[read_index]));
write_index += 1;
read_index -= 1;
}
}
// Get combined current and update leafs from current bytes32 elements in calldata and update bytes32 elements in memory, in reverse order
function get_reversed_combined_leafs_from_current_and_update_elements_m(
bytes32[] calldata elements,
bytes32[] memory update_elements
) internal pure returns (bytes32[] memory combined_leafs) {
uint256 element_count = elements.length;
require(update_elements.length == element_count, "LENGTH_MISMATCH");
combined_leafs = new bytes32[](element_count << 1);
uint256 read_index = element_count - 1;
uint256 write_index;
while (write_index < element_count) {
combined_leafs[write_index] = keccak256(abi.encodePacked(bytes1(0), elements[read_index]));
combined_leafs[element_count + write_index] = keccak256(abi.encodePacked(bytes1(0), update_elements[read_index]));
write_index += 1;
read_index -= 1;
}
}
// Copy leaf and update leaf at read indices and to write indices
function copy_within_combined_leafs(
bytes32[] memory combined_leafs,
uint256 write_index,
uint256 read_index,
uint256 leaf_count
) internal pure {
combined_leafs[write_index] = combined_leafs[read_index];
combined_leafs[leaf_count + write_index] = combined_leafs[leaf_count + read_index];
}
// Hashes leaf and update leaf at read indices and next indices (circular) to write indices
function hash_within_combined_leafs(
bytes32[] memory combined_leafs,
uint256 write_index,
uint256 read_index,
uint256 leaf_count
) internal pure {
uint256 scratch = (read_index + 1) % leaf_count;
combined_leafs[write_index] = hash_pair(combined_leafs[read_index], combined_leafs[scratch]);
combined_leafs[leaf_count + write_index] = hash_pair(
combined_leafs[leaf_count + read_index],
combined_leafs[leaf_count + scratch]
);
}
// Hashes value with leaf and update leaf at read indices to write indices
function hash_with_combined_leafs(
bytes32[] memory combined_leafs,
bytes32 value,
uint256 write_index,
uint256 read_index,
uint256 leaf_count
) internal pure {
combined_leafs[write_index] = hash_pair(value, combined_leafs[read_index]);
combined_leafs[leaf_count + write_index] = hash_pair(value, combined_leafs[leaf_count + read_index]);
}
// Get the original Element Merkle Root and derive Append Proof, given combined leafs and update leafs and an Existence Multi Proof
function get_append_proof_from_leafs_and_multi_proof_update(bytes32[] memory combined_leafs, bytes32[] calldata proof)
internal
pure
returns (bytes32 append_hash, bytes32[] memory append_proof)
{
uint256 leaf_count = combined_leafs.length >> 1;
uint256 read_index;
uint256 write_index;
uint256 read_index_of_append_node;
uint256 proof_index = 3;
uint256 append_node_index = uint256(proof[0]);
uint256 append_proof_index = bit_count_32(uint32(append_node_index)) + 1;
append_proof = new bytes32[](append_proof_index);
append_proof[0] = bytes32(append_node_index);
bytes32 flags = proof[1];
bytes32 skips = proof[2];
bytes32 bit_check = 0x0000000000000000000000000000000000000000000000000000000000000001;
while (true) {
if (skips & bit_check == bit_check) {
if (flags & bit_check == bit_check) {
read_index = (write_index == 0 ? leaf_count : write_index) - 1;
// reuse flags as scratch variable
flags = combined_leafs[read_index];
require(append_proof_index == 2 || append_hash == flags, "INVALID_PROOF");
if (append_proof_index == 2) {
append_proof[1] = combined_leafs[leaf_count + read_index];
}
return (flags, append_proof);
}
if (append_node_index & 1 == 1) {
append_proof_index -= 1;
append_hash = combined_leafs[read_index];
append_proof[append_proof_index] = combined_leafs[leaf_count + read_index];
}
read_index_of_append_node = write_index;
append_node_index >>= 1;
combined_leafs[write_index] = combined_leafs[read_index];
combined_leafs[leaf_count + write_index] = combined_leafs[leaf_count + read_index];
read_index = (read_index + 1) % leaf_count;
write_index = (write_index + 1) % leaf_count;
bit_check <<= 1;
continue;
}
if (read_index_of_append_node == read_index) {
if (append_node_index & 1 == 1) {
append_proof_index -= 1;
if (flags & bit_check == bit_check) {
// use read_index_of_append_node as temporary scratch
read_index_of_append_node = (read_index + 1) % leaf_count;
append_hash = hash_pair(combined_leafs[read_index_of_append_node], append_hash);
append_proof[append_proof_index] = combined_leafs[leaf_count + read_index_of_append_node];
} else {
append_hash = hash_pair(proof[proof_index], append_hash);
append_proof[append_proof_index] = proof[proof_index];
}
}
read_index_of_append_node = write_index;
append_node_index >>= 1;
}
if (flags & bit_check == bit_check) {
hash_within_combined_leafs(combined_leafs, write_index, read_index, leaf_count);
read_index += 2;
} else {
hash_with_combined_leafs(combined_leafs, proof[proof_index], write_index, read_index, leaf_count);
proof_index += 1;
read_index += 1;
}
read_index %= leaf_count;
write_index = (write_index + 1) % leaf_count;
bit_check <<= 1;
}
}
// Get the original Element Merkle Root and derive Append Proof,
// given bytes elements in calldata, bytes update elements in calldata, and an Existence Multi Proof
function get_append_proof_from_multi_proof_update_c(
bytes[] calldata elements,
bytes[] calldata update_elements,
bytes32[] calldata proof
) internal pure returns (bytes32, bytes32[] memory) {
return
get_append_proof_from_leafs_and_multi_proof_update(
get_reversed_combined_leafs_from_current_and_update_elements_c(elements, update_elements),
proof
);
}
// Get the original Element Merkle Root and derive Append Proof,
// given bytes elements in calldata, bytes update elements in memory, and an Existence Multi Proof
function get_append_proof_from_multi_proof_update_m(
bytes[] calldata elements,
bytes[] memory update_elements,
bytes32[] calldata proof
) internal pure returns (bytes32, bytes32[] memory) {
return
get_append_proof_from_leafs_and_multi_proof_update(
get_reversed_combined_leafs_from_current_and_update_elements_m(elements, update_elements),
proof
);
}
// Get the original Element Merkle Root and derive Append Proof,
// given bytes32 elements in calldata, bytes32 update elements in calldata, and an Existence Multi Proof
function get_append_proof_from_multi_proof_update_c(
bytes32[] calldata elements,
bytes32[] calldata update_elements,
bytes32[] calldata proof
) internal pure returns (bytes32, bytes32[] memory) {
return
get_append_proof_from_leafs_and_multi_proof_update(
get_reversed_combined_leafs_from_current_and_update_elements_c(elements, update_elements),
proof
);
}
// Get the original Element Merkle Root and derive Append Proof,
// given bytes32 elements in calldata, bytes32 update elements in memory, and an Existence Multi Proof
function get_append_proof_from_multi_proof_update_m(
bytes32[] calldata elements,
bytes32[] memory update_elements,
bytes32[] calldata proof
) internal pure returns (bytes32, bytes32[] memory) {
return
get_append_proof_from_leafs_and_multi_proof_update(
get_reversed_combined_leafs_from_current_and_update_elements_m(elements, update_elements),
proof
);
}
// INTERFACE: Check if bytes element in calldata exists at index, given a root and a Single Proof
function element_exists_c(
bytes32 root,
uint256 index,
bytes calldata element,
bytes32[] calldata proof
) internal pure returns (bool) {
return hash_node(proof[0], get_root_from_single_proof_c(index, element, proof)) == root;
}
// INTERFACE: Check if bytes element in calldata exists at index, given a root and a Single Proof
function element_exists_m(
bytes32 root,
uint256 index,
bytes memory element,
bytes32[] calldata proof
) internal pure returns (bool) {
return hash_node(proof[0], get_root_from_single_proof_m(index, element, proof)) == root;
}
// INTERFACE: Check if bytes32 element exists at index, given a root and a Single Proof
function element_exists(
bytes32 root,
uint256 index,
bytes32 element,
bytes32[] calldata proof
) internal pure returns (bool) {
return hash_node(proof[0], get_root_from_single_proof(index, element, proof)) == root;
}
// INTERFACE: Check if bytes elements in calldata exist, given a root and a Single Proof
function elements_exist_c(
bytes32 root,
bytes[] calldata elements,
bytes32[] calldata proof
) internal pure returns (bool) {
return hash_node(proof[0], get_root_from_multi_proof_c(elements, proof)) == root;
}
// INTERFACE: Check if bytes elements in memory exist, given a root and a Single Proof
function elements_exist_m(
bytes32 root,
bytes[] memory elements,
bytes32[] calldata proof
) internal pure returns (bool) {
return hash_node(proof[0], get_root_from_multi_proof_m(elements, proof)) == root;
}
// INTERFACE: Check if bytes32 elements in calldata exist, given a root and a Single Proof
function elements_exist_c(
bytes32 root,
bytes32[] calldata elements,
bytes32[] calldata proof
) internal pure returns (bool) {
return hash_node(proof[0], get_root_from_multi_proof_c(elements, proof)) == root;
}
// INTERFACE: Check if bytes32 elements in memory exist, given a root and a Single Proof
function elements_exist_m(
bytes32 root,
bytes32[] memory elements,
bytes32[] calldata proof
) internal pure returns (bool) {
return hash_node(proof[0], get_root_from_multi_proof_m(elements, proof)) == root;
}
// get_indices cannot be implemented with sorted hashed pairs
// verify_size_with_proof cannot be implemented with sorted hashed pairs
// INTERFACE: Check tree size, given a the Element Merkle Root
function verify_size(
bytes32 root,
uint256 size,
bytes32 element_root
) internal pure returns (bool) {
if (root == bytes32(0) && size == 0) return true;
return hash_node(bytes32(size), element_root) == root;
}
// INTERFACE: Try to update a bytes element in calldata, given a root, and index, an bytes element in calldata, and a Single Proof
function try_update_one_c(
bytes32 root,
uint256 index,
bytes calldata element,
bytes calldata update_element,
bytes32[] calldata proof
) internal pure returns (bytes32 new_element_root) {
bytes32 total_element_count = proof[0];
require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE");
bytes32 old_element_root;
(old_element_root, new_element_root) = get_roots_from_single_proof_update_c(index, element, update_element, proof);
require(hash_node(total_element_count, old_element_root) == root, "INVALID_PROOF");
return hash_node(total_element_count, new_element_root);
}
// INTERFACE: Try to update a bytes element in memory, given a root, and index, an bytes element in calldata, and a Single Proof
function try_update_one_m(
bytes32 root,
uint256 index,
bytes calldata element,
bytes memory update_element,
bytes32[] calldata proof
) internal pure returns (bytes32 new_element_root) {
bytes32 total_element_count = proof[0];
require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE");
bytes32 old_element_root;
(old_element_root, new_element_root) = get_roots_from_single_proof_update_m(index, element, update_element, proof);
require(hash_node(total_element_count, old_element_root) == root, "INVALID_PROOF");
return hash_node(total_element_count, new_element_root);
}
// INTERFACE: Try to update a bytes32 element, given a root, and index, an bytes32 element, and a Single Proof
function try_update_one(
bytes32 root,
uint256 index,
bytes32 element,
bytes32 update_element,
bytes32[] calldata proof
) internal pure returns (bytes32 new_element_root) {
bytes32 total_element_count = proof[0];
require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE");
bytes32 old_element_root;
(old_element_root, new_element_root) = get_roots_from_single_proof_update(index, element, update_element, proof);
require(hash_node(total_element_count, old_element_root) == root, "INVALID_PROOF");
return hash_node(total_element_count, new_element_root);
}
// INTERFACE: Try to update bytes elements in calldata, given a root, bytes elements in calldata, and an Existence Multi Proof
function try_update_many_c(
bytes32 root,
bytes[] calldata elements,
bytes[] calldata update_elements,
bytes32[] calldata proof
) internal pure returns (bytes32 new_element_root) {
bytes32 total_element_count = proof[0];
require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE");
bytes32 old_element_root;
(old_element_root, new_element_root) = get_roots_from_multi_proof_update_c(elements, update_elements, proof);
require(hash_node(total_element_count, old_element_root) == root, "INVALID_PROOF");
return hash_node(total_element_count, new_element_root);
}
// INTERFACE: Try to update bytes elements in calldata, given a root, bytes elements in calldata, and an Existence Multi Proof
function try_update_many_m(
bytes32 root,
bytes[] calldata elements,
bytes[] memory update_elements,
bytes32[] calldata proof
) internal pure returns (bytes32 new_element_root) {
bytes32 total_element_count = proof[0];
require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE");
bytes32 old_element_root;
(old_element_root, new_element_root) = get_roots_from_multi_proof_update_m(elements, update_elements, proof);
require(hash_node(total_element_count, old_element_root) == root, "INVALID_PROOF");
return hash_node(total_element_count, new_element_root);
}
// INTERFACE: Try to update bytes32 elements in calldata, given a root, bytes32 elements in calldata, and an Existence Multi Proof
function try_update_many_c(
bytes32 root,
bytes32[] calldata elements,
bytes32[] calldata update_elements,
bytes32[] calldata proof
) internal pure returns (bytes32 new_element_root) {
bytes32 total_element_count = proof[0];
require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE");
bytes32 old_element_root;
(old_element_root, new_element_root) = get_roots_from_multi_proof_update_c(elements, update_elements, proof);
require(hash_node(total_element_count, old_element_root) == root, "INVALID_PROOF");
return hash_node(total_element_count, new_element_root);
}
// INTERFACE: Try to update bytes32 elements in calldata, given a root, bytes32 elements in calldata, and an Existence Multi Proof
function try_update_many_m(
bytes32 root,
bytes32[] calldata elements,
bytes32[] memory update_elements,
bytes32[] calldata proof
) internal pure returns (bytes32 new_element_root) {
bytes32 total_element_count = proof[0];
require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE");
bytes32 old_element_root;
(old_element_root, new_element_root) = get_roots_from_multi_proof_update_m(elements, update_elements, proof);
require(hash_node(total_element_count, old_element_root) == root, "INVALID_PROOF");
return hash_node(total_element_count, new_element_root);
}
// INTERFACE: Try to append a bytes element in calldata, given a root and an Append Proof
function try_append_one_c(
bytes32 root,
bytes calldata append_element,
bytes32[] calldata proof
) internal pure returns (bytes32 new_element_root) {
bytes32 total_element_count = proof[0];
require((root == bytes32(0)) == (total_element_count == bytes32(0)), "INVALID_TREE");
if (root == bytes32(0)) return hash_node(bytes32(uint256(1)), get_root_from_one_c(append_element));
bytes32 old_element_root;
(old_element_root, new_element_root) = get_roots_from_append_proof_single_append_c(append_element, proof);
require(hash_node(total_element_count, old_element_root) == root, "INVALID_PROOF");
return hash_node(bytes32(uint256(total_element_count) + 1), new_element_root);
}
// INTERFACE: Try to append a bytes element in memory, given a root and an Append Proof
function try_append_one_m(
bytes32 root,
bytes memory append_element,
bytes32[] calldata proof
) internal pure returns (bytes32 new_element_root) {
bytes32 total_element_count = proof[0];
require((root == bytes32(0)) == (total_element_count == bytes32(0)), "INVALID_TREE");
if (root == bytes32(0)) return hash_node(bytes32(uint256(1)), get_root_from_one_m(append_element));
bytes32 old_element_root;
(old_element_root, new_element_root) = get_roots_from_append_proof_single_append_m(append_element, proof);
require(hash_node(total_element_count, old_element_root) == root, "INVALID_PROOF");
return hash_node(bytes32(uint256(total_element_count) + 1), new_element_root);
}
// INTERFACE: Try to append a bytes32 element, given a root and an Append Proof
function try_append_one(
bytes32 root,
bytes32 append_element,
bytes32[] calldata proof
) internal pure returns (bytes32 new_element_root) {
bytes32 total_element_count = proof[0];
require((root == bytes32(0)) == (total_element_count == bytes32(0)), "INVALID_TREE");
if (root == bytes32(0)) return hash_node(bytes32(uint256(1)), get_root_from_one(append_element));
bytes32 old_element_root;
(old_element_root, new_element_root) = get_roots_from_append_proof_single_append(append_element, proof);
require(hash_node(total_element_count, old_element_root) == root, "INVALID_PROOF");
return hash_node(bytes32(uint256(total_element_count) + 1), new_element_root);
}
// INTERFACE: Try to append bytes elements in calldata, given a root and an Append Proof
function try_append_many_c(
bytes32 root,
bytes[] calldata append_elements,
bytes32[] calldata proof
) internal pure returns (bytes32 new_element_root) {
bytes32 total_element_count = proof[0];
require((root == bytes32(0)) == (total_element_count == bytes32(0)), "INVALID_TREE");
if (root == bytes32(0)) return hash_node(bytes32(append_elements.length), get_root_from_many_c(append_elements));
bytes32 old_element_root;
(old_element_root, new_element_root) = get_roots_from_append_proof_multi_append_c(append_elements, proof);
require(hash_node(total_element_count, old_element_root) == root, "INVALID_PROOF");
return hash_node(bytes32(uint256(total_element_count) + append_elements.length), new_element_root);
}
// INTERFACE: Try to append bytes elements in memory, given a root and an Append Proof
function try_append_many_m(
bytes32 root,
bytes[] memory append_elements,
bytes32[] calldata proof
) internal pure returns (bytes32 new_element_root) {
bytes32 total_element_count = proof[0];
require((root == bytes32(0)) == (total_element_count == bytes32(0)), "INVALID_TREE");
if (root == bytes32(0)) return hash_node(bytes32(append_elements.length), get_root_from_many_m(append_elements));
bytes32 old_element_root;
(old_element_root, new_element_root) = get_roots_from_append_proof_multi_append_m(append_elements, proof);
require(hash_node(total_element_count, old_element_root) == root, "INVALID_PROOF");
return hash_node(bytes32(uint256(total_element_count) + append_elements.length), new_element_root);
}
// INTERFACE: Try to append bytes32 elements in calldata, given a root and an Append Proof
function try_append_many_c(
bytes32 root,
bytes32[] calldata append_elements,
bytes32[] calldata proof
) internal pure returns (bytes32 new_element_root) {
bytes32 total_element_count = proof[0];
require((root == bytes32(0)) == (total_element_count == bytes32(0)), "INVALID_TREE");
if (root == bytes32(0)) return hash_node(bytes32(append_elements.length), get_root_from_many_c(append_elements));
bytes32 old_element_root;
(old_element_root, new_element_root) = get_roots_from_append_proof_multi_append_c(append_elements, proof);
require(hash_node(total_element_count, old_element_root) == root, "INVALID_PROOF");
return hash_node(bytes32(uint256(total_element_count) + append_elements.length), new_element_root);
}
// INTERFACE: Try to append bytes32 elements in memory, given a root and an Append Proof
function try_append_many_m(
bytes32 root,
bytes32[] memory append_elements,
bytes32[] calldata proof
) internal pure returns (bytes32 new_element_root) {
bytes32 total_element_count = proof[0];
require((root == bytes32(0)) == (total_element_count == bytes32(0)), "INVALID_TREE");
if (root == bytes32(0)) return hash_node(bytes32(append_elements.length), get_root_from_many_m(append_elements));
bytes32 old_element_root;
(old_element_root, new_element_root) = get_roots_from_append_proof_multi_append_m(append_elements, proof);
require(hash_node(total_element_count, old_element_root) == root, "INVALID_PROOF");
return hash_node(bytes32(uint256(total_element_count) + append_elements.length), new_element_root);
}
// INTERFACE: Try to append a bytes element in calldata, given a root, an index, a bytes element in calldata, and a Single Proof
function try_append_one_using_one_c(
bytes32 root,
uint256 index,
bytes calldata element,
bytes calldata append_element,
bytes32[] calldata proof
) internal pure returns (bytes32 element_root) {
bytes32 total_element_count = proof[0];
require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE");
bytes32[] memory append_proof;
(element_root, append_proof) = get_append_proof_from_single_proof(index, element, proof);
require(hash_node(total_element_count, element_root) == root, "INVALID_PROOF");
element_root = get_new_root_from_append_proof_single_append_c(append_element, append_proof);
return hash_node(bytes32(uint256(total_element_count) + 1), element_root);
}
// INTERFACE: Try to append a bytes element in memory, given a root, an index, a bytes element in calldata, and a Single Proof
function try_append_one_using_one_m(
bytes32 root,
uint256 index,
bytes calldata element,
bytes memory append_element,
bytes32[] calldata proof
) internal pure returns (bytes32 element_root) {
bytes32 total_element_count = proof[0];
require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE");
bytes32[] memory append_proof;
(element_root, append_proof) = get_append_proof_from_single_proof(index, element, proof);
require(hash_node(total_element_count, element_root) == root, "INVALID_PROOF");
element_root = get_new_root_from_append_proof_single_append_m(append_element, append_proof);
return hash_node(bytes32(uint256(total_element_count) + 1), element_root);
}
// INTERFACE: Try to append a bytes32 element, given a root, an index, a bytes32 element, and a Single Proof
function try_append_one_using_one(
bytes32 root,
uint256 index,
bytes32 element,
bytes32 append_element,
bytes32[] calldata proof
) internal pure returns (bytes32 element_root) {
bytes32 total_element_count = proof[0];
require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE");
bytes32[] memory append_proof;
(element_root, append_proof) = get_append_proof_from_single_proof(index, element, proof);
require(hash_node(total_element_count, element_root) == root, "INVALID_PROOF");
element_root = get_new_root_from_append_proof_single_append(append_element, append_proof);
return hash_node(bytes32(uint256(total_element_count) + 1), element_root);
}
// INTERFACE: Try to append bytes elements in calldata, given a root, an index, a bytes element in calldata, and a Single Proof
function try_append_many_using_one_c(
bytes32 root,
uint256 index,
bytes calldata element,
bytes[] calldata append_elements,
bytes32[] calldata proof
) internal pure returns (bytes32 element_root) {
bytes32 total_element_count = proof[0];
require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE");
bytes32[] memory append_proof;
(element_root, append_proof) = get_append_proof_from_single_proof(index, element, proof);
require(hash_node(total_element_count, element_root) == root, "INVALID_PROOF");
element_root = get_new_root_from_append_proof_multi_append_c(append_elements, append_proof);
return hash_node(bytes32(uint256(total_element_count) + append_elements.length), element_root);
}
// INTERFACE: Try to append bytes elements in memory, given a root, an index, a bytes element in calldata, and a Single Proof
function try_append_many_using_one_m(
bytes32 root,
uint256 index,
bytes calldata element,
bytes[] memory append_elements,
bytes32[] calldata proof
) internal pure returns (bytes32 element_root) {
bytes32 total_element_count = proof[0];
require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE");
bytes32[] memory append_proof;
(element_root, append_proof) = get_append_proof_from_single_proof(index, element, proof);
require(hash_node(total_element_count, element_root) == root, "INVALID_PROOF");
element_root = get_new_root_from_append_proof_multi_append_m(append_elements, append_proof);
return hash_node(bytes32(uint256(total_element_count) + append_elements.length), element_root);
}
// INTERFACE: Try to append bytes32 elements in calldata, given a root, an index, a bytes32 element, and a Single Proof
function try_append_many_using_one_c(
bytes32 root,
uint256 index,
bytes32 element,
bytes32[] calldata append_elements,
bytes32[] calldata proof
) internal pure returns (bytes32 element_root) {
bytes32 total_element_count = proof[0];
require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE");
bytes32[] memory append_proof;
(element_root, append_proof) = get_append_proof_from_single_proof(index, element, proof);
require(hash_node(total_element_count, element_root) == root, "INVALID_PROOF");
element_root = get_new_root_from_append_proof_multi_append_c(append_elements, append_proof);
return hash_node(bytes32(uint256(total_element_count) + append_elements.length), element_root);
}
// INTERFACE: Try to append bytes32 elements in memory, given a root, an index, a bytes32 element, and a Single Proof
function try_append_many_using_one_m(
bytes32 root,
uint256 index,
bytes32 element,
bytes32[] memory append_elements,
bytes32[] calldata proof
) internal pure returns (bytes32 element_root) {
bytes32 total_element_count = proof[0];
require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE");
bytes32[] memory append_proof;
(element_root, append_proof) = get_append_proof_from_single_proof(index, element, proof);
require(hash_node(total_element_count, element_root) == root, "INVALID_PROOF");
element_root = get_new_root_from_append_proof_multi_append_m(append_elements, append_proof);
return hash_node(bytes32(uint256(total_element_count) + append_elements.length), element_root);
}
// INTERFACE: Try to append a bytes element in calldata, given a root, bytes elements in calldata, and an Existence Multi Proof
function try_append_one_using_many_c(
bytes32 root,
bytes[] calldata elements,
bytes calldata append_element,
bytes32[] calldata proof
) internal pure returns (bytes32 element_root) {
bytes32 total_element_count = proof[0];
require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE");
bytes32[] memory append_proof;
(element_root, append_proof) = get_append_proof_from_multi_proof(elements, proof);
require(hash_node(total_element_count, element_root) == root, "INVALID_PROOF");
element_root = get_new_root_from_append_proof_single_append_c(append_element, append_proof);
return hash_node(bytes32(uint256(total_element_count) + 1), element_root);
}
// INTERFACE: Try to append a bytes element in memory, given a root, bytes elements in calldata, and an Existence Multi Proof
function try_append_one_using_many_m(
bytes32 root,
bytes[] calldata elements,
bytes memory append_element,
bytes32[] calldata proof
) internal pure returns (bytes32 element_root) {
bytes32 total_element_count = proof[0];
require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE");
bytes32[] memory append_proof;
(element_root, append_proof) = get_append_proof_from_multi_proof(elements, proof);
require(hash_node(total_element_count, element_root) == root, "INVALID_PROOF");
element_root = get_new_root_from_append_proof_single_append_m(append_element, append_proof);
return hash_node(bytes32(uint256(total_element_count) + 1), element_root);
}
// INTERFACE: Try to append a bytes32 element, given a root, bytes32 elements in calldata, and an Existence Multi Proof
function try_append_one_using_many(
bytes32 root,
bytes32[] calldata elements,
bytes32 append_element,
bytes32[] calldata proof
) internal pure returns (bytes32 element_root) {
bytes32 total_element_count = proof[0];
require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE");
bytes32[] memory append_proof;
(element_root, append_proof) = get_append_proof_from_multi_proof(elements, proof);
require(hash_node(total_element_count, element_root) == root, "INVALID_PROOF");
element_root = get_new_root_from_append_proof_single_append(append_element, append_proof);
return hash_node(bytes32(uint256(total_element_count) + 1), element_root);
}
// INTERFACE: Try to append bytes elements in calldata, given a root, bytes elements in calldata, and an Existence Multi Proof
function try_append_many_using_many_c(
bytes32 root,
bytes[] calldata elements,
bytes[] calldata append_elements,
bytes32[] calldata proof
) internal pure returns (bytes32 element_root) {
bytes32 total_element_count = proof[0];
require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE");
bytes32[] memory append_proof;
(element_root, append_proof) = get_append_proof_from_multi_proof(elements, proof);
require(hash_node(total_element_count, element_root) == root, "INVALID_PROOF");
element_root = get_new_root_from_append_proof_multi_append_c(append_elements, append_proof);
return hash_node(bytes32(uint256(total_element_count) + append_elements.length), element_root);
}
// INTERFACE: Try to append bytes elements in memory, given a root, bytes elements in calldata, and an Existence Multi Proof
function try_append_many_using_many_m(
bytes32 root,
bytes[] calldata elements,
bytes[] memory append_elements,
bytes32[] calldata proof
) internal pure returns (bytes32 element_root) {
bytes32 total_element_count = proof[0];
require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE");
bytes32[] memory append_proof;
(element_root, append_proof) = get_append_proof_from_multi_proof(elements, proof);
require(hash_node(total_element_count, element_root) == root, "INVALID_PROOF");
element_root = get_new_root_from_append_proof_multi_append_m(append_elements, append_proof);
return hash_node(bytes32(uint256(total_element_count) + append_elements.length), element_root);
}
// INTERFACE: Try to append bytes32 elements in calldata, given a root, bytes32 elements in calldata, and an Existence Multi Proof
function try_append_many_using_many_c(
bytes32 root,
bytes32[] calldata elements,
bytes32[] calldata append_elements,
bytes32[] calldata proof
) internal pure returns (bytes32 element_root) {
bytes32 total_element_count = proof[0];
require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE");
bytes32[] memory append_proof;
(element_root, append_proof) = get_append_proof_from_multi_proof(elements, proof);
require(hash_node(total_element_count, element_root) == root, "INVALID_PROOF");
element_root = get_new_root_from_append_proof_multi_append_c(append_elements, append_proof);
return hash_node(bytes32(uint256(total_element_count) + append_elements.length), element_root);
}
// INTERFACE: Try to append bytes32 elements in memory, given a root, bytes32 elements in calldata, and an Existence Multi Proof
function try_append_many_using_many_m(
bytes32 root,
bytes32[] calldata elements,
bytes32[] memory append_elements,
bytes32[] calldata proof
) internal pure returns (bytes32 element_root) {
bytes32 total_element_count = proof[0];
require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE");
bytes32[] memory append_proof;
(element_root, append_proof) = get_append_proof_from_multi_proof(elements, proof);
require(hash_node(total_element_count, element_root) == root, "INVALID_PROOF");
element_root = get_new_root_from_append_proof_multi_append_m(append_elements, append_proof);
return hash_node(bytes32(uint256(total_element_count) + append_elements.length), element_root);
}
// INTERFACE: Try to update a bytes element in calldata and append a bytes element in calldata,
// given a root, an index, a bytes element in calldata, and a Single Proof
function try_update_one_and_append_one_c(
bytes32 root,
uint256 index,
bytes calldata element,
bytes calldata update_element,
bytes calldata append_element,
bytes32[] calldata proof
) internal pure returns (bytes32 element_root) {
bytes32 total_element_count = proof[0];
require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE");
bytes32[] memory append_proof;
(element_root, append_proof) = get_append_proof_from_single_proof_update_c(index, element, update_element, proof);
require(hash_node(total_element_count, element_root) == root, "INVALID_PROOF");
element_root = get_new_root_from_append_proof_single_append_c(append_element, append_proof);
return hash_node(bytes32(uint256(total_element_count) + 1), element_root);
}
// INTERFACE: Try to update a bytes element in memory and append a bytes element in memory,
// given a root, an index, a bytes element in calldata, and a Single Proof
function try_update_one_and_append_one_m(
bytes32 root,
uint256 index,
bytes calldata element,
bytes memory update_element,
bytes memory append_element,
bytes32[] calldata proof
) internal pure returns (bytes32 element_root) {
bytes32 total_element_count = proof[0];
require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE");
bytes32[] memory append_proof;
(element_root, append_proof) = get_append_proof_from_single_proof_update_m(index, element, update_element, proof);
require(hash_node(total_element_count, element_root) == root, "INVALID_PROOF");
element_root = get_new_root_from_append_proof_single_append_m(append_element, append_proof);
return hash_node(bytes32(uint256(total_element_count) + 1), element_root);
}
// INTERFACE: Try to update a bytes32 element and append a bytes32 element,
// given a root, an index, a bytes32 element, and a Single Proof
function try_update_one_and_append_one(
bytes32 root,
uint256 index,
bytes32 element,
bytes32 update_element,
bytes32 append_element,
bytes32[] calldata proof
) internal pure returns (bytes32 element_root) {
bytes32 total_element_count = proof[0];
require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE");
bytes32[] memory append_proof;
(element_root, append_proof) = get_append_proof_from_single_proof_update(index, element, update_element, proof);
require(hash_node(total_element_count, element_root) == root, "INVALID_PROOF");
element_root = get_new_root_from_append_proof_single_append(append_element, append_proof);
return hash_node(bytes32(uint256(total_element_count) + 1), element_root);
}
// INTERFACE: Try to update a bytes element in calldata and append bytes elements in calldata,
// given a root, an index, a bytes element in calldata, and a Single Proof
function try_update_one_and_append_many_c(
bytes32 root,
uint256 index,
bytes calldata element,
bytes calldata update_element,
bytes[] calldata append_elements,
bytes32[] calldata proof
) internal pure returns (bytes32 element_root) {
bytes32 total_element_count = proof[0];
require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE");
bytes32[] memory append_proof;
(element_root, append_proof) = get_append_proof_from_single_proof_update_c(index, element, update_element, proof);
require(hash_node(total_element_count, element_root) == root, "INVALID_PROOF");
element_root = get_new_root_from_append_proof_multi_append_c(append_elements, append_proof);
return hash_node(bytes32(uint256(total_element_count) + append_elements.length), element_root);
}
// INTERFACE: Try to update a bytes element in memory and append bytes elements in memory,
// given a root, an index, a bytes element in calldata, and a Single Proof
function try_update_one_and_append_many_m(
bytes32 root,
uint256 index,
bytes calldata element,
bytes memory update_element,
bytes[] memory append_elements,
bytes32[] calldata proof
) internal pure returns (bytes32 element_root) {
bytes32 total_element_count = proof[0];
require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE");
bytes32[] memory append_proof;
(element_root, append_proof) = get_append_proof_from_single_proof_update_m(index, element, update_element, proof);
require(hash_node(total_element_count, element_root) == root, "INVALID_PROOF");
element_root = get_new_root_from_append_proof_multi_append_m(append_elements, append_proof);
return hash_node(bytes32(uint256(total_element_count) + append_elements.length), element_root);
}
// INTERFACE: Try to update a bytes32 element and append bytes32 elements in calldata,
// given a root, an index, a bytes32 element, and a Single Proof
function try_update_one_and_append_many_c(
bytes32 root,
uint256 index,
bytes32 element,
bytes32 update_element,
bytes32[] calldata append_elements,
bytes32[] calldata proof
) internal pure returns (bytes32 element_root) {
bytes32 total_element_count = proof[0];
require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE");
bytes32[] memory append_proof;
(element_root, append_proof) = get_append_proof_from_single_proof_update(index, element, update_element, proof);
require(hash_node(total_element_count, element_root) == root, "INVALID_PROOF");
element_root = get_new_root_from_append_proof_multi_append_c(append_elements, append_proof);
return hash_node(bytes32(uint256(total_element_count) + append_elements.length), element_root);
}
// INTERFACE: Try to update a bytes32 element and append bytes32 elements in memory,
// given a root, an index, a bytes32 element, and a Single Proof
function try_update_one_and_append_many_m(
bytes32 root,
uint256 index,
bytes32 element,
bytes32 update_element,
bytes32[] memory append_elements,
bytes32[] calldata proof
) internal pure returns (bytes32 element_root) {
bytes32 total_element_count = proof[0];
require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE");
bytes32[] memory append_proof;
(element_root, append_proof) = get_append_proof_from_single_proof_update(index, element, update_element, proof);
require(hash_node(total_element_count, element_root) == root, "INVALID_PROOF");
element_root = get_new_root_from_append_proof_multi_append_m(append_elements, append_proof);
return hash_node(bytes32(uint256(total_element_count) + append_elements.length), element_root);
}
// INTERFACE: Try to update bytes elements in calldata and append a bytes element in calldata,
// given a root, bytes elements in calldata, and a Single Proof
function try_update_many_and_append_one_c(
bytes32 root,
bytes[] calldata elements,
bytes[] calldata update_elements,
bytes calldata append_element,
bytes32[] calldata proof
) internal pure returns (bytes32 element_root) {
bytes32 total_element_count = proof[0];
require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE");
bytes32[] memory append_proof;
(element_root, append_proof) = get_append_proof_from_multi_proof_update_c(elements, update_elements, proof);
require(hash_node(total_element_count, element_root) == root, "INVALID_PROOF");
element_root = get_new_root_from_append_proof_single_append_c(append_element, append_proof);
return hash_node(bytes32(uint256(total_element_count) + 1), element_root);
}
// INTERFACE: Try to update bytes elements in memory and append a bytes element in memory,
// given a root, bytes elements in calldata, and a Single Proof
function try_update_many_and_append_one_m(
bytes32 root,
bytes[] calldata elements,
bytes[] memory update_elements,
bytes memory append_element,
bytes32[] calldata proof
) internal pure returns (bytes32 element_root) {
bytes32 total_element_count = proof[0];
require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE");
bytes32[] memory append_proof;
(element_root, append_proof) = get_append_proof_from_multi_proof_update_m(elements, update_elements, proof);
require(hash_node(total_element_count, element_root) == root, "INVALID_PROOF");
element_root = get_new_root_from_append_proof_single_append_m(append_element, append_proof);
return hash_node(bytes32(uint256(total_element_count) + 1), element_root);
}
// INTERFACE: Try to update bytes32 elements in calldata and append a bytes32 element,
// given a root, bytes32 elements in calldata, and a Single Proof
function try_update_many_and_append_one_c(
bytes32 root,
bytes32[] calldata elements,
bytes32[] calldata update_elements,
bytes32 append_element,
bytes32[] calldata proof
) internal pure returns (bytes32 element_root) {
bytes32 total_element_count = proof[0];
require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE");
bytes32[] memory append_proof;
(element_root, append_proof) = get_append_proof_from_multi_proof_update_c(elements, update_elements, proof);
require(hash_node(total_element_count, element_root) == root, "INVALID_PROOF");
element_root = get_new_root_from_append_proof_single_append(append_element, append_proof);
return hash_node(bytes32(uint256(total_element_count) + 1), element_root);
}
// INTERFACE: Try to update bytes32 elements in memory and append a bytes32 element,
// given a root, bytes32 elements in calldata, and a Single Proof
function try_update_many_and_append_one_m(
bytes32 root,
bytes32[] calldata elements,
bytes32[] memory update_elements,
bytes32 append_element,
bytes32[] calldata proof
) internal pure returns (bytes32 element_root) {
bytes32 total_element_count = proof[0];
require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE");
bytes32[] memory append_proof;
(element_root, append_proof) = get_append_proof_from_multi_proof_update_m(elements, update_elements, proof);
require(hash_node(total_element_count, element_root) == root, "INVALID_PROOF");
element_root = get_new_root_from_append_proof_single_append(append_element, append_proof);
return hash_node(bytes32(uint256(total_element_count) + 1), element_root);
}
// INTERFACE: Try to update bytes elements in calldata and append bytes elements in calldata,
// given a root, bytes elements in calldata, and an Existence Multi Proof
function try_update_many_and_append_many_c(
bytes32 root,
bytes[] calldata elements,
bytes[] calldata update_elements,
bytes[] calldata append_elements,
bytes32[] calldata proof
) internal pure returns (bytes32 element_root) {
bytes32 total_element_count = proof[0];
require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE");
bytes32[] memory append_proof;
(element_root, append_proof) = get_append_proof_from_multi_proof_update_c(elements, update_elements, proof);
require(hash_node(total_element_count, element_root) == root, "INVALID_PROOF");
element_root = get_new_root_from_append_proof_multi_append_c(append_elements, append_proof);
return hash_node(bytes32(uint256(total_element_count) + append_elements.length), element_root);
}
// INTERFACE: Try to update bytes elements in memory and append bytes elements in memory,
// given a root, bytes elements in calldata, and an Existence Multi Proof
function try_update_many_and_append_many_m(
bytes32 root,
bytes[] calldata elements,
bytes[] memory update_elements,
bytes[] memory append_elements,
bytes32[] calldata proof
) internal pure returns (bytes32 element_root) {
bytes32 total_element_count = proof[0];
require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE");
bytes32[] memory append_proof;
(element_root, append_proof) = get_append_proof_from_multi_proof_update_m(elements, update_elements, proof);
require(hash_node(total_element_count, element_root) == root, "INVALID_PROOF");
element_root = get_new_root_from_append_proof_multi_append_m(append_elements, append_proof);
return hash_node(bytes32(uint256(total_element_count) + append_elements.length), element_root);
}
// INTERFACE: Try to update bytes32 elements in calldata and append bytes32 elements in calldata,
// given a root, bytes32 elements in calldata, and an Existence Multi Proof
function try_update_many_and_append_many_c(
bytes32 root,
bytes32[] calldata elements,
bytes32[] calldata update_elements,
bytes32[] calldata append_elements,
bytes32[] calldata proof
) internal pure returns (bytes32 element_root) {
bytes32 total_element_count = proof[0];
require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE");
bytes32[] memory append_proof;
(element_root, append_proof) = get_append_proof_from_multi_proof_update_c(elements, update_elements, proof);
require(hash_node(total_element_count, element_root) == root, "INVALID_PROOF");
element_root = get_new_root_from_append_proof_multi_append_c(append_elements, append_proof);
return hash_node(bytes32(uint256(total_element_count) + append_elements.length), element_root);
}
// INTERFACE: Try to update bytes32 elements in memory and append bytes32 elements in memory,
// given a root, bytes32 elements in calldata, and an Existence Multi Proof
function try_update_many_and_append_many_m(
bytes32 root,
bytes32[] calldata elements,
bytes32[] memory update_elements,
bytes32[] memory append_elements,
bytes32[] calldata proof
) internal pure returns (bytes32 element_root) {
bytes32 total_element_count = proof[0];
require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE");
bytes32[] memory append_proof;
(element_root, append_proof) = get_append_proof_from_multi_proof_update_m(elements, update_elements, proof);
require(hash_node(total_element_count, element_root) == root, "INVALID_PROOF");
element_root = get_new_root_from_append_proof_multi_append_m(append_elements, append_proof);
return hash_node(bytes32(uint256(total_element_count) + append_elements.length), element_root);
}
// INTERFACE: Create a tree and return the root, given a bytes element in calldata
function create_from_one_c(bytes calldata element) internal pure returns (bytes32 new_element_root) {
return hash_node(bytes32(uint256(1)), get_root_from_one_c(element));
}
// INTERFACE: Create a tree and return the root, given a bytes element in memory
function create_from_one_m(bytes memory element) internal pure returns (bytes32 new_element_root) {
return hash_node(bytes32(uint256(1)), get_root_from_one_m(element));
}
// INTERFACE: Create a tree and return the root, given a bytes32 element
function create_from_one(bytes32 element) internal pure returns (bytes32 new_element_root) {
return hash_node(bytes32(uint256(1)), get_root_from_one(element));
}
// INTERFACE: Create a tree and return the root, given bytes elements in calldata
function create_from_many_c(bytes[] calldata elements) internal pure returns (bytes32 new_element_root) {
return hash_node(bytes32(elements.length), get_root_from_many_c(elements));
}
// INTERFACE: Create a tree and return the root, given bytes elements in memory
function create_from_many_m(bytes[] memory elements) internal pure returns (bytes32 new_element_root) {
return hash_node(bytes32(elements.length), get_root_from_many_m(elements));
}
// INTERFACE: Create a tree and return the root, given bytes32 elements in calldata
function create_from_many_c(bytes32[] calldata elements) internal pure returns (bytes32 new_element_root) {
return hash_node(bytes32(elements.length), get_root_from_many_c(elements));
}
// INTERFACE: Create a tree and return the root, given bytes32 elements in memory
function create_from_many_m(bytes32[] memory elements) internal pure returns (bytes32 new_element_root) {
return hash_node(bytes32(elements.length), get_root_from_many_m(elements));
}
}
| Get current and update leafs from current bytes32 elements in calldata and update bytes32 elements in calldata, in reverse order | function get_reversed_leafs_from_current_and_update_elements_c(
bytes32[] calldata elements,
bytes32[] calldata update_elements
) internal pure returns (bytes32[] memory leafs, bytes32[] memory update_leafs) {
uint256 element_count = elements.length;
require(update_elements.length == element_count, "LENGTH_MISMATCH");
leafs = new bytes32[](element_count);
update_leafs = new bytes32[](element_count);
uint256 read_index = element_count - 1;
uint256 write_index;
while (write_index < element_count) {
leafs[write_index] = keccak256(abi.encodePacked(bytes1(0), elements[read_index]));
update_leafs[write_index] = keccak256(abi.encodePacked(bytes1(0), update_elements[read_index]));
write_index += 1;
read_index -= 1;
}
}
| 12,859,651 | [
1,
967,
783,
471,
1089,
7839,
87,
628,
783,
1731,
1578,
2186,
316,
745,
892,
471,
1089,
1731,
1578,
2186,
316,
745,
892,
16,
316,
4219,
1353,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
336,
67,
266,
7548,
67,
12070,
87,
67,
2080,
67,
2972,
67,
464,
67,
2725,
67,
6274,
67,
71,
12,
203,
565,
1731,
1578,
8526,
745,
892,
2186,
16,
203,
565,
1731,
1578,
8526,
745,
892,
1089,
67,
6274,
203,
225,
262,
2713,
16618,
1135,
261,
3890,
1578,
8526,
3778,
7839,
87,
16,
1731,
1578,
8526,
3778,
1089,
67,
12070,
87,
13,
288,
203,
565,
2254,
5034,
930,
67,
1883,
273,
2186,
18,
2469,
31,
203,
565,
2583,
12,
2725,
67,
6274,
18,
2469,
422,
930,
67,
1883,
16,
315,
7096,
67,
30062,
11793,
8863,
203,
203,
565,
7839,
87,
273,
394,
1731,
1578,
8526,
12,
2956,
67,
1883,
1769,
203,
565,
1089,
67,
12070,
87,
273,
394,
1731,
1578,
8526,
12,
2956,
67,
1883,
1769,
203,
565,
2254,
5034,
855,
67,
1615,
273,
930,
67,
1883,
300,
404,
31,
203,
565,
2254,
5034,
1045,
67,
1615,
31,
203,
203,
565,
1323,
261,
2626,
67,
1615,
411,
930,
67,
1883,
13,
288,
203,
1377,
7839,
87,
63,
2626,
67,
1615,
65,
273,
417,
24410,
581,
5034,
12,
21457,
18,
3015,
4420,
329,
12,
3890,
21,
12,
20,
3631,
2186,
63,
896,
67,
1615,
5717,
1769,
203,
1377,
1089,
67,
12070,
87,
63,
2626,
67,
1615,
65,
273,
417,
24410,
581,
5034,
12,
21457,
18,
3015,
4420,
329,
12,
3890,
21,
12,
20,
3631,
1089,
67,
6274,
63,
896,
67,
1615,
5717,
1769,
203,
1377,
1045,
67,
1615,
1011,
404,
31,
203,
1377,
855,
67,
1615,
3947,
404,
31,
203,
565,
289,
203,
2
] |
pragma solidity ^0.4.11;
contract ERC20_Transferable {
function balanceOf(address addr) public returns(uint);
function transfer(address to, uint value) public returns (bool);
}
contract TimeLockedRewardFaucet {
// =========== CONFIG START ===========
address constant public MULTISIG_OWNER = 0xe18Af0dDA74fC4Ee90bCB37E45b4BD623dC6e099;
address constant public TEAM_WALLET = 0x008cdC9b89AD677CEf7F2C055efC97d3606a50Bd;
ERC20_Transferable public token = ERC20_Transferable(0x7C5A0CE9267ED19B22F8cae653F198e3E8daf098);
uint public LOCK_RELASE_TIME = now + 15 minutes; //block.timestamp(4011221) == 1499846591
uint public WITHDRAWAL_END_TIME = LOCK_RELASE_TIME + 10 minutes;
// =========== CONFIG END ===========
address[] public team_accounts;
uint public locked_since = 0;
uint amount_to_distribute;
function all_team_accounts() external constant returns(address[]) {
return team_accounts;
}
function timeToUnlockDDHHMM() external constant returns(uint[3]) {
if (LOCK_RELASE_TIME > now) {
uint diff = LOCK_RELASE_TIME - now;
uint dd = diff / 1 days;
uint hh = diff % 1 days / 1 hours;
uint mm = diff % 1 hours / 1 minutes;
return [dd,hh,mm];
} else {
return [uint(0), uint(0), uint(0)];
}
}
function start() external
only(MULTISIG_OWNER)
inState(State.INIT){
locked_since = now;
}
function () payable {
msg.sender.transfer(msg.value); //pay back whole amount sent
State state = _state();
if (state==State.INIT) {
//collect addresses for payout
require(indexOf(team_accounts,msg.sender)==-1);
team_accounts.push(msg.sender);
} else if (state==State.WITHDRAWAL) {
// setup amount to distribute
if (amount_to_distribute==0) amount_to_distribute = token.balanceOf(this);
//payout processing
require(indexOf(team_accounts, msg.sender)>=0);
token.transfer(msg.sender, amount_to_distribute / team_accounts.length);
} else if (state==State.CLOSED) {
//collect unclaimed token to team wallet
require(msg.sender == TEAM_WALLET);
var balance = token.balanceOf(this);
token.transfer(msg.sender, balance);
} else {
revert();
}
}
enum State {INIT, LOCKED, WITHDRAWAL, CLOSED}
string[4] labels = ["INIT", "LOCKED", "WITHDRAWAL", "CLOSED"];
function _state() internal returns(State) {
if (locked_since == 0) return State.INIT;
else if (now < LOCK_RELASE_TIME) return State.LOCKED;
else if (now < WITHDRAWAL_END_TIME) return State.WITHDRAWAL;
else return State.CLOSED;
}
function state() constant public returns(string) {
return labels[uint(_state())];
}
function indexOf(address[] storage addrs, address addr) internal returns (int){
for(uint i=0; i<addrs.length; ++i) {
if (addr == addrs[i]) return int(i);
}
return -1;
}
//fails if state dosn't match
modifier inState(State s) {
if (_state() != s) revert();
_;
}
modifier only(address allowed) {
if (msg.sender != allowed) revert();
_;
}
} | collect addresses for payout setup amount to distributepayout processingcollect unclaimed token to team wallet | function () payable {
State state = _state();
if (state==State.INIT) {
require(indexOf(team_accounts,msg.sender)==-1);
team_accounts.push(msg.sender);
if (amount_to_distribute==0) amount_to_distribute = token.balanceOf(this);
require(indexOf(team_accounts, msg.sender)>=0);
token.transfer(msg.sender, amount_to_distribute / team_accounts.length);
require(msg.sender == TEAM_WALLET);
var balance = token.balanceOf(this);
token.transfer(msg.sender, balance);
revert();
}
}
string[4] labels = ["INIT", "LOCKED", "WITHDRAWAL", "CLOSED"];
| 1,781,921 | [
1,
14676,
6138,
364,
293,
2012,
3875,
3844,
358,
25722,
84,
2012,
4929,
14676,
6301,
80,
4581,
329,
1147,
358,
5927,
9230,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
1832,
8843,
429,
288,
203,
203,
3639,
3287,
919,
273,
389,
2019,
5621,
203,
3639,
309,
261,
2019,
631,
1119,
18,
12919,
13,
288,
203,
5411,
2583,
12,
31806,
12,
10035,
67,
13739,
16,
3576,
18,
15330,
13,
631,
17,
21,
1769,
203,
5411,
5927,
67,
13739,
18,
6206,
12,
3576,
18,
15330,
1769,
203,
5411,
309,
261,
8949,
67,
869,
67,
2251,
887,
631,
20,
13,
3844,
67,
869,
67,
2251,
887,
273,
1147,
18,
12296,
951,
12,
2211,
1769,
203,
5411,
2583,
12,
31806,
12,
10035,
67,
13739,
16,
1234,
18,
15330,
13,
34,
33,
20,
1769,
203,
5411,
1147,
18,
13866,
12,
3576,
18,
15330,
16,
225,
3844,
67,
869,
67,
2251,
887,
342,
5927,
67,
13739,
18,
2469,
1769,
203,
5411,
2583,
12,
3576,
18,
15330,
422,
25156,
2192,
67,
59,
1013,
15146,
1769,
203,
5411,
569,
11013,
273,
1147,
18,
12296,
951,
12,
2211,
1769,
203,
5411,
1147,
18,
13866,
12,
3576,
18,
15330,
16,
11013,
1769,
203,
5411,
15226,
5621,
203,
3639,
289,
203,
565,
289,
203,
203,
203,
565,
533,
63,
24,
65,
3249,
273,
8247,
12919,
3113,
315,
6589,
2056,
3113,
315,
9147,
40,
10821,
1013,
3113,
315,
28475,
11929,
31,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// Правила для изменения достоверности распознавания конкретных словоформ в русском словаре.
// Обычное предназначение этих правил - изменить равновероятные распознавания
// омонимичных форм жаль(безличный глагол)>жаль(императив),
// либо повлиять на выбор многословных форм в противовес
// выбору отдельных слов: [слева от] <--> [слева] [от]
wordform_score смеси{глагол}=-10 // из чего смеси ?
wordform_score ага{ существительное }=-5
wordform_score малышки{ род:муж }=-10 // Малышки будут прыгать от радости!
wordform_score мебели{ число:мн }=-10 // Рвали обивку мебели.
wordform_score начало{ глагол }=-6 // Сегодня неплохое начало.
wordform_score воды{ род:муж }=-10 // мы приплывем в их воды
wordform_score скалы{ род:муж }=-10 // там должны быть скалы
wordform_score кафе{ род:муж }=-10 // в кафе
wordform_score скалы{ род:муж }=-10 // волны бились о скалы
wordform_score кроме{ существительное }=-10 // кроме этой вот ягоды
wordform_score жилище{ род:жен }=-10 // в ее жилище
wordform_score почитай{ наречие }=-4 // Ты лучше почитай.
wordform_score без{ существительное }=-10 // Без кладовок и гардеробных комнат
wordform_score бренды{род:жен}=-10 // Вообще-то перечисленные бренды давно уже избавились от налета местечковости.
wordform_score ярки{ существительное }=-10 // Глаза его были ярки
wordform_score голубей{ прилагательное }=-1 // Ты будешь Петькиных голубей подманивать.
wordform_score дело{ глагол }=-10 // Дело наше лесное.
wordform_score правило{ глагол }=-5 // Такое наше правило...
wordform_score карусель{ глагол }=-10 // Карусель начинается мировая.
wordform_score Германии{ число:мн }=-10 // В Германии беженец спрыгнул с поезда из-за угрозы депортации в Италию
wordform_score бусы { род:муж }=-5 // Весенние бусы персикового дерева разорвались.
wordform_score суеты { число:мн }=-10 // Завершился 26-ой тур российской премьер-лиги.
wordform_score метель { глагол }=-10 // На улице метель.
//wordform_score по-видимому { наречие }=2
//wordform_score по-видимому { вводное }=2 // Ему, по-видимому, не терпелось начать.
wordform_score энергии { существительное число:мн }=-2 // Ему и сейчас не занимать энергии.
wordform_score таки { существительное }=-5 // Ему-таки удалось ее завести.
wordform_score выстуживаем { прилагательное }=-1
wordform_score уполномочиваем { прилагательное }=-1
wordform_score кормим { прилагательное }=-1
wordform_score чиним { прилагательное }=-1
wordform_score заводим { прилагательное }=-1
wordform_score периодизируем { прилагательное }=-1
wordform_score завозим { прилагательное }=-1
wordform_score дегустируем { прилагательное }=-1
wordform_score увозим { прилагательное }=-1
wordform_score вообразим { прилагательное }=-1
wordform_score дробим { прилагательное }=-1
wordform_score таскаем { прилагательное }=-1
wordform_score превозносим { прилагательное }=-1
wordform_score потопляем { прилагательное }=-1
wordform_score волочим { прилагательное }=-1
wordform_score перевиваем { прилагательное }=-1
wordform_score засекречиваем { прилагательное }=-1
wordform_score храним { прилагательное }=-1
wordform_score уносим { прилагательное }=-1
wordform_score предводим { прилагательное }=-1
wordform_score мыслим { прилагательное }=-1
wordform_score проходим { прилагательное }=-1
wordform_score влачим { прилагательное }=-1
wordform_score творим { прилагательное }=-1
wordform_score сравним { прилагательное }=-1
wordform_score измерим { прилагательное }=-1
wordform_score душим { прилагательное }=-1
wordform_score сопоставим { прилагательное }=-1
wordform_score досягаем { прилагательное }=-1
wordform_score травим { прилагательное }=-1
wordform_score благоволим { прилагательное }=-1
wordform_score убеждаем { прилагательное }=-1
wordform_score слышим { прилагательное }=-1
wordform_score слышим { прилагательное }=-1
wordform_score подгружаем { прилагательное }=-1
wordform_score укрупняем { прилагательное }=-1
wordform_score взымаем { прилагательное }=-1
wordform_score зашвыриваем { прилагательное }=-1
wordform_score зависим { прилагательное }=-1
wordform_score ощутим { прилагательное }=-1
wordform_score громим { прилагательное }=-1
wordform_score застраиваем { прилагательное }=-1
wordform_score исправим { прилагательное }=-1
wordform_score выполним { прилагательное }=-1
wordform_score производим { прилагательное }=-1
wordform_score втемяшиваем { прилагательное }=-1
wordform_score содержим { прилагательное }=-1
wordform_score подносим { прилагательное }=-1
wordform_score вкраиваем { прилагательное }=-1
wordform_score беспокоим { прилагательное }=-1
wordform_score взнуздываем { прилагательное }=-1
wordform_score носим { прилагательное }=-1
wordform_score любим { прилагательное }=-1
wordform_score доносим { прилагательное }=-1
wordform_score уценяем { прилагательное }=-1
wordform_score ненавидим { прилагательное }=-1
wordform_score судим { прилагательное }=-1
wordform_score вмораживаем { прилагательное }=-1
wordform_score ввозим { прилагательное }=-1
wordform_score подвозим { прилагательное }=-1
wordform_score развозим { прилагательное }=-1
wordform_score привозим { прилагательное }=-1
wordform_score реструктурируем { прилагательное }=-1
wordform_score реструктурируем { прилагательное }=-1
wordform_score подтопляем { прилагательное }=-1
wordform_score перезаписываем { прилагательное }=-1
wordform_score ценим { прилагательное }=-1
wordform_score национализируем { прилагательное }=-1
wordform_score национализируем { прилагательное }=-1
wordform_score проминаем { прилагательное }=-1
wordform_score переносим { прилагательное }=-1
wordform_score возводим { прилагательное }=-1
wordform_score проницаем { прилагательное }=-1
wordform_score проводим { прилагательное }=-1
wordform_score проводим { прилагательное }=-1
wordform_score таим { прилагательное }=-1
wordform_score синхронизируем { прилагательное }=-1
wordform_score вводим { прилагательное }=-1
wordform_score гоним { прилагательное }=-1
wordform_score разделим { прилагательное }=-1
wordform_score ввариваем { прилагательное }=-1
wordform_score бороздим { прилагательное }=-1
wordform_score воспоминаем { прилагательное }=-1
wordform_score руководим { прилагательное }=-1
wordform_score сносим { прилагательное }=-1
wordform_score разносим { прилагательное }=-1
wordform_score стандартизируем { прилагательное }=-1
wordform_score терпим { прилагательное }=-1
wordform_score выносим { прилагательное }=-1
wordform_score выносим { прилагательное }=-1
wordform_score боготворим { прилагательное }=-1
wordform_score клоним { прилагательное }=-1
wordform_score прозываем { прилагательное }=-1
wordform_score привносим { прилагательное }=-1
wordform_score соизмерим { прилагательное }=-1
wordform_score компилируем { прилагательное }=-1
wordform_score централизуем { прилагательное }=-1
wordform_score упаковываем { прилагательное }=-1
wordform_score возбудим { прилагательное }=-1
wordform_score отделим { прилагательное }=-1
wordform_score ограбляем { прилагательное }=-1
wordform_score объясним { прилагательное }=-1
wordform_score наводим { прилагательное }=-1
wordform_score подводим { прилагательное }=-1
wordform_score исполним { прилагательное }=-1
wordform_score вычислим { прилагательное }=-1
wordform_score монетизируем { прилагательное }=-1
wordform_score отряжаем { прилагательное }=-1
wordform_score разъединим { прилагательное }=-1
wordform_score заменим { прилагательное }=-1
wordform_score охаиваем { прилагательное }=-1
wordform_score растворим { прилагательное }=-1
wordform_score наносим { прилагательное }=-1
wordform_score уничтожим { прилагательное }=-1
wordform_score томим { прилагательное }=-1
wordform_score заполним { прилагательное }=-1
wordform_score сводим { прилагательное }=-1
wordform_score выводим { прилагательное }=-1
wordform_score перевозим { прилагательное }=-1
wordform_score взаимозаменяем { прилагательное }=-1
wordform_score поносим { прилагательное }=-1
wordform_score вверстываем { прилагательное }=-1
wordform_score воспроизводим { прилагательное }=-1
wordform_score вывозим { прилагательное }=-1
wordform_score прорежаем { прилагательное }=-1
wordform_score дренируем { прилагательное }=-1
wordform_score разграбляем { прилагательное }=-1
wordform_score обеззараживаем { прилагательное }=-1
wordform_score тесним { прилагательное }=-1
wordform_score вносим { прилагательное }=-1
wordform_score разрешим { прилагательное }=-1
wordform_score подбодряем { прилагательное }=-1
wordform_score уловим { прилагательное }=-1
wordform_score вдергиваем { прилагательное }=-1
wordform_score автопилотируем { прилагательное }=-1
wordform_score автопилотируем { прилагательное }=-1
wordform_score воссоединяем { прилагательное }=-1
wordform_score фондируем { прилагательное }=-1
wordform_score зрим { прилагательное }=-1
wordform_score допустим { прилагательное }=-1
wordform_score преподносим { прилагательное }=-1
wordform_score устраним { прилагательное }=-1
wordform_score устрашим { прилагательное }=-1
wordform_score поправим { прилагательное }=-1
wordform_score нарезаем { прилагательное }=-1
wordform_score значим { прилагательное }=-1
wordform_score истребим { прилагательное }=-1
wordform_score окормляем { прилагательное }=-1
wordform_score воплотим { прилагательное }=-1
wordform_score будоражим { прилагательное }=-1
wordform_score тревожим { прилагательное }=-1
wordform_score применим { прилагательное }=-1
wordform_score дактилоскопируем { прилагательное }=-1
wordform_score дактилоскопируем { прилагательное }=-1
wordform_score браним { прилагательное }=-1
wordform_score провозим { прилагательное }=-1
wordform_score чтим { прилагательное }=-1
wordform_score приложим { прилагательное }=-1
wordform_score повторим { прилагательное }=-1
wordform_score вменяем { прилагательное }=-1
wordform_score раздробляем { прилагательное }=-1
wordform_score льготируем { прилагательное }=-1
wordform_score перезаправляем { прилагательное }=-1
wordform_score удовлетворим { прилагательное }=-1
wordform_score отводим { прилагательное }=-1
wordform_score переводим { прилагательное }=-1
wordform_score утапливаем { прилагательное }=-1
wordform_score предотвратим { прилагательное }=-1
wordform_score тормозим { прилагательное }=-1
wordform_score вербализуем { прилагательное }=-1
wordform_score тостуем { прилагательное }=-1
wordform_score разводим { прилагательное }=-1
wordform_score уводим { прилагательное }=-1
wordform_score искореним { прилагательное }=-1
wordform_score протапливаем { прилагательное }=-1
wordform_score изготавливаем { прилагательное }=-1
wordform_score изъясним { прилагательное }=-1
wordform_score употребим { прилагательное }=-1
wordform_score разложим { прилагательное }=-1
wordform_score возносим { прилагательное }=-1
wordform_score проносим { прилагательное }=-1
wordform_score предвидим { прилагательное }=-1
wordform_score полимеризуем { прилагательное }=-1
wordform_score полимеризуем { прилагательное }=-1
wordform_score исчислим { прилагательное }=-1
wordform_score погрешим { прилагательное }=-1
wordform_score совместим { прилагательное }=-1
wordform_score впериваем { прилагательное }=-1
wordform_score приносим { прилагательное }=-1
wordform_score доводим { прилагательное }=-1
wordform_score заносим { прилагательное }=-1
wordform_score вытаращиваем { прилагательное }=-1
wordform_score обоготворяем { прилагательное }=-1
wordform_score наметаем { прилагательное }=-1
wordform_score делим { прилагательное }=-1
wordform_score хвалим { прилагательное }=-1
wordform_score излечим { прилагательное }=-1
wordform_score обратим { прилагательное }=-1
wordform_score уязвим { прилагательное }=-1
wordform_score определим { прилагательное }=-1
wordform_score произносим { прилагательное }=-1
wordform_score возобновим { прилагательное }=-1
wordform_score соотносим { прилагательное }=-1
wordform_score победим { прилагательное }=-1
wordform_score раним { прилагательное }=-1
wordform_score отличим { прилагательное }=-1
wordform_score прокачиваем { прилагательное }=-1
wordform_score рейтингуем { прилагательное }=-1
wordform_score растравляем { прилагательное }=-1
wordform_score коров { род:муж } = -2 // Без коров мужчины погибли бы.
wordform_score ангел { род:жен } = -2 // А мисс Уиллоу была просто ангел.
wordform_score слаб { глагол } = -1 // Просто ты слаб!
//wordform_score писал { stress:"п^исал" } = -1 // Державин писал:
//wordform_score писала { stress:"п^исала" } = -1
wordform_score сердит { глагол } = -1 // Он очень сердит.
wordform_score ребят { падеж:зват } = -1 // Ребят пора вернуть
wordform_score помочь { существительное } = -10 // мы хотим вам помочь
wordform_score вон { существительное } = -1 // Я вон зарабатываю.
wordform_score скалами { род:муж } = -5 // Миновав Море Акул, путешественники оказались над Крабьими Скалами.
wordform_score воды { род:муж } = -5 // выпить воды
wordform_score воде { род:муж } = -5 // рожать в воде
wordform_score лук { род:жен } = -5 // возьми с собой лук
wordform_score базе { род:муж } = -5 // заправлять на базе
wordform_score порошки { род:жен } = -5 // Порошки не помогают...
wordform_score обезвреживания { число:мн } = -5 // Разработали план обезвреживания.
wordform_score трех { существительное } = -10 // Считаю до трех.
wordform_score метель { глагол } = -10 // На улице метель.
wordforms_score городской { существительное }=-1 // Существуют городские правила, касающиеся этих процедур.
wordforms_score утесать {глагол}=-5 // Я утешу тебя.
wordforms_score примереть {глагол}=-5 // Внутри пример
wordforms_score запоить {глагол}=-5 // Я запою
wordforms_score новое { существительное }=-5 // Начинаются поиски новых приемов, новых методов.
wordforms_score просек { существительное }=-5 // Матросы переползали просеку.
wordforms_score прививок { существительное }=-10
wordforms_score полок { существительное род:муж }=-5 // Началась переправа полков.
wordforms_score уток { существительное род:муж }=-10
wordforms_score юр { существительное }=-10
wordforms_score наркотика { существительное род:жен }=-10 // Одно время она даже пыталась бросить наркотики
wordforms_score полян { существительное род:муж }=-10
wordforms_score полянин { существительное род:муж }=-10
wordforms_score чужой { существительное }=-5 // голос ее стал чужим
wordforms_score живой { существительное }=-5 // но оно было живым!
wordforms_score пяток { существительное }=-5 // сверкать пятками
wordforms_score ложок { существительное }=-5 // звякнуть ложками
wordforms_score костра { существительное }=-5 // сжечь на костре
wordforms_score роить { глагол }=-10 // Я рою траншеи
wordforms_score ситце { род:ср }=-10 // шить из ситца
wordforms_score взяток { существительное }=-10 // Врач попался на взятке
wordforms_score сило { существительное }=-10 // Оставить в силе закон.
wordforms_score покадить { глагол }=-5 // Я после покажу...
wordforms_score выло { существительное }=-5 // Як не выл больше.
wordforms_score вылезть { глагол }=-1 // Я медленно вылез.
wordforms_score лунь { существительное }=-1 // Астронавты смогут оставаться на Луне в течение недели
wordforms_score закроить { глагол }=-1 // Я потом закрою.
wordforms_score вылезть { глагол }=-1 // Машинист вылез.
wordforms_score охаять { глагол }=-1 // Кто охает?
wordforms_score покадить { глагол }=-1 // Я покажу!
wordforms_score ила { существительное род:жен }=-5 // Я раскопал ил
wordforms_score ос { существительное род:муж }=-5 // В воздухе гудели мухи и осы.
wordforms_score прикроить { глагол }=-2 // Атакуй, прикрою.
wordforms_score ох { существительное }=-2 // Ей это ох как не нравилось.
wordforms_score кровяный { прилагательное }=-2 // Стимулирует кровообращение и снижает кровяное давление.
wordforms_score жило { существительное }=-5 // Именно так выглядит обычный кварц рудных жил.
wordforms_score крон { существительное } =-5 // Видите эти могучие кроны, тяжелые плоды?
wordforms_score утюжка { существительное }=-5
wordforms_score нар { существительное }=-2
wordforms_score подбора { существительное }=-10
wordforms_score кормило { существительное }=-10
wordforms_score дубка { существительное }=-2 // Сам горб порос крепкими дубками.
wordforms_score кода { существительное }=-5 // Серые ячейки указывают на неназначенные коды
wordforms_score песнь { существительное }=-1 // Проводится круглогодичный конкурс бардовской песни.
wordforms_score тоника { существительное }=-10
wordforms_score рака { существительное }=-10
wordforms_score бахчевый { прилагательное }=-5 // Особое внимание уделялось бахчевым культурам.
wordforms_score нецелевый { прилагательное }=-5 // Процветало нецелевое использование этих средств.
wordforms_score запасный { прилагательное }=-5 // Пятигорский вокзал был запасным вариантом.
wordforms_score бредовой { прилагательное }=-5 // Первая стопка содержала бредовые работы.
wordforms_score меньшой { прилагательное }=-5 // Такие передачи имеют меньшую аудиторию.
wordforms_score меховый { прилагательное }=-5 // Летняя распродажа меховых изделий продолжается!
wordforms_score заводский { прилагательное }=-10 // Существует заводская группа внутренних аудиторов.
wordforms_score щенка { существительное }=-10 // Продаются красивые щенки йоркширского терьера.
wordforms_score кур { существительное }=-10
wordforms_score любый { прилагательное }=-10 // Для него любая власть является раздражителем.
wordforms_score ванный { прилагательное }=-1 // большая ванная
wordforms_score плавной { прилагательное }=-10 // Такая конструкция обеспечивает плавное перемещение
wordforms_score санатория { существительное }=-10
wordforms_score шпалер { существительное }=-10
wordforms_score хромый { прилагательное }=-5 // Волшебный лепесток излечивает хромого мальчика.
wordforms_score газа { существительное }=-1 // Раскаленные газы с чудовищной силой вырываются
wordforms_score рейки { род:ср }=-10 // Многочисленные рейки стягивала стальная проволока.
wordforms_score протяжной { прилагательное }=-5 // Каменные своды отозвались протяжным эхом.
wordforms_score страстной { прилагательное }=-2 // Страстная любовь вызывает страстную борьбу.
wordforms_score дневный { прилагательное }=-2 // Дневная суета сменилась полной тишиной.
wordforms_score хромый { прилагательное }=-2 // Гони эту свору хромого горбуна!
wordforms_score восковой { прилагательное }=-5 // Восковые свечи разливали мягкое сияние.
wordforms_score угловый { прилагательное }=-5 // Угловая камера записала этот момент.
wordforms_score пестрить { глагол }=-10 // Мировая пресса пестрит сенсационными сообщениями.
wordforms_score чина { существительное }=-5 // Это требование поддержали высшие чины.
wordforms_score языковый { прилагательное }=-5
wordforms_score половый { прилагательное }=-5 // Переполненный желудок затрудняет половой акт.
wordforms_score шампанский { прилагательное }=-5
wordforms_score замок { глагол }=-10 // Замок небольшой и необычный.
wordforms_score синоптика { существительное }=-5 // Русский сухогруз утопили турецкие синоптики.
wordforms_score корректив { существительное род:муж }=-10 // Президентские выборы вносят определенные коррективы.
wordforms_score поджога { существительное род:жен }=-10 // Умышленные поджоги стали доходным бизнесом.
wordforms_score матерь { существительное }=-1
wordforms_score плюсовый { прилагательное }=-1
wordforms_score экой { прилагательное }=-1 // Экую несуразицу плетет этот мужик.
wordforms_score овсяной { прилагательное }=-5 // Сморщенный чиновник жует овсяную лепешку.
wordforms_score хмельный { прилагательное }=-1 // Остался ровный шелест хмельных кипарисов.
wordforms_score спазма { существительное }=-10 // Пустой желудок разрывали болезненные спазмы.
wordforms_score мазка { существительное }=-10 // Замельтешили нервные мазки ярких красок...
wordforms_score громовый { прилагательное }=-5 // Эти вспышки сопровождались громовыми ударами.
wordforms_score зарев { существительное }=-10 // Длинные пальцы налились красноватым заревом.
wordforms_score шара { существительное }=-5 // Латунные шары заполнялись керосиновой смесью.
wordforms_score корн { существительное }=-5 // в корне мандрагоры содержится наркотический сок
wordforms_score справа { существительное }=-10 // Справа Дэни разглядела маленькое каменное святилище.
wordforms_score теля { существительное }=-5 // Было чувство клаустрофобии в собственном теле.
wordforms_score коленной { прилагательное }=-5 // 26-летний футболист получил растяжение коленного сустава.
wordforms_score полом { существительное }=-5 // Бойцы рыли под полом окопы.
wordforms_score бород { существительное }=-5 // Елена просит молодого мужа сбрить бороду.
wordform_score присутствия { число:мн }=-5 // // Ей стало не хватать его присутствия.
wordform_score косы { род:муж число:мн }=-10 // Ее косы были убраны под шапку.
wordform_score обожания { число:мн }=-10 // Изливают любвеобильные лучи обожания
wordform_score смелости { число:мн }=-10 // Ей просто недоставало смелости его сделать.
wordform_score ясности { число:мн }=-10 // Черные ящики не добавили ясности.
wordform_score с { частица }=-2 // // Загадали желания – ждем-с!
wordform_score "ей-богу"{} = 10 // Ей-богу, отлично выйдет.
wordform_score дыхания { число:мн }=-2 // Ее подключили к аппарату искусственного дыхания.
wordform_score реставрации { число:мн }=-2 // Ее не ремонтировали со времен Реставрации.
wordform_score бересты { число:мн }=-10 // Сверху настелили большие куски бересты.
wordform_score охоты { число:мн }=-10 // Сезон охоты откроют 25 августа.
wordform_score развития { существительное число:мн }=-10 // В Чувашии обсуждают проблемы инновационного развития регионов
wordform_score наглости { существительное число:мн }=-10 // противопоставить наглости
wordform_score еды { существительное число:мн }=-5 // хозяин должен дать еды
wordform_score безопасности { существительное число:мн }=-5 // Его обвинили в пренебрежении вопросами безопасности.
wordform_score выдержки { существительное число:мн }=-5 // Если хватит выдержки...
wordform_score истерик { существительное }=-2 // И хватит истерик!
wordform_score послезавтра { существительное }=-5 // Послезавтра утром проверю...
wordform_score дискриминации { число:мн }=-5 // Его называли анахронизмом и признаком дискриминации.
wordform_score полиции { число:мн }=-5 // Его доставили в 20-й отдел полиции.
wordform_score уверенности { число:мн }=-10 // Его немое обожание придавало Анне уверенности.
wordform_score насилия { число:мн }=-5 // А насилия Рекс никогда не совершит.
wordform_score болтовни { число:мн }=-10 // А теперь хватит болтовни, Кейн.
wordform_score оружия { число:мн }=-10 // А Филип вообще не любит оружия.
wordform_score внимания { число:мн }=-10 // А на брата не обращай внимания.
wordform_score бытия { число:мн }=-10 // Имеют телесную форму предшествовавшего бытия.
wordform_score сочувствия { число:мн }=-5 // А вот Мария действительно заслуживает сочувствия.
wordform_score разнообразия { число:мн }=-5 // Болото хотело разнообразия в компании.
wordform_score ним { существительное }=-5 // А вместе с ним и свою душу.
wordform_score ник { глагол }=-5 // А ты как думаешь, Ник?
wordform_score тете { одуш:неодуш }=-1 // А перед этим послал тете цветы.
wordform_score гораздо { прилагательное }=-5 // А кажется, что гораздо больше.
wordform_score Калифорнии { число:мн }=-10 // А в Калифорнии сейчас цветет мимоза.
wordform_score замок { глагол }=-10 // А на краю леса красивый замок.
wordform_score мирке { род:жен }=-5 // В их мирке вдруг оказался третий.
wordform_score жалости { число:мн }=-5 // В этом деле не знают жалости.
wordform_score орала { существительное }=-5 // Я била подушки и орала в ярости.
wordform_score яркости { число:мн }=-2 // Второй цвет добавляет яркости и выразительности.
wordform_score выразительности { число:мн }=-10 // Второй цвет добавляет яркости и выразительности.
wordform_score македонии { число:мн }=-10 // Встретились главы МИД России и Македонии.
wordform_score бочками { род:муж }=-5 // Грузить апельсины бочками?
wordform_score полдня { существительное }=-5 // Полдня шел дождь.
wordform_score пол { падеж:род }=-5 // Меряю шагами пол.
wordform_score правей { глагол }=-10 // Еще чуть правей...
wordform_score чуточку { существительное }=-10 // Самолет чуточку подбросило.
wordform_score правосудья { число:мн }=-10 // Жид хочет правосудья
wordform_score единства { число:мн }=-10 // Партия хочет единства.
wordform_score счастья { число:мн }=-10 // Все хотят счастья.
wordform_score агрессии { число:мн }=-10 // Фашизм хочет агрессии?..
wordform_score горючки { число:мн }=-10 // Не хватило горючки.
wordform_score усмирения { число:мн }=-10 // Потребовать усмирения Петрограда.
wordform_score метель { глагол }=-15 // На улице метель.
wordform_score ясней { глагол }=-10 // Куда уж ясней.
wordform_score штурману { глагол }=-10 // Штурману тоже трудно.
wordform_score целиком { существительное }=-10 // Скука съела целиком.
wordform_score хмелю { глагол }=-10
wordform_score четкой { существительное }=-2 // Работа персонала была четкой
wordform_score милую { глагол }=-10
wordform_score гордости { число:мн }=-10 // Есть другие предметы, достойные гордости.
wordform_score тих { глагол }=-10
wordform_score инфраструктуры { число:мн }=-2 // РАЗРАБОТАЮТ ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ ЭЛЕКТРОННОЙ ИНФРАСТРУКТУРЫ.
wordform_score ангелы { род:жен }=-5
wordform_score большие { СТЕПЕНЬ:СРАВН }=-10 // большие отели
wordform_score больших { СТЕПЕНЬ:СРАВН }=-10
wordform_score большим { СТЕПЕНЬ:СРАВН }=-10
wordform_score большими { СТЕПЕНЬ:СРАВН }=-10
wordform_score физики { род:жен } =-5 // Волгоградские Физики совершили научную революцию.
wordform_score хорошей { глагол }=-10 // хорошей душевой кабиной
wordform_score стиле { существительное род:ср }=-2 // Продам свадебное платье в греческом стиле
wordform_score молока { род:жен падеж:им }=-2
wordform_score Турции { число:мн }=-5 // В Турции муллы провозглашают священную войну.
wordform_score гости { глагол }=-5 // В саду могут оказаться и гости.
wordform_score администрации { число:мн }=-5 // Структуру администрации Краснодара изменят
wordform_score горячим { глагол }=-5
wordform_score свежую { глагол }=-5 // свежую рыбу
wordform_score голубой { существительное }=-10 // за дверью жил голубой лев
wordform_score фанту { род:муж }=-5
wordform_score фанте { род:муж }=-5
wordform_score баню { ГЛАГОЛ }=-5
wordform_score бань { ГЛАГОЛ }=-5
wordform_score сласти { ГЛАГОЛ }=-10
wordform_score сыр { ПРИЛАГАТЕЛЬНОЕ }=-5
wordform_score сыра { ПРИЛАГАТЕЛЬНОЕ }=-5
wordform_score сыры { ПРИЛАГАТЕЛЬНОЕ }=-5
wordform_score альбом { ПАДЕЖ:ТВОР }=-5 // По запросу могу показать альбом.
wordform_score хоре { падеж:предл одуш:одуш }=-5 // подпевать в церковном хоре
wordform_score Европы { число:мн }=-5 // Ее считали прекраснейшей женщиной Европы.
wordform_score свежую { глагол }=-6 // свежую форель
wordform_score содействия { число:мн }=-5
wordform_score общества { число:мн }=-1 // Индивидуальную честность связали с прогрессивностью общества
wordform_score подготовки { число:мн }=-5 // Процесс подготовки спутника к запуску уместили в короткий видеоролик
wordform_score недвижимости { число:мн }=-10 // Тест: способны ли вы отличить рекламу недвижимости от рекламы презервативов?
wordform_score родины { число:мн }=-2 // Кандидата «Родины» уличили в получении поддельного военного билета
wordform_score защиты { число:мн }=-2 // Google просит защиты у Аркадия Дворковича
wordform_score освобождения { число:мн }=-5 // В Болгарии отпраздновали годовщину освобождения от османского ига
wordform_score веры { число:мн }=-5 // Папу Римского призвали отказаться от догмата своей непогрешимости в вопросах веры
wordforms_score гнома { существительное }=-10 // Но гномы начали погоню
wordform_score рада { существительное }=-2
wordform_score полон { существительное }=-10 // а этот полон ненависти
wordform_score Марин { существительное }=-2 // Алла отпустила Марину
wordforms_score снимка { существительное }=-5
wordforms_score ям { существительное }=-5
wordforms_score купа { существительное }=-5 // мы нашли в его купе
wordforms_score половый { прилагательное }=-5
wordforms_score теста { существительное }=-5 // выявляться тестами
wordforms_score гриба { существительное }=-5 // отравиться грибами
wordforms_score босый { прилагательное }=-5 // ноги ее были босые
wordforms_score арен { существительное }=-5
wordforms_score плат { существительное }=-5
wordforms_score теста { существительное род:жен }=-5
wordforms_score бара { существительное род:жен }=1 // праздновать в баре
wordform_score погиб { существительное }=-5
wordforms_score хора { существительное }=-5
wordforms_score дворовой { прилагательное }=-5
wordforms_score сводной { прилагательное }=-5
wordforms_score шпор { существительное }=-5
wordform_score сдачи { число:мн }=-2 // Сдачи не надо.
wordforms_score комара { существительное }=-5
wordforms_score бара { существительное }=-5
wordforms_score теста { существительное }=-5
wordforms_score венка { существительное }=-5
wordforms_score метода { существительное }=-5
wordforms_score мор { существительное }=-5
wordforms_score мора { существительное }=-5 // Море достаточно холодное
wordform_score трое { существительное }=-5 // трое из мира людей
wordform_score повезло { глагол }=-2 // - Не повезло тебе.
wordforms_score распоряженье { существительное }=-5 // Полицейские стали ждать дальнейших распоряжений.
wordforms_score варианта { существительное род:жен }=-10 // Для разных ситуаций есть предпочтительные варианты.
wordforms_score лангуста { существительное }=-10 // В рыбном купила огромного сырокопченого лангуста.
wordforms_score верховый { прилагательное }=-5 // Бывало, возьмут верховых лошадей и уедут в поле.
wordforms_score об { существительное }=-10
wordforms_score слушанье { существительное }=-5 // Регламент проведения публичных слушаний утверждается постановлением городского парламента.
wordforms_score леса { существительное }=-5 // В алтайских лесах истребили сибирского коконопряда, объедающего хвою
wordforms_score рельса { существительное }=-1 // В основном были подорваны рельсы на второстепенных запасных путях.
wordforms_score перекрытье { существительное }=-5 // Лишь в одной части здания перекрытия оказались бетонными.
wordforms_score бракосочетанье { существительное }=-5 // Но в понедельник во Дворце бракосочетания был выходной.
wordforms_score благополучье { существительное } =-5 // В полном благополучии путешественники достигли Вефиля.
wordforms_score лет { род:муж }=-5 // Летом в этой бухте собиралась целая флотилия яхт.
wordforms_score снов { существительное }=-10
wordforms_score така { существительное }=-5 // Сигнал бедствия от лыжницы так и не поступил.
wordforms_score корпусный { прилагательное }=-5 // Снаряд выпустила наша батарея 5-го корпусного артиллерийского полка.
wordforms_score окружный { прилагательное }=-5 // В Агинском округе началась внеочередная сессия окружной думы.
wordforms_score входный { прилагательное }=-5 // Для делегатов напечатали специальные входные билеты.
wordforms_score образной { прилагательное }=-5 // Образное выражение, однако, отражает реальную жизнь.
wordforms_score окружный { прилагательное }=-5 // Финансирование осуществлялось из окружного бюджета.
wordforms_score дверный { прилагательное }=-5
wordforms_score личной{ прилагательное }=-5 // - А ты пробовал концентрировать свои личные мысли?
wordforms_score основный{ прилагательное }=-5 // Основные "боевые" мероприятия проходят в Самаре.
wordforms_score мирной{ прилагательное }=-5 // Уже в мирное время миссии тачали хорошие сапоги;
wordforms_score ЧЕСТНОЙ{ прилагательное }=-5 // Это было хорошее, честное, благородное желание.
wordforms_score РОДНЫЙ{ прилагательное }=-5 // Израильские танкисты приняли меня как родного.
wordforms_score назначенье{ существительное }=-5 // В администрации Алтайского края произошел ряд отставок и назначений
wordforms_score кадра{ существительное }=-5
wordforms_score перекрытье{ существительное }=-5 // Лишь в одной части здания перекрытия оказались бетонными.
wordforms_score увечье{ существительное }=-5 // Жертва аварии скончалась в больнице от полученных увечий.
wordforms_score исключенье{ существительное }=-5 // Однако из этого правила существует несколько исключений.
wordforms_score подкрепленье{ существительное }=-5 // При этом используется вероятностная схема подкреплений.
wordforms_score нет{ существительное }=-5 // решение жениться или нет можешь принять только ты сам.
wordforms_score признанье{ существительное }=-5 //
wordforms_score втора{ существительное }=-5
wordforms_score настроенье{ существительное }=-5 // Но антироссийских настроений вы в Грузии не найдете.
wordforms_score заседанье{ существительное }=-5 // Семеро акционеров не были допущены в зал заседаний.
wordforms_score сбора{ существительное }=-5 // В ближайшее время Денис улетает на очередные сборы.
wordforms_score предложенье{ существительное }=-5 // Вячеслав Евгеньевич готовит свой пакет предложений.
wordforms_score свитка{ существительное }=-5 // В кумранских свитках нередко встречается тайнопись
wordforms_score носка{ существительное }=-5 // Из-под подола выглядывали белые спортивные носки.
wordforms_score дыханье{ существительное }=-5 // При виде обнажившихся грудей перехватило дыхание.
wordforms_score усилье{ существительное }=-5 // Бесконечная борьба требовала беспрестанных усилий.
wordforms_score помещенье{ существительное }=-5 // Для обработки помещений ядами привлекают бомжей.
wordforms_score до{ существительное }=-5 // Санкционированная акция прошла с 16 до 17 часов.
wordforms_score ПАРКА{ существительное }=-5 // Королевские парки занимали обширную территорию.
wordforms_score НИМ{ существительное }=-5 // Василий, не отрываясь, следит за ним взглядом.
wordforms_score СТОЛА{ существительное }=-5 // На столе могут вырастать лужайки зеленой пищи.
wordforms_score низка { существительное }=-5
wordforms_score мешка{ существительное }=-5 // Мешки с углем один за другим полетели в темную воду.
wordforms_score стен { существительное }=-5 // По стенам развеваются блестящие знамена света.
wordforms_score ряда { существительное }=-5
wordforms_score так { существительное }=-5
wordforms_score снова { существительное }=-5
wordforms_score лагер { существительное }=-5
wordforms_score гор { существительное }=-5
wordforms_score карт { существительное }=-5 // Военные топографы и геодезисты сверяют карты.
wordforms_score зала { существительное }=-5
wordforms_score зало { существительное }=-5
wordforms_score миро { существительное }=-5 // В макротеле Мира отпечатывается мировая душа.
wordforms_score мира { существительное }=-5
wordforms_score облак { существительное }=-5 // По ночным облакам зарумянилось дымное зарево.
wordforms_score троп { существительное }=-5 // По берегу идут нерегулярные туристские тропы.
wordforms_score пещер { существительное }=-5
wordforms_score ко{ существительное }=-10 // Разумеется, ко мне он больше не показывался.
wordforms_score суда{ существительное }=-5 // В ближайшее время начнется его рассмотрение в суде.
wordform_score "то и дело" { наречие }=5 // Во всяком случае, не придется то и дело нагибаться.
wordform_score "воды" { число:мн } =-1 // они дали ему воды
wordform_score "лицо" { одуш:одуш } =-1
wordform_score "лица" { одуш:одуш } =-1 // Ему даже делают специальный массаж лица.
wordform_score "лицу" { одуш:одуш } =-1
wordform_score "лице" { одуш:одуш } =-1
wordform_score "лицом" { одуш:одуш } =-1
wordform_score "замок" { глагол } =-5 // замок на горе
wordform_score "самогонки" { число:мн } = -1 // Пришлось добавить самогонки.
wordform_score "интуиции" { число:мн } = -1 // Больше доверяют интуиции.
wordform_score "воды" { число:мн } = -1 // Джек добавил воды.
wordform_score "во" { вводное } = -2 // В детях эта программа усиливается во много раз.
wordform_score "на" { глагол } =-1 // В эфир выходили на несколько секунд.
wordform_score "веселей" { глагол } = -8 // В колонне веселей.
wordform_score "гранит" { глагол } = -3 // Почем гранит науки?
wordform_score "катя" { деепричастие } = -2 // Катя, давай!
wordform_score "прочь" { глагол } = -5 // пойти прочь
wordform_score "сволочь" { глагол } = -5 // - Сволочь!
wordform_score "юля" { деепричастие } = -2 // Юля, уважь человека.
wordform_score "катя" { деепричастие } = -2 // я направляюсь сюда, Катя.
wordform_score "женя" { деепричастие } = -2 // Я больше не буду, Женя.
wordform_score "нашей" { глагол } = -3 // - А вот и первые плоды нашей работы!
wordform_score "Камчатки" { число:мн } = -2 // К аварийной подстанции в столице Камчатки подключают новый трансформатор
wordform_score "воротам" { род:муж } = -2 // Беседуя, они подошли к воротам.
wordform_score "один" { существительное } = -5 // Значит, он не один.
wordform_score "то-то" { частица } = 2 // То-то выслуживается, вас гоняет.
wordform_score "погреб" { глагол } =-2 // А вот погреб...
wordform_score "просим" { прилагательное } = -5 // Просим всей группой.
wordform_score "крови" { число:мн } = -5 // Скорее разойдитесь, не проливая крови!
wordform_score "скоро" { прилагательное } = -4 // Скоро в строй?
wordform_score "подъем" { глагол } = -5 // Подъем, товарищ майор!
wordform_score "порой" { глагол } = -5 // И порой не без успеха.
wordform_score "порой" { существительное } = -1 // Они ворчат порой.
wordform_score "погоды" { число:мн } = -3 // По случаю чудной погоды Алексея тоже вывозили кататься.
wordform_score "дарим" { прилагательное} = -5 // - Решено, дарим один ящик командиру полка!
wordform_score "хватит" { глагол } = -1 // - На одну атаку хватит.
wordform_score "как ни в чем не бывало" { наречие } = 1 // Ординарец в сенях спал как ни в чем не бывало.
wordform_score "разве что" { наречие } = 1 // Так жарко бывает разве что перед грозой.
wordform_score "потому что" { союз } =5 // - Потому что мне так нравится.
wordform_score "на поводу у"{ предлог} = 1 // Нельзя идти на поводу у таких состояний
wordform_score "что" { наречие } = -8
wordform_score "так что" { наречие } = -5 // Ну, так что вы скажете?
wordform_score "вот" { наречие } = -3
wordform_score "Иду" { существительное } = -3 // - Иду к тебе!
wordform_score "хотите" { НАКЛОНЕНИЕ:ПОБУД } = -5
wordform_score "всего" { наречие } = -4 // Он всего боялся
wordform_score "всего лишь" { наречие } = 2
wordform_score "еле-еле" { наречие } = 2
wordform_score "туда-сюда" { наречие } = 2
wordform_score "туда-то" { наречие } = 2
wordform_score "отчего-то" { наречие } = 2
wordform_score "когда-то" { наречие } = 2
wordform_score "чуть-чуть" { наречие } = 2
wordform_score "так-то" { наречие } = 2
wordform_score "наконец-то" { наречие } = 2
wordform_score "туда-то" { наречие } = 2
wordform_score "тут-то" { наречие } = 2
wordform_score "Наконец-то" { наречие } = 2
wordform_score "добро" { наречие } = -4 // - Знаю я это добро.
wordform_score "должно" { наречие } = -5 // Но так и должно быть.
wordform_score "тем не менее" { наречие } = 1
wordform_score "прежде всего" { наречие } = 1 // Нужно прежде всего знать группу крови.
wordform_score "выходит" { наречие } = -2 // это из тебя страх так выходит
wordform_score "трибуны" { одуш:одуш } = -2 // Трибуны взрываются аплодисментами.
wordform_score "по прошествии" { предлог } = 5 // По прошествии двух дней следствие не может установить их личности.
wordform_score "сроком на" { предлог } = 2 // Аэропорт перешел в управление компании сроком на 30 лет.
// Я ничего подобного не видал
wordform_score "ничего" { наречие } = -5
// Не было таких прецедентов пока что.
// ^^^^^^^^
wordform_score "пока что" { наречие } = 1
wordform_score "приводим" { прилагательное } = -5 // Приводим полный текст этого заявления.
// Она поколебалась, прежде чем ответить.
// ^^^^^^^^^^
wordform_score "прежде чем" { союз } = 1
wordform_score "а то" { союз } = 1 // А то тебе плохо станет.
wordform_score "не то" { союз } = 1 // Вставай, не то опоздаем
wordform_score "а не то" { союз } = 1 // Сядь, а не то упадешь
// кости у всех одинаковые
// ^^^^^
wordform_score "кости" { глагол } = -3
wordform_score "чести" { глагол } = -3
// Мы знаем друг друга много лет
// ^^^^^^^^^^
wordform_score "друг друга" { существительное падеж:парт } = -1
// Текст речи премьер-министра
// ^^^^^^^^^^^^^^^^
wordform_score "премьер-министр" { существительное } = 1
wordform_score "премьер-министра" { существительное } = 1
wordform_score "премьер-министром" { существительное } = 1
wordform_score "премьер-министру" { существительное } = 1
wordform_score "премьер-министре" { существительное } = 1
wordform_score "премьер-министры" { существительное } = 1
wordform_score "премьер-министров" { существительное } = 1
wordform_score "премьер-министрами" { существительное } = 1
wordform_score "премьер-министрам" { существительное } = 1
wordform_score "премьер-министрах" { существительное } = 1
// Хотим получить максимум информации
// ^^^^^^^^^^
wordform_score "информации" { существительное число:мн } = -5
wordform_score "тому назад" { послелог } = 1
// Он просто вынужден закончить цикл историй, так как ограничены размеры книги.
wordform_score "так как" { союз } = 5
// Поможем ему сена накосить
// ^^^^
wordform_score "сена" { существительное число:мн } = -5
// Подавляем множественное число "ПУШОК":
// "Мы видели их пушки"
wordform_score "пушки" { существительное род:муж } = -5
wordform_score "это" { частица } = -2
// Кажется, вчера еще бродил я в этих рощах.
wordform_score "кажется" { наречие } = -2
wordform_score "лицом к лицу" { наречие } = 5
// из конюшни они возвращались бок о бок.
wordform_score "бок о бок" { наречие } = 2
// люди спят тем более.
wordform_score "тем более" { наречие } = 2
wordform_score "в связи с" { предлог } = 1
// то есть могла бы
wordform_score "то есть" { союз } = 3
// ПОКАДИТЬ(ПОКАЖУ)
// wordform_score "покажу" { глагол глагол:покадить{} } = -5
// ПРОПАСТЬ>ПРОПАЛИТЬ(ПРОПАЛИ)
wordform_score "пропали" { глагол наклонение:побуд } = -5
// ПОПАСТЬ > ПОПАЛИТЬ
wordform_score "попали" { глагол наклонение:побуд } = -5
// предпочитаем вариант безличного глагола:
//wordform_score "оставалось" { глагол } = -2
//wordform_score "остается" { глагол } = -2
//wordform_score "останется" { глагол } = -2
//wordform_score "осталось" { глагол } = -2
wordform_score "стали" { существительное число:мн } = -5
wordform_score "стали" { существительное падеж:род } = -3
// Жаль, если принятые обязательства не выполняются
// ^^^^
wordform_score "жаль" { глагол } = -3
wordform_score "давным-давно" { наречие } = 2
// Можно ли сейчас применять старые методы?
wordform_score "методам" { существительное род:жен } = -5
wordform_score "методах" { существительное род:жен } = -5
wordform_score "методу" { существительное род:жен } = -5
wordform_score "методе" { существительное род:жен } = -5
wordform_score "метода" { существительное род:жен } = -5
wordform_score "методы" { существительное род:жен } = -5
// Не вижу необходимости
// ^^^^^^^^^^^^^
wordform_score "необходимости" { число:мн } = -1
wordform_score "о" { частица } = -2
wordform_score "Спешите" { наклонение:побуд } = -1
// отдадим преимущество безличной форме:
// мне удалось поспать
// ^^^^^^^
wordform_score "удалось" { глагол } = -3
// Придавим вариант "ПАР^ОК"
// В парке был бассейн с золотыми рыбками.
// ^^^^^
wordform_score "парке" { ПЕРЕЧИСЛИМОСТЬ:НЕТ } = -10
// слово БЫЛО редко выступает в роли наречия, но иногда бывает:
// один из воинов пошел было к дверям
// ^^^^
wordform_score "было" { наречие } = -10
// Это было примерно месяц назад
wordform_score "примерно" { прилагательное } = -2
// чтобы подавить ВРЯД(ЛИ)
wordform_score "вряд ли" { наречие } = 2
// при помощи женской страсти?
// ^^^^^^^^^^
wordform_score "при помощи" { предлог } = 5
wordform_score "Владимиру" { существительное род:жен } = -2
wordform_score "Владимира" { существительное род:жен } = -2
wordform_score "Владимире" { существительное род:жен } = -2
// у тебя впереди серьезное дело
wordform_score "дело" { глагол } = -5
wordform_score "правды" { существительное число:мн } = -2
// ты сволочь
wordform_score "сволочь" { глагол } = -2
// во мне все же росло беспокойство
wordform_score "росло" { прилагательное } = -1
// конкуренция между ЗАБРАТЬ.гл и ЗАБРАЛО.сущ
wordform_score "забрала" { существительное } = -2
wordform_score "забрало" { существительное } = -2
wordform_score "забрал" { существительное } = -2
// обычно ЗАВТРА - наречие:
// можно зайти за этим завтра?
// ^^^^^^
wordform_score "завтра" { существительное } = -10
wordform_score "сегодня" { существительное } = -15
// взять деньги
wordform_score "деньги" { существительное падеж:род } = -10
// Подавляем просторечный вариант "Сашок"
// Сашка не знал
wordform_score "Сашка" { существительное падеж:вин } = -1
wordform_score "Сашка" { существительное падеж:род } = -1
// обычно это - прилагательное
wordform_score "простой" { глагол } = -1
// есть варианты ТУШЬ и ТУША (помимо глагола ТУШИТЬ). Вариант ТУШЬ гасим.
wordform_score "тушь" { существительное одуш:неодуш } = -5
// обычно ПОЧТИ - это наречие
// Почти совсем темно.
// ^^^^^
wordform_score "почти" { глагол } = -5
// теперь самое время бросить кости
wordform_score "кости" { глагол } = -5
wordform_score "брехло" { наречие } = -10
wordform_score "силой" { наречие } = -2
wordform_score "может" { вводное } = -1
// скорее доедай
wordform_score "скорее" { вводное } = -1
wordform_score "пять" { глагол } = -5
wordform_score "спины" { существительное род:муж } = -1
wordform_score "спинах" { существительное род:муж } = -1
wordform_score "спине" { существительное род:муж } = -1
// хозяин дает корм псам
wordform_score "корм" { существительное род:жен падеж:род } = -5
// несмотря на жару, солдаты носили шлемы и кирасы.
wordform_score "несмотря на" { предлог } = 10
// В соответствии с шариатом, свинину употреблять запрещено
// ^^^^^^^^^^^^^^^^
wordform_score "В соответствии с" { предлог } = 2
wordform_score "В соответствии со" { предлог } = 2
// В Дамаске в ходе ракетного обстрела погиб чиновник Евросоюза
// ^^^^^^
wordform_score "в ходе" { предлог } = 2
// Мы пошли вместе по направлению к городу.
// ^^^^^^^^^^^^^^^^
wordform_score "по направлению к" { предлог } = 2
wordform_score "по направлению ко" { предлог } = 2
// шеф просит еще раз проверить
// wordform_score "еще раз" { наречие } = 10
// очень трудно найти задачу по силам
wordform_score "по силам" { безлич_глагол } = -1
// есть все же средства
// ^^^^^^
wordform_score "все же" { наречие } = 10
// все время находился в командировках
// ^^^^^^^^^
//wordform_score "все время" { наречие } = 2
// Однако эти средства до сих пор не дошли до реального сектора экономики
wordform_score "до сих пор" { наречие } = 10
// сбыться на самом деле
wordform_score "на самом деле" { наречие } = 10
// Лошадь встала на дыбы.
wordform_score "встать на дыбы" { инфинитив } = 2
wordform_score "встала на дыбы" { глагол } = 2
wordform_score "встал на дыбы" { глагол } = 2
wordform_score "встали на дыбы" { глагол } = 2
wordform_score "встанет на дыбы" { глагол } = 2
wordform_score "пузырь" { глагол } = -2
// выражение его лица было довольно странным
wordform_score "довольно" { прилагательное } = -1
// они как будто пришли издалека
// ^^^^^^^^^
wordform_score "как будто" { наречие } = 2
// Лошадь встала на дыбы.
wordform_score "встать на дыбы" { глагол } = 2
// мой друг как всегда был прав
// ^^^^^^^^^^
wordform_score "как всегда" { наречие } = 2
// без кольца все стало как обычно
// ^^^^^^^^^^
wordform_score "как обычно" { наречие } = 2
// однако совершенно необходимо время от времени менять темп.
// ^^^^^^^^^^^^^^^^
wordform_score "время от времени" { наречие } = 5
// все равно уже сорвал
// ^^^^^^^^^
wordform_score "все равно" { наречие } = 10
// деревья полностью закрывают серое небо
// ^^^^^^^^^
wordform_score "полностью" { существительное } = -100
// волосы обоих были все еще мокрые.
// ^^^^^^^
wordform_score "все еще" { наречие } = 2
// всего один день.
wordform_score "день" { глагол } = -1
// ты все это прекрасно знаешь
// ^^^^^^^
wordform_score "все это" { местоим_сущ } = 1
// Андрюха хотел жить на отшибе
// ^^^^^^^^^
wordform_score "на отшибе" { наречие } = 1
// ПОЙМА vs ПОНЯТЬ
wordform_score "пойму" { существительное } = -1
// лучше всего сделать это сразу
// ^^^^^^^^^^^
wordform_score "лучше всего" { безлич_глагол } = 1
wordform_score "нахожусь" { глагол вид:соверш } = -2
wordform_score "находимся" { глагол вид:соверш } = -2
wordform_score "находится" { глагол вид:соверш } = -2
wordform_score "находитесь" { глагол вид:соверш } = -2
wordform_score "находился" { глагол вид:соверш } = -2
wordform_score "находилась" { глагол вид:соверш } = -2
wordform_score "находилось" { глагол вид:соверш } = -2
wordform_score "находились" { глагол вид:соверш } = -2
wordform_score "находим" { прилагательное } = -5 // В Полинезии находим культ черепов вождей.
wordform_score пошли { глагол время:прошедшее } = 1 // мы пошли домой
wordform_score пошли { глагол наклонение:побуд } = -1 // не пошли!
wordform_score спешить { инфинитив вид:несоверш } = 1 // спеш^ить (торопиться)
wordform_score спешил { глагол вид:несоверш }=1
wordform_score спешила { глагол вид:несоверш }=1
wordform_score спешили { глагол вид:несоверш }=1
wordform_score спеши { глагол вид:несоверш }=1
wordform_score спешить { инфинитив вид:соверш } =-2 // сп^ешить (спустить с коня на землю)
wordform_score спешил { глагол вид:соверш }=-2
wordform_score спешила { глагол вид:соверш }=-2
wordform_score спешили { глагол вид:соверш }=-2
wordform_score лето { существительное род:ср } = 1
wordform_score лёт { существительное род:муж } = -5
// Коля, давай-ка выпей молока
wordform_score выпей { глагол } = 1
wordform_score выпей { существительное } = -2
wordform_score видно { наречие } = -3
//wordform_score видно { прилагательное } = 0
//wordform_score видно { вводное } = -1
//wordform_score времени { существительное } = 1
wordform_score времени { глагол } = -5 // О факторе времени.
//wordform_score перед { предлог } = 1
wordform_score перед { существительное } = -2
wordform_score на { предлог } = 1
wordform_score на { частица } = -10
wordform_score жил { существительное } = -1 // жила
wordform_score жил { глагол } = 1 // жить
wordform_score любой { существительное } = -1 // Люба
wordform_score жал { существительное } = -10 // жало
wordform_score жал { глагол } = 1 // жать
wordform_score велик { прилагательное } = -1 // великий
wordform_score велика { существительное } = -10
wordform_score велика { прилагательное } = 1 // великий
wordform_score велики { существительное } = -10
wordform_score велики { прилагательное } = 1 // великий
wordform_score были { существительное } = -10
wordform_score были { глагол } = 1
wordform_score весь { существительное } = -10
wordform_score весь { глагол } = -10
wordform_score весь { прилагательное } = 1
wordform_score вещей { существительное } = 1
wordform_score вещей { прилагательное } = -1
wordform_score времени { глагол } = -10
wordform_score времени { существительное } = 1
//wordform_score все { местоим_сущ } = 1
//wordform_score все { прилагательное } = 1
wordform_score все { наречие } = -2
wordform_score все { частица } = -2
wordform_score всей { глагол } = -10
wordform_score всей { прилагательное } = 1
//wordform_score дали { глагол } = 1
wordform_score дали { существительное } = -1
//wordform_score смог { глагол } = 1
wordform_score смог { существительное } = -1
wordform_score действительно { прилагательное } = -10
wordform_score действительно { наречие } = 1
// wordform_score дел { существительное } = 1
// wordform_score дел { глагол } = 1
wordform_score дело { существительное } = 1
wordform_score дело { глагол } = -1
// wordform_score дела { существительное } = 1
// wordform_score дела { глагол } = 1
wordform_score день { существительное } = 1
wordform_score день { глагол } = -10
wordform_score для { предлог } = 1
wordform_score для { деепричастие } = -10
wordform_score какая { прилагательное } = 1
wordform_score какая { деепричастие } = -10
wordform_score конечно { прилагательное } = -1
wordform_score конечно { наречие } = 1
wordform_score мая { существительное одуш:неодуш } = 1
wordform_score мая { существительное одуш:одуш } = -1
wordform_score моря { существительное } = 1
wordform_score моря { деепричастие } = -10
wordform_score моя { прилагательное } = 1
wordform_score моя { деепричастие } = -10
wordform_score особой { прилагательное } = 1
wordform_score особой { существительное } = -1
wordform_score пора { существительное } = -1
wordform_score пора { безлич_глагол } = 1
wordform_score при { предлог } = 1
wordform_score при { глагол } = -10
wordform_score разрыв { существительное } = 1
wordform_score разрыв { деепричастие } = -1
wordform_score совести { существительное число:ед } = 1
wordform_score совести { существительное число:мн } = -5
wordform_score совести { глагол } = -2
wordform_score хвои { глагол } = -2 // Кубдя подбросил хвои.
wordform_score споров { существительное } = 1
wordform_score споров { деепричастие } = -1
wordform_score стать { существительное } = -1
wordform_score стать { инфинитив } = 1
wordform_score такая { деепричастие } = -10 // такать
wordform_score такая { прилагательное } = 1
wordform_score три { глагол } = -1 // тереть
wordform_score три { числительное } = 1
wordform_score тут { существительное одуш:неодуш } = -10 // тут (тутовое дерево)
wordform_score тут { наречие } = 1
wordform_score уж { частица } = 1
wordform_score уж { наречие } = 1
wordform_score уж { существительное } = -2
wordform_score уже { наречие степень:атриб } = 1
wordform_score уже { прилагательное } = -3 // узкий
wordform_score уже { существительное } = -2
wordform_score уже { наречие степень:сравн } = -5 // узко
wordform_score хотя { деепричастие } = -10 // хотеть
wordform_score хотя { союз } = 1
// краткие формы среднего рода прилагательных используются очень редко, в отличие
// от буквально совпадающих с ними наречий
#define PreferAdverb(x) \
#begin
//wordform_score x { наречие } = 2000000
wordform_score x { прилагательное } = -2
#end
PreferAdverb( "абсолютно" )
PreferAdverb( "абстрактно" )
PreferAdverb( "абсурдно" )
PreferAdverb( "аварийно" )
PreferAdverb( "автоматично" )
PreferAdverb( "авторитарно" )
PreferAdverb( "авторитетно" )
PreferAdverb( "азартно" )
PreferAdverb( "аккуратно" )
PreferAdverb( "активно" )
PreferAdverb( "актуально" )
PreferAdverb( "алогично" )
PreferAdverb( "амбивалентно" )
PreferAdverb( "аномально" )
PreferAdverb( "анонимно" )
PreferAdverb( "аргументировано" )
PreferAdverb( "аристократично" )
PreferAdverb( "архиважно" )
PreferAdverb( "аскетично" )
PreferAdverb( "афористично" )
PreferAdverb( "капризно" )
PreferAdverb( "кардинально" )
PreferAdverb( "карикатурно" )
PreferAdverb( "категорично" )
PreferAdverb( "качественно" )
PreferAdverb( "классно" )
PreferAdverb( "комично" )
PreferAdverb( "комфортабельно" )
PreferAdverb( "комфортно" )
PreferAdverb( "конвульсивно" )
PreferAdverb( "конечно" )
PreferAdverb( "конкретно" )
PreferAdverb( "конструктивно" )
PreferAdverb( "контрастно" )
PreferAdverb( "концептуально" )
PreferAdverb( "корректно" )
PreferAdverb( "кратковременно" )
PreferAdverb( "крестообразно" )
PreferAdverb( "кристально" )
PreferAdverb( "круглосуточно" )
PreferAdverb( "курьезно" )
PreferAdverb( "кучно" )
PreferAdverb( "комплиментарно" )
PreferAdverb( "агрессивно" )
PreferAdverb( "адекватно" )
PreferAdverb( "алчно" )
PreferAdverb( "амбициозно" )
PreferAdverb( "аморально" )
PreferAdverb( "аналогично" )
PreferAdverb( "анекдотично" )
PreferAdverb( "апатично" )
PreferAdverb( "аполитично" )
PreferAdverb( "артистично" )
PreferAdverb( "асимметрично" )
PreferAdverb( "ассоциативно" )
PreferAdverb( "красно" )
PreferAdverb( "конфиденциально" )
PreferAdverb( "клятвенно" )
PreferAdverb( "краткосрочно" )
PreferAdverb( "круглогодично" )
PreferAdverb( "когерентно" )
PreferAdverb( "конъюнктурно" )
PreferAdverb( "конформно" )
PreferAdverb( "асинхронно" )
PreferAdverb( "аритмично" )
PreferAdverb( "альтруистично" )
PreferAdverb( "критично" )
PreferAdverb( "авантюрно" )
PreferAdverb( "автобиографично" )
PreferAdverb( "автономно" )
PreferAdverb( "аддитивно" )
PreferAdverb( "ажурно" )
PreferAdverb( "азбучно" )
PreferAdverb( "академично" )
PreferAdverb( "аллегорично" )
PreferAdverb( "альтернативно" )
PreferAdverb( "аморфно" )
PreferAdverb( "антагонистично" )
PreferAdverb( "антинаучно" )
PreferAdverb( "антиобщественно" )
PreferAdverb( "аппетитно" )
PreferAdverb( "ароматно" )
PreferAdverb( "архаично" )
PreferAdverb( "атипично" )
PreferAdverb( "аутентично" )
PreferAdverb( "каверзно" )
PreferAdverb( "капитально" )
PreferAdverb( "каплеобразно" )
PreferAdverb( "катастрофично" )
PreferAdverb( "келейно" )
PreferAdverb( "клешнеобразно" )
PreferAdverb( "клиновидно" )
PreferAdverb( "клинообразно" )
PreferAdverb( "коварно" )
PreferAdverb( "комедийно" )
PreferAdverb( "консервативно" )
PreferAdverb( "конституционно" )
PreferAdverb( "конусовидно" )
PreferAdverb( "конусообразно" )
PreferAdverb( "корыстно" )
PreferAdverb( "косвенно" )
PreferAdverb( "косноязычно" )
PreferAdverb( "кошмарно" )
PreferAdverb( "кощунственно" )
PreferAdverb( "красочно" )
PreferAdverb( "криводушно" )
PreferAdverb( "кровожадно" )
PreferAdverb( "крохотно" )
PreferAdverb( "крупно" )
PreferAdverb( "культурно" )
PreferAdverb( "куполообразно" )
PreferAdverb( "кустарно" )
PreferAdverb( "акцентировано" )
/*-----------------------
select F1.name as word, Concat( '// ', C1.name, ':', E1.name, '{} и ', C2.name, ':', E2.name, '{}' )
from sg_entry E1, sg_entry E2, sg_form F1, sg_form F2, sg_class C1, sg_class C2
where E1.id_class!=E2.id_class and E1.name!='???' and
F1.id_entry=E1.id and F2.id_entry=E2.id and F1.name=F2.name and C1.id=E1.id_class and C2.id=E2.id_class and
E1.id<E2.id
order by F1.name
-------------------------*/
wordform_score "атакуем" { глагол } = 1 // ГЛАГОЛ:атаковать{} и ПРИЛАГАТЕЛЬНОЕ:атакуемый{}
wordform_score "атакуем" { прилагательное } = -10 // ГЛАГОЛ:атаковать{} и ПРИЛАГАТЕЛЬНОЕ:атакуемый{}
wordform_score "классифицируем" { глагол } = 1 // ГЛАГОЛ:классифицировать{} и ПРИЛАГАТЕЛЬНОЕ:классифицируемый{}
wordform_score "классифицируем" { прилагательное } = -10 // ГЛАГОЛ:классифицировать{} и ПРИЛАГАТЕЛЬНОЕ:классифицируемый{}
wordform_score "компенсируем" { глагол } = 1 // ГЛАГОЛ:компенсировать{} и ПРИЛАГАТЕЛЬНОЕ:компенсируемый{}
wordform_score "компенсируем" { прилагательное } = -10 // ГЛАГОЛ:компенсировать{} и ПРИЛАГАТЕЛЬНОЕ:компенсируемый{}
wordform_score "Коля" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:Коля{} и ДЕЕПРИЧАСТИЕ:коля{}
wordform_score "Коля" { ДЕЕПРИЧАСТИЕ } = -10 // СУЩЕСТВИТЕЛЬНОЕ:Коля{} и ГЛАГОЛ:колоть{}
wordform_score "Коли" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:Коля{} и СОЮЗ:коли{}
wordform_score "Коли" { ГЛАГОЛ } = -2 // СУЩЕСТВИТЕЛЬНОЕ:Коля{} и ГЛАГОЛ:колоть{}
wordform_score "Колю" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:Коля{} и ГЛАГОЛ:колоть{}
wordform_score "Колю" { ГЛАГОЛ } = -2 // СУЩЕСТВИТЕЛЬНОЕ:Коля{} и ГЛАГОЛ:колоть{}
wordform_score "Кати" { СУЩЕСТВИТЕЛЬНОЕ } = 2 // СУЩЕСТВИТЕЛЬНОЕ:Катя{} и ГЛАГОЛ:катить{}
wordform_score "Кати" { ГЛАГОЛ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:Катя{} и ГЛАГОЛ:катить{}
wordform_score "куплю" { СУЩЕСТВИТЕЛЬНОЕ } = -1 // СУЩЕСТВИТЕЛЬНОЕ:купля{} и ГЛАГОЛ:купить{}
wordform_score "куплю" { ГЛАГОЛ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:купля{} и ГЛАГОЛ:купить{}
wordform_score "крали" { СУЩЕСТВИТЕЛЬНОЕ } = -1 // СУЩЕСТВИТЕЛЬНОЕ:краля{} и ГЛАГОЛ:красть{}
wordform_score "крали" { ГЛАГОЛ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:краля{} и ГЛАГОЛ:красть{}
wordform_score "крести" { СУЩЕСТВИТЕЛЬНОЕ } = -2 // СУЩЕСТВИТЕЛЬНОЕ:крести{} и ГЛАГОЛ:крестить{}
wordform_score "крести" { ГЛАГОЛ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:крести{} и ГЛАГОЛ:крестить{}
wordform_score "крыло" { СУЩЕСТВИТЕЛЬНОЕ } = 1000000 // СУЩЕСТВИТЕЛЬНОЕ:крыло{} и ГЛАГОЛ:крыть{}
wordform_score "крыло" { ГЛАГОЛ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:крыло{} и ГЛАГОЛ:крыть{}
wordform_score "крыла" { СУЩЕСТВИТЕЛЬНОЕ } = 2 // СУЩЕСТВИТЕЛЬНОЕ:крыло{} и ГЛАГОЛ:крыть{}
wordform_score "крыла" { ГЛАГОЛ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:крыло{} и ГЛАГОЛ:крыть{}
wordform_score "крыло" { СУЩЕСТВИТЕЛЬНОЕ } = 2 // СУЩЕСТВИТЕЛЬНОЕ:крыло{} и ГЛАГОЛ:крыть{}
wordform_score "крыло" { ГЛАГОЛ } = -1 // СУЩЕСТВИТЕЛЬНОЕ:крыло{} и ГЛАГОЛ:крыть{}
wordform_score "ком" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:ком{} и МЕСТОИМ_СУЩ:кто{}
wordform_score "ком" { МЕСТОИМ_СУЩ } = 2 // СУЩЕСТВИТЕЛЬНОЕ:ком{} и МЕСТОИМ_СУЩ:кто{}
wordform_score "кому" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:ком{} и МЕСТОИМ_СУЩ:кто{}
wordform_score "кому" { МЕСТОИМ_СУЩ } = 2 // СУЩЕСТВИТЕЛЬНОЕ:ком{} и МЕСТОИМ_СУЩ:кто{}
wordform_score "Костя" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:Костя{} и ДЕЕПРИЧАСТИЕ:костя{}
wordform_score "Костя" { ДЕЕПРИЧАСТИЕ } = -10 // СУЩЕСТВИТЕЛЬНОЕ:Костя{} и ДЕЕПРИЧАСТИЕ:костя{}
wordform_score "кувырком" { СУЩЕСТВИТЕЛЬНОЕ } = -10 // СУЩЕСТВИТЕЛЬНОЕ:кувырок{} и НАРЕЧИЕ:кувырком{}
wordform_score "кувырком" { НАРЕЧИЕ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:кувырок{} и НАРЕЧИЕ:кувырком{}
wordform_score "колея" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:колея{} и ДЕЕПРИЧАСТИЕ:колея{}
wordform_score "колея" { ДЕЕПРИЧАСТИЕ } = -10 // СУЩЕСТВИТЕЛЬНОЕ:колея{} и ДЕЕПРИЧАСТИЕ:колея{}
wordform_score "качком" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:качок{} и ПРИЛАГАТЕЛЬНОЕ:качкий{}
wordform_score "качком" { ПРИЛАГАТЕЛЬНОЕ } = -10 // СУЩЕСТВИТЕЛЬНОЕ:качок{} и ПРИЛАГАТЕЛЬНОЕ:качкий{}
wordform_score "канал" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:канал{} и ГЛАГОЛ:канать{}
wordform_score "канал" { ГЛАГОЛ } = -2 // СУЩЕСТВИТЕЛЬНОЕ:канал{} и ГЛАГОЛ:канать{}
wordform_score "канала" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:канал{} и ГЛАГОЛ:канать{}
wordform_score "канала" { ГЛАГОЛ } = -2 // СУЩЕСТВИТЕЛЬНОЕ:канал{} и ГЛАГОЛ:канать{}
wordform_score "автостопом" { СУЩЕСТВИТЕЛЬНОЕ } = -1 // СУЩЕСТВИТЕЛЬНОЕ:автостоп{} и НАРЕЧИЕ:автостопом{}
wordform_score "автостопом" { НАРЕЧИЕ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:автостоп{} и НАРЕЧИЕ:автостопом{}
wordform_score "Ковровом" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:Ковров{} и ПРИЛАГАТЕЛЬНОЕ:ковровый{}
wordform_score "Ковровом" { ПРИЛАГАТЕЛЬНОЕ } = 2 // СУЩЕСТВИТЕЛЬНОЕ:Ковров{} и ПРИЛАГАТЕЛЬНОЕ:ковровый{}
wordform_score "кладу" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:клад{} и ГЛАГОЛ:класть{}
wordform_score "кладу" { ГЛАГОЛ } = 2 // СУЩЕСТВИТЕЛЬНОЕ:клад{} и ГЛАГОЛ:класть{}
wordform_score "клей" { СУЩЕСТВИТЕЛЬНОЕ } = 2 // СУЩЕСТВИТЕЛЬНОЕ:клей{} и ГЛАГОЛ:клеить{}
wordform_score "клей" { ГЛАГОЛ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:клей{} и ГЛАГОЛ:клеить{}
wordform_score "клея" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:клей{} и ДЕЕПРИЧАСТИЕ:клея{}
wordform_score "клея" { ДЕЕПРИЧАСТИЕ } = -2 // СУЩЕСТВИТЕЛЬНОЕ:клей{} и ДЕЕПРИЧАСТИЕ:клея{}
wordform_score "кубарем" { СУЩЕСТВИТЕЛЬНОЕ } = -10 // СУЩЕСТВИТЕЛЬНОЕ:кубарь{} и НАРЕЧИЕ:кубарем{}
wordform_score "кубарем" { НАРЕЧИЕ } = 2 // СУЩЕСТВИТЕЛЬНОЕ:кубарь{} и НАРЕЧИЕ:кубарем{}
wordform_score "калачиком" { СУЩЕСТВИТЕЛЬНОЕ } = -1 // СУЩЕСТВИТЕЛЬНОЕ:калачик{} и НАРЕЧИЕ:калачиком{}
wordform_score "калачиком" { НАРЕЧИЕ } = 2 // СУЩЕСТВИТЕЛЬНОЕ:калачик{} и НАРЕЧИЕ:калачиком{}
wordform_score "ковали" { СУЩЕСТВИТЕЛЬНОЕ } = -10 // СУЩЕСТВИТЕЛЬНОЕ:коваль{} и ГЛАГОЛ:ковать{}
wordform_score "ковали" { ГЛАГОЛ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:коваль{} и ГЛАГОЛ:ковать{}
wordform_score "Алле" { СУЩЕСТВИТЕЛЬНОЕ } = 2 // СУЩЕСТВИТЕЛЬНОЕ:Алла{} и ЧАСТИЦА:алле{}
wordform_score "Алле" { ЧАСТИЦА } = 1 // СУЩЕСТВИТЕЛЬНОЕ:Алла{} и ЧАСТИЦА:алле{}
wordform_score "кому" { СУЩЕСТВИТЕЛЬНОЕ } = -1 // СУЩЕСТВИТЕЛЬНОЕ:кома{} и МЕСТОИМ_СУЩ:кто{}
wordform_score "кому" { МЕСТОИМ_СУЩ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:кома{} и МЕСТОИМ_СУЩ:кто{}
wordform_score "кисла" { ПРИЛАГАТЕЛЬНОЕ } = 1 // ПРИЛАГАТЕЛЬНОЕ:кислый{} и ГЛАГОЛ:киснуть{}
wordform_score "кисла" { ГЛАГОЛ } = 2 // ПРИЛАГАТЕЛЬНОЕ:кислый{} и ГЛАГОЛ:киснуть{}
wordform_score "кисло" { наречие } = 2
wordform_score "кисло" { ПРИЛАГАТЕЛЬНОЕ } = -2 // ПРИЛАГАТЕЛЬНОЕ:кислый{} и ГЛАГОЛ:киснуть{}
wordform_score "кисло" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:кислый{} и ГЛАГОЛ:киснуть{}
wordform_score "конвертируем" { ПРИЛАГАТЕЛЬНОЕ } = -1 // ПРИЛАГАТЕЛЬНОЕ:конвертируемый{} и ГЛАГОЛ:конвертировать{}
wordform_score "конвертируем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:конвертируемый{} и ГЛАГОЛ:конвертировать{}
wordform_score "клади" { СУЩЕСТВИТЕЛЬНОЕ } = -2 // СУЩЕСТВИТЕЛЬНОЕ:кладь{} и ГЛАГОЛ:класть{}
wordform_score "клади" { ГЛАГОЛ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:кладь{} и ГЛАГОЛ:класть{}
wordform_score "копи" { СУЩЕСТВИТЕЛЬНОЕ } = -1 // СУЩЕСТВИТЕЛЬНОЕ:копь{} и ГЛАГОЛ:копить{}
wordform_score "копи" { ГЛАГОЛ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:копь{} и ГЛАГОЛ:копить{}
wordform_score "крепи" { СУЩЕСТВИТЕЛЬНОЕ } = -1 // СУЩЕСТВИТЕЛЬНОЕ:крепь{} и ГЛАГОЛ:крепить{}
wordform_score "крепи" { ГЛАГОЛ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:крепь{} и ГЛАГОЛ:крепить{}
wordform_score "крошку" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:крошка{} и НАРЕЧИЕ:крошку{}
wordform_score "крошку" { НАРЕЧИЕ } = -10 // СУЩЕСТВИТЕЛЬНОЕ:крошка{} и НАРЕЧИЕ:крошку{}
wordform_score "качкой" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:качка{} и ПРИЛАГАТЕЛЬНОЕ:качкий{}
wordform_score "качкой" { ПРИЛАГАТЕЛЬНОЕ } = -10 // СУЩЕСТВИТЕЛЬНОЕ:качка{} и ПРИЛАГАТЕЛЬНОЕ:качкий{}
wordform_score "какой" { СУЩЕСТВИТЕЛЬНОЕ } = -10 // СУЩЕСТВИТЕЛЬНОЕ:кака{} и ПРИЛАГАТЕЛЬНОЕ:какой{}
//wordform_score "какой" { ПРИЛАГАТЕЛЬНОЕ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:кака{} и ПРИЛАГАТЕЛЬНОЕ:какой{}
wordform_score "какою" { СУЩЕСТВИТЕЛЬНОЕ } = -10 // СУЩЕСТВИТЕЛЬНОЕ:кака{} и ПРИЛАГАТЕЛЬНОЕ:какой{}
wordform_score "какою" { ПРИЛАГАТЕЛЬНОЕ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:кака{} и ПРИЛАГАТЕЛЬНОЕ:какой{}
// СУЩЕСТВИТЕЛЬНОЕ:кака{} и СОЮЗ:как{}
wordform_score "как" { СОЮЗ } = 3
wordform_score "как" { НАРЕЧИЕ } = 2
wordform_score "как" { ЧАСТИЦА } = 1
wordform_score "как" { СУЩЕСТВИТЕЛЬНОЕ } = -10
wordform_score "ковка" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:ковка{} и ПРИЛАГАТЕЛЬНОЕ:ковкий{}
wordform_score "ковка" { ПРИЛАГАТЕЛЬНОЕ } = -1 // СУЩЕСТВИТЕЛЬНОЕ:ковка{} и ПРИЛАГАТЕЛЬНОЕ:ковкий{}
wordform_score "кучу" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:куча{} и ГЛАГОЛ:кутить{}
wordform_score "кучу" { ГЛАГОЛ } = -10 // СУЩЕСТВИТЕЛЬНОЕ:куча{} и ГЛАГОЛ:кутить{}
wordform_score "кручу" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:круча{} и ГЛАГОЛ:крутить{}
wordform_score "кручу" { ГЛАГОЛ } = 2 // СУЩЕСТВИТЕЛЬНОЕ:круча{} и ГЛАГОЛ:крутить{}
wordform_score "круче" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:круча{} и НАРЕЧИЕ:круто{}
wordform_score "круче" { НАРЕЧИЕ } = 2 // СУЩЕСТВИТЕЛЬНОЕ:круча{} и НАРЕЧИЕ:круто{}
wordform_score "круче" { ПРИЛАГАТЕЛЬНОЕ } = 2 // СУЩЕСТВИТЕЛЬНОЕ:круча{} и ПРИЛАГАТЕЛЬНОЕ:крутой{}
wordform_score "как" { СОЮЗ } = 3 // НАРЕЧИЕ:как{} и СУЩЕСТВИТЕЛЬНОЕ:кака{}
wordform_score "как" { НАРЕЧИЕ } = 2 // НАРЕЧИЕ:как{} и СУЩЕСТВИТЕЛЬНОЕ:кака{}
wordform_score "как" { ЧАСТИЦА } = 0 // НАРЕЧИЕ:как{} и СОЮЗ:как{}
wordform_score "как" { СУЩЕСТВИТЕЛЬНОЕ } = -10 // НАРЕЧИЕ:как{} и ЧАСТИЦА:как{}
wordform_score "кругом" { НАРЕЧИЕ } = 2 // НАРЕЧИЕ:кругом{} и СУЩЕСТВИТЕЛЬНОЕ:круг{}
wordform_score "кругом" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // НАРЕЧИЕ:кругом{} и СУЩЕСТВИТЕЛЬНОЕ:круг{}
wordform_score "кувырком" { НАРЕЧИЕ } = 2 // НАРЕЧИЕ:кувырком{} и СУЩЕСТВИТЕЛЬНОЕ:кувырок{}
wordform_score "кувырком" { СУЩЕСТВИТЕЛЬНОЕ } = -10 // НАРЕЧИЕ:кувырком{} и СУЩЕСТВИТЕЛЬНОЕ:кувырок{}
wordform_score "каплю" { НАРЕЧИЕ } = -10 // НАРЕЧИЕ:каплю{} и СУЩЕСТВИТЕЛЬНОЕ:капля{}
wordform_score "каплю" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // НАРЕЧИЕ:каплю{} и СУЩЕСТВИТЕЛЬНОЕ:капля{}
wordform_score "крошечку" { НАРЕЧИЕ } = -10 // НАРЕЧИЕ:крошечку{} и СУЩЕСТВИТЕЛЬНОЕ:крошечка{}
wordform_score "крошечку" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // НАРЕЧИЕ:крошечку{} и СУЩЕСТВИТЕЛЬНОЕ:крошечка{}
wordform_score "крошку" { НАРЕЧИЕ } = -10 // НАРЕЧИЕ:крошку{} и СУЩЕСТВИТЕЛЬНОЕ:крошка{}
wordform_score "крошку" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // НАРЕЧИЕ:крошку{} и СУЩЕСТВИТЕЛЬНОЕ:крошка{}
wordform_score "кубарем" { НАРЕЧИЕ } = 1 // НАРЕЧИЕ:кубарем{} и СУЩЕСТВИТЕЛЬНОЕ:кубарь{}
wordform_score "кубарем" { СУЩЕСТВИТЕЛЬНОЕ } = -10 // НАРЕЧИЕ:кубарем{} и СУЩЕСТВИТЕЛЬНОЕ:кубарь{}
wordform_score "кипуче" { НАРЕЧИЕ } = 1 // НАРЕЧИЕ:кипуче{} и ПРИЛАГАТЕЛЬНОЕ:кипучий{}
wordform_score "кипуче" { ПРИЛАГАТЕЛЬНОЕ } = -1 // НАРЕЧИЕ:кипуче{} и ПРИЛАГАТЕЛЬНОЕ:кипучий{}
wordform_score "куце" { НАРЕЧИЕ } = 1 // НАРЕЧИЕ:куце{} и ПРИЛАГАТЕЛЬНОЕ:куцый{}
wordform_score "куце" { ПРИЛАГАТЕЛЬНОЕ } = -1 // НАРЕЧИЕ:куце{} и ПРИЛАГАТЕЛЬНОЕ:куцый{}
wordform_score "антенной" { ПРИЛАГАТЕЛЬНОЕ } = 1 // ПРИЛАГАТЕЛЬНОЕ:антенный{} и СУЩЕСТВИТЕЛЬНОЕ:антенна{}
wordform_score "антенной" { СУЩЕСТВИТЕЛЬНОЕ } = 2 // ПРИЛАГАТЕЛЬНОЕ:антенный{} и СУЩЕСТВИТЕЛЬНОЕ:антенна{}
wordform_score "анализируем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:анализируемый{} и ГЛАГОЛ:анализировать{}
wordform_score "анализируем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:анализируемый{} и ГЛАГОЛ:анализировать{}
wordform_score "ассоциируем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:ассоциируемый{} и ГЛАГОЛ:ассоциировать{}
wordform_score "ассоциируем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:ассоциируемый{} и ГЛАГОЛ:ассоциировать{}
wordform_score "культивируем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:культивируемый{} и ГЛАГОЛ:культивировать{}
wordform_score "контролируем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:контролируемый{} и ГЛАГОЛ:контролировать{}
wordform_score "автоматизируем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:автоматизируемый{} и ГЛАГОЛ:автоматизировать{}
wordform_score "автоматизируем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:автоматизируемый{} и ГЛАГОЛ:автоматизировать{}
wordform_score "адаптируем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:адаптируемый{} и ГЛАГОЛ:адаптировать{}
wordform_score "адаптируем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:адаптируемый{} и ГЛАГОЛ:адаптировать{}
wordform_score "адресуем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:адресуемый{} и ГЛАГОЛ:адресовать{}
wordform_score "адресуем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:адресуемый{} и ГЛАГОЛ:адресовать{}
wordform_score "аккумулируем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:аккумулируемый{} и ГЛАГОЛ:аккумулировать{}
wordform_score "аккумулируем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:аккумулируемый{} и ГЛАГОЛ:аккумулировать{}
wordform_score "акцептуем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:акцептуемый{} и ГЛАГОЛ:акцептовать{}
wordform_score "акцептуем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:акцептуемый{} и ГЛАГОЛ:акцептовать{}
wordform_score "акционируем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:акционируемый{} и ГЛАГОЛ:акционировать{}
wordform_score "акционируем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:акционируемый{} и ГЛАГОЛ:акционировать{}
wordform_score "амортизируем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:амортизируемый{} и ГЛАГОЛ:амортизировать{}
wordform_score "амортизируем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:амортизируемый{} и ГЛАГОЛ:амортизировать{}
wordform_score "арендуем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:арендуемый{} и ГЛАГОЛ:арендовать{}
wordform_score "арендуем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:арендуемый{} и ГЛАГОЛ:арендовать{}
wordform_score "афишируем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:афишируемый{} и ГЛАГОЛ:афишировать{}
wordform_score "афишируем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:афишируемый{} и ГЛАГОЛ:афишировать{}
wordform_score "капитализируем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:капитализируемый{} и ГЛАГОЛ:капитализировать{}
wordform_score "капитализируем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:капитализируемый{} и ГЛАГОЛ:капитализировать{}
wordform_score "классифицируем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:классифицируемый{} и ГЛАГОЛ:классифицировать{}
wordform_score "классифицируем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:классифицируемый{} и ГЛАГОЛ:классифицировать{}
wordform_score "классифицируем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:классифицируемый{} и ГЛАГОЛ:классифицировать{}
wordform_score "классифицируем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:классифицируемый{} и ГЛАГОЛ:классифицировать{}
wordform_score "комментируем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:комментируемый{} и ГЛАГОЛ:комментировать{}
wordform_score "комментируем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:комментируемый{} и ГЛАГОЛ:комментировать{}
wordform_score "коммутируем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:коммутируемый{} и ГЛАГОЛ:коммутировать{}
wordform_score "коммутируем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:коммутируемый{} и ГЛАГОЛ:коммутировать{}
wordform_score "конвоируем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:конвоируемый{} и ГЛАГОЛ:конвоировать{}
wordform_score "конвоируем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:конвоируемый{} и ГЛАГОЛ:конвоировать{}
wordform_score "координируем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:координируемый{} и ГЛАГОЛ:координировать{}
wordform_score "координируем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:координируемый{} и ГЛАГОЛ:координировать{}
wordform_score "котируем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:котируемый{} и ГЛАГОЛ:котировать{}
wordform_score "котируем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:котируемый{} и ГЛАГОЛ:котировать{}
wordform_score "кредитуем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:кредитуемый{} и ГЛАГОЛ:кредитовать{}
wordform_score "кредитуем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:кредитуемый{} и ГЛАГОЛ:кредитовать{}
wordform_score "критикуем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:критикуемый{} и ГЛАГОЛ:критиковать{}
wordform_score "критикуем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:критикуемый{} и ГЛАГОЛ:критиковать{}
wordform_score "курируем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:курируемый{} и ГЛАГОЛ:курировать{}
wordform_score "курируем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:курируемый{} и ГЛАГОЛ:курировать{}
wordform_score "корректируем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:корректируемый{} и ГЛАГОЛ:корректировать{}
wordform_score "корректируем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:корректируемый{} и ГЛАГОЛ:корректировать{}
wordform_score "ковровом" { ПРИЛАГАТЕЛЬНОЕ } = 1 // ПРИЛАГАТЕЛЬНОЕ:ковровый{} и СУЩЕСТВИТЕЛЬНОЕ:Ковров{}
wordform_score "ковровом" { СУЩЕСТВИТЕЛЬНОЕ } = -1 // ПРИЛАГАТЕЛЬНОЕ:ковровый{} и СУЩЕСТВИТЕЛЬНОЕ:Ковров{}
wordform_score "кочевым" { ПРИЛАГАТЕЛЬНОЕ } = 1 // ПРИЛАГАТЕЛЬНОЕ:кочевой{} и СУЩЕСТВИТЕЛЬНОЕ:Кочево{}
wordform_score "кочевым" { СУЩЕСТВИТЕЛЬНОЕ } = -10 // ПРИЛАГАТЕЛЬНОЕ:кочевой{} и СУЩЕСТВИТЕЛЬНОЕ:Кочево{}
wordform_score "атакуем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:атакуемый{} и ГЛАГОЛ:атаковать{}
wordform_score "атакуем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:атакуемый{} и ГЛАГОЛ:атаковать{}
wordform_score "казним" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:казнимый{} и ГЛАГОЛ:казнить{}
wordform_score "казним" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:казнимый{} и ГЛАГОЛ:казнить{}
wordform_score "качаем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:качаемый{} и ГЛАГОЛ:качать{}
wordform_score "качаем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:качаемый{} и ГЛАГОЛ:качать{}
wordform_score "кусаем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:кусаемый{} и ГЛАГОЛ:кусать{}
wordform_score "кусаем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:кусаемый{} и ГЛАГОЛ:кусать{}
wordform_score "компенсируем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:компенсируемый{} и ГЛАГОЛ:компенсировать{}
wordform_score "компенсируем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:компенсируемый{} и ГЛАГОЛ:компенсировать{}
wordform_score "караем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:караемый{} и ГЛАГОЛ:карать{}
wordform_score "караем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:караемый{} и ГЛАГОЛ:карать{}
wordform_score "командируем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:командируемый{} и ГЛАГОЛ:командировать{}
wordform_score "командируем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:командируемый{} и ГЛАГОЛ:командировать{}
wordform_score "конструируем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:конструируемый{} и ГЛАГОЛ:конструировать{}
wordform_score "конструируем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:конструируемый{} и ГЛАГОЛ:конструировать{}
wordform_score "консультируем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:консультируемый{} и ГЛАГОЛ:консультировать{}
wordform_score "консультируем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:консультируемый{} и ГЛАГОЛ:консультировать{}
wordform_score "кидаем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:кидаемый{} и ГЛАГОЛ:кидать{}
wordform_score "кидаем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:кидаемый{} и ГЛАГОЛ:кидать{}
wordform_score "акцентируем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:акцентируемый{} и ГЛАГОЛ:акцентировать{}
wordform_score "акцентируем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:акцентируемый{} и ГЛАГОЛ:акцентировать{}
wordform_score "колонизируем" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:колонизируемый{} и ГЛАГОЛ:колонизировать{}
wordform_score "колонизируем" { ГЛАГОЛ } = 1 // ПРИЛАГАТЕЛЬНОЕ:колонизируемый{} и ГЛАГОЛ:колонизировать{}
wordform_score "крымском" { ПРИЛАГАТЕЛЬНОЕ } = 2 // ПРИЛАГАТЕЛЬНОЕ:крымский{} и СУЩЕСТВИТЕЛЬНОЕ:Крымск{}
wordform_score "крымском" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // ПРИЛАГАТЕЛЬНОЕ:крымский{} и СУЩЕСТВИТЕЛЬНОЕ:Крымск{}
wordform_score "каспийском" { ПРИЛАГАТЕЛЬНОЕ } = 2 // ПРИЛАГАТЕЛЬНОЕ:каспийский{} и СУЩЕСТВИТЕЛЬНОЕ:Каспийск{}
wordform_score "каспийском" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // ПРИЛАГАТЕЛЬНОЕ:каспийский{} и СУЩЕСТВИТЕЛЬНОЕ:Каспийск{}
wordform_score "амурском" { ПРИЛАГАТЕЛЬНОЕ } = 2 // ПРИЛАГАТЕЛЬНОЕ:амурский{} и СУЩЕСТВИТЕЛЬНОЕ:Амурск{}
wordform_score "амурском" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // ПРИЛАГАТЕЛЬНОЕ:амурский{} и СУЩЕСТВИТЕЛЬНОЕ:Амурск{}
wordform_score "архангельском" { ПРИЛАГАТЕЛЬНОЕ } = 2 // ПРИЛАГАТЕЛЬНОЕ:архангельский{} и СУЩЕСТВИТЕЛЬНОЕ:Архангельск{}
wordform_score "архангельском" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // ПРИЛАГАТЕЛЬНОЕ:архангельский{} и СУЩЕСТВИТЕЛЬНОЕ:Архангельск{}
wordform_score "курильском" { ПРИЛАГАТЕЛЬНОЕ } = 2 // ПРИЛАГАТЕЛЬНОЕ:курильский{} и СУЩЕСТВИТЕЛЬНОЕ:Курильск{}
wordform_score "курильском" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // ПРИЛАГАТЕЛЬНОЕ:курильский{} и СУЩЕСТВИТЕЛЬНОЕ:Курильск{}
wordform_score "кировском" { ПРИЛАГАТЕЛЬНОЕ } = 2 // ПРИЛАГАТЕЛЬНОЕ:кировский{} и СУЩЕСТВИТЕЛЬНОЕ:Кировск{}
wordform_score "кировском" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // ПРИЛАГАТЕЛЬНОЕ:кировский{} и СУЩЕСТВИТЕЛЬНОЕ:Кировск{}
wordform_score "козельском" { ПРИЛАГАТЕЛЬНОЕ } = 2 // ПРИЛАГАТЕЛЬНОЕ:козельский{} и СУЩЕСТВИТЕЛЬНОЕ:Козельск{}
wordform_score "козельском" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // ПРИЛАГАТЕЛЬНОЕ:козельский{} и СУЩЕСТВИТЕЛЬНОЕ:Козельск{}
wordform_score "курском" { ПРИЛАГАТЕЛЬНОЕ } = 2 // ПРИЛАГАТЕЛЬНОЕ:курский{} и СУЩЕСТВИТЕЛЬНОЕ:Курск{}
wordform_score "курском" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // ПРИЛАГАТЕЛЬНОЕ:курский{} и СУЩЕСТВИТЕЛЬНОЕ:Курск{}
wordform_score "калининском" { ПРИЛАГАТЕЛЬНОЕ } = 2 // ПРИЛАГАТЕЛЬНОЕ:калининский{} и СУЩЕСТВИТЕЛЬНОЕ:Калининск{}
wordform_score "калининском" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // ПРИЛАГАТЕЛЬНОЕ:калининский{} и СУЩЕСТВИТЕЛЬНОЕ:Калининск{}
wordform_score "красноярском" { ПРИЛАГАТЕЛЬНОЕ } = 2 // ПРИЛАГАТЕЛЬНОЕ:красноярский{} и СУЩЕСТВИТЕЛЬНОЕ:Красноярск{}
wordform_score "красноярском" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // ПРИЛАГАТЕЛЬНОЕ:красноярский{} и СУЩЕСТВИТЕЛЬНОЕ:Красноярск{}
wordform_score "качкой" { ПРИЛАГАТЕЛЬНОЕ } = 1 // ПРИЛАГАТЕЛЬНОЕ:качкий{} и СУЩЕСТВИТЕЛЬНОЕ:качка{}
wordform_score "качкой" { СУЩЕСТВИТЕЛЬНОЕ } = 2 // ПРИЛАГАТЕЛЬНОЕ:качкий{} и СУЩЕСТВИТЕЛЬНОЕ:качка{}
wordform_score "качкою" { ПРИЛАГАТЕЛЬНОЕ } = 1 // ПРИЛАГАТЕЛЬНОЕ:качкий{} и СУЩЕСТВИТЕЛЬНОЕ:качка{}
wordform_score "качкою" { СУЩЕСТВИТЕЛЬНОЕ } = 2 // ПРИЛАГАТЕЛЬНОЕ:качкий{} и СУЩЕСТВИТЕЛЬНОЕ:качка{}
wordform_score "качком" { ПРИЛАГАТЕЛЬНОЕ } = 1 // ПРИЛАГАТЕЛЬНОЕ:качкий{} и СУЩЕСТВИТЕЛЬНОЕ:качок{}
wordform_score "качком" { СУЩЕСТВИТЕЛЬНОЕ } = 2 // ПРИЛАГАТЕЛЬНОЕ:качкий{} и СУЩЕСТВИТЕЛЬНОЕ:качок{}
wordform_score "адыгейском" { ПРИЛАГАТЕЛЬНОЕ } = 2 // ПРИЛАГАТЕЛЬНОЕ:адыгейский{} и СУЩЕСТВИТЕЛЬНОЕ:Адыгейск{}
wordform_score "адыгейском" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // ПРИЛАГАТЕЛЬНОЕ:адыгейский{} и СУЩЕСТВИТЕЛЬНОЕ:Адыгейск{}
wordform_score "комсомольском" { ПРИЛАГАТЕЛЬНОЕ } = 2 // ПРИЛАГАТЕЛЬНОЕ:комсомольский{} и СУЩЕСТВИТЕЛЬНОЕ:Комсомольск{}
wordform_score "комсомольском" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // ПРИЛАГАТЕЛЬНОЕ:комсомольский{} и СУЩЕСТВИТЕЛЬНОЕ:Комсомольск{}
wordform_score "апшеронском" { ПРИЛАГАТЕЛЬНОЕ } = 2 // ПРИЛАГАТЕЛЬНОЕ:апшеронский{} и СУЩЕСТВИТЕЛЬНОЕ:Апшеронск{}
wordform_score "апшеронском" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // ПРИЛАГАТЕЛЬНОЕ:апшеронский{} и СУЩЕСТВИТЕЛЬНОЕ:Апшеронск{}
wordform_score "тайна" { ПРИЛАГАТЕЛЬНОЕ } = -5 // ПРИЛАГАТЕЛЬНОЕ:тайный{}
wordform_score "тайна" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // СУЩЕСТВИТЕЛЬНОЕ:тайна{}
wordform_score "коробило" { БЕЗЛИЧ_ГЛАГОЛ } = 1 // БЕЗЛИЧ_ГЛАГОЛ:коробит{} и ГЛАГОЛ:коробить{}
wordform_score "коробило" { ГЛАГОЛ } = -2 // БЕЗЛИЧ_ГЛАГОЛ:коробит{} и ГЛАГОЛ:коробить{}
wordform_score "коробит" { БЕЗЛИЧ_ГЛАГОЛ } = 1 // БЕЗЛИЧ_ГЛАГОЛ:коробит{} и ГЛАГОЛ:коробить{}
wordform_score "коробит" { ГЛАГОЛ } = -2 // БЕЗЛИЧ_ГЛАГОЛ:коробит{} и ГЛАГОЛ:коробить{}
wordform_score "казалось" { БЕЗЛИЧ_ГЛАГОЛ } = 1 // БЕЗЛИЧ_ГЛАГОЛ:кажется{} и ГЛАГОЛ:казаться{}
wordform_score "казалось" { ГЛАГОЛ } = -2 // БЕЗЛИЧ_ГЛАГОЛ:кажется{} и ГЛАГОЛ:казаться{}
wordform_score "канал" { ГЛАГОЛ } = -5 // ГЛАГОЛ:канать{} и СУЩЕСТВИТЕЛЬНОЕ:канал{}
wordform_score "канал" { СУЩЕСТВИТЕЛЬНОЕ } = 1 // ГЛАГОЛ:канать{} и СУЩЕСТВИТЕЛЬНОЕ:канал{}
wordform_score "канала" { ГЛАГОЛ } = 1 // ГЛАГОЛ:канать{} и СУЩЕСТВИТЕЛЬНОЕ:канал{}
wordform_score "канала" { СУЩЕСТВИТЕЛЬНОЕ } = 1000000 // ГЛАГОЛ:канать{} и СУЩЕСТВИТЕЛЬНОЕ:канал{}
wordform_score "чай" { ГЛАГОЛ } = -10 // чаять
wordform_score "чай" { СУЩЕСТВИТЕЛЬНОЕ } = 0 // чай
wordform_score "чай" { частица } = -2 // чай
wordform_score "чай" { наречие } = -5
wordform_score "готов" { прилагательное } = 1
wordform_score "готов" { существительное } = -1
wordform_score "извести" { инфинитив } = -1
wordform_score "извести" { существительное } = 1
wordform_score "нашли" { наклонение:изъяв } = 1
wordform_score "нашли" { наклонение:побуд } = -5
// ----
wordform_score "брехни" { глагол } = -1 // брехня брехни --> брехнуть брехни
wordform_score "бузил" { существительное } = -1 // бузила бузил --> бузить бузил
wordform_score "бурей" { глагол } = -1 // буря бурей --> буреть бурей
wordform_score "бюллетень" { глагол } = -1 // бюллетень бюллетень --> бюллетенить бюллетень
wordform_score "возрасту" { глагол } = -1 // возраст возрасту --> возрасти возрасту
wordform_score "воплю" { глагол } = -1 // вопль воплю --> вопить воплю
wordform_score "врали" { существительное } = -1 // враль врали --> врать врали
wordform_score "гвозди" { глагол } = -1 // гвоздь гвозди --> гвоздить гвозди
wordform_score "Глашу" { глагол } = -1 // Глаша Глашу --> гласить глашу
wordform_score "голубей" { глагол } = -1 // голубь голубей --> голубеть голубей
wordform_score "гряду" { глагол } = -1 // гряда гряду --> грясти гряду
wordform_score "Дорою" { существительное } = -1 // Дора Дорою --> дорыть дорою
wordform_score "дох" { глагол } = -1 // доха дох --> дохнуть дох
wordform_score "драконят" { существительное } = -1 // драконенок драконят --> драконить драконят
wordform_score "дублю" { глагол } = -1 // дубль дублю --> дубить дублю
wordform_score "дули" { существительное } = -1 // дуля дули --> дуть дули
wordform_score "ежу" { глагол } = -1 // еж ежу --> ежить ежу
wordform_score "жал" { существительное } = -1 // жало жал --> жать жал
wordform_score "жигану" { глагол } = -1 // жиган жигану --> жигануть жигану
wordform_score "завали" { существительное } = -1 // заваль завали --> завалить завали
wordform_score "замшей" { глагол } = -1 // замша замшей --> замшеть замшей
wordform_score "зарей" { глагол } = -1 // заря зарей --> зареять зарей
wordform_score "затей" { глагол } = -1 // затея затей --> затеять затей
wordform_score "затею" { глагол } = -1 // затея затею --> затеять затею
wordform_score "затону" { существительное } = -1 // затон затону --> затонуть затону
wordform_score "знахарю" { глагол } = -1 // знахарь знахарю --> знахарить знахарю
wordform_score "изморозь" { глагол } = -1 // изморозь изморозь --> изморозить изморозь
wordform_score "канитель" { глагол } = -1 // канитель канитель --> канителить канитель
wordform_score "ковали" { существительное } = -1 // коваль ковали --> ковать ковали
wordform_score "кучу" { глагол } = -1 // куча кучу --> кутить кучу
wordform_score "лохмачу" { существительное } = -1 // лохмач лохмачу --> лохматить лохмачу
wordform_score "матерей" { глагол } = -5 // мать матерей --> матереть матерей
wordform_score "матери" { глагол } = -5 // мать матери --> материть матери
wordform_score "метель" { глагол } = -1 // метель метель --> метелить метель
wordform_score "мини" { глагол } = -1 // мини мини --> минуть мини
wordform_score "минут" { глагол } = -1 // минута минут --> минуть минут
wordform_score "молоди" { глагол } = -1 // молодь молоди --> молодить молоди
wordform_score "батрачат" { существительное } = -1 // батрачонок батрачат --> батрачить батрачат
wordform_score "бузила" { существительное } = -1 // бузила бузила --> бузить бузила
wordform_score "времени" { глагол } = -1 // время времени --> временить времени
wordform_score "дурней" { глагол } = -1 // дурень дурней --> дурнеть дурней
wordform_score "наймите" { существительное } = -1 // наймит наймите --> нанять наймите
wordform_score "накипи" { глагол } = -1 // накипь накипи --> накипеть накипи
wordform_score "нарвал" { существительное } = -1 // нарвал нарвал --> нарвать нарвал
wordform_score "нарвала" { существительное } = -1 // нарвал нарвала --> нарвать нарвала
wordform_score "нарой" { существительное } = -1 // нара нарой --> нарыть нарой
wordform_score "пари" { глагол } = -1 // пари пари --> парить пари
wordform_score "пастушат" { глагол } = -1 // пастушонок пастушат --> пастушить пастушат
wordform_score "пасу" { существительное } = -1 // пас пасу --> пасти пасу
wordform_score "пень" { глагол } = -1 // пень пень --> пенить пень
wordform_score "пеню" { глагол } = -1 // пеня пеню --> пенить пеню
wordform_score "передам" { существительное } = -1 // перед передам --> передать передам
wordform_score "печаль" { глагол } = -1 // печаль печаль --> печалить печаль
wordform_score "подтеки" { глагол } = -1 // подтек подтеки --> подтечь подтеки
wordform_score "постригу" { существительное } = -1 // постриг постригу --> постричь постригу
wordform_score "проем" { глагол } = -1 // проем проем --> проесть проем
wordform_score "простой" { глагол } = -1 // простой простой --> простоять простой
wordform_score "пряди" { глагол } = -1 // прядь пряди --> прясть пряди
wordform_score "разъем" { глагол } = -1 // разъем разъем --> разъесть разъем
wordform_score "ржу" { существительное } = -1 // ржа ржу --> ржать ржу
wordform_score "ругани" { глагол } = -1 // ругань ругани --> ругануть ругани
wordform_score "сбои" { глагол } = -1 // сбой сбои --> сбоить сбои
wordform_score "секретарь" { глагол } = -1 // секретарь секретарь --> секретарить секретарь
wordform_score "скину" { существительное } = -1 // скин скину --> скинуть скину
wordform_score "слесарь" { глагол } = -1 // слесарь слесарь --> слесарить слесарь
wordform_score "случаем" { глагол } = -1 // случай случаем --> случать случаем
wordform_score "соловей" { глагол } = -1 // соловей соловей --> соловеть соловей
wordform_score "спирали" { глагол } = -1 // спираль спирали --> спирать спирали
wordform_score "старь" { глагол } = -1 // старь старь --> старить старь
wordform_score "струи" { глагол } = -1 // струя струи --> струить струи
wordform_score "такелажу" { глагол } = -1 // такелаж такелажу --> такелажить такелажу
wordform_score "участи" { глагол } = -1 // участь участи --> участить участи
wordform_score "хмелю" { глагол } = -10 // хмель хмелю --> хмелить хмелю
wordform_score "чаем" { глагол } = -10 // чай чаем --> чаять чаем
wordform_score "замшею" { глагол } = -1 // замша замшею --> замшеть замшею
wordform_score "зелени" { глагол } = -1 // зелень зелени --> зеленить зелени
wordform_score "знахарь" { глагол } = -1 // знахарь знахарь --> знахарить знахарь
wordform_score "канифоль" { глагол } = -1 // канифоль канифоль --> канифолить канифоль
wordform_score "лужу" { глагол } = -1 // лужа лужу --> лудить лужу
wordform_score "матерей" { глагол } = -1 // матерь матерей --> матереть матерей
wordform_score "матери" { глагол } = -1 // матерь матери --> материть матери
wordform_score "мелей" { глагол } = -1 // мель мелей --> мелеть мелей
wordform_score "мыло" { глагол } = -1 // мыло мыло --> мыть мыло
wordform_score "обезьянят" { существительное } = -1 // обезьяненок обезьянят --> обезьянить обезьянят
wordform_score "объем" { глагол } = -1 // объем объем --> объесть объем
wordform_score "осени" { глагол } = -1 // осень осени --> осенить осени
wordform_score "отмели" { глагол } = -1 // отмель отмели --> отмолоть отмели
wordform_score "перла" { существительное } = -1 // перл перла --> переть перла
wordform_score "пил" { существительное } = -1 // пила пил --> пить пил
wordform_score "пищали" { существительное } = -1 // пищаль пищали --> пищать пищали
wordform_score "поволок" { существительное } = -1 // поволока поволок --> поволочь поволок
wordform_score "поволоку" { существительное } = -1 // поволока поволоку --> поволочь поволоку
wordform_score "покой" { глагол } = -5 // покой покой --> покоить покой
wordform_score "покою" { глагол } = -5 // покой покою --> покоить покою
wordform_score "полет" { глагол } = -1 // полет полет --> полоть полет
wordform_score "полете" { глагол } = -1 // полет полете --> полоть полете
wordform_score "полю" { глагол } = -1 // поле полю --> полоть полю
wordform_score "примеси" { глагол } = -1 // примесь примеси --> примесить примеси
wordform_score "примету" { глагол } = -1 // примета примету --> примести примету
wordform_score "припас" { существительное } = -1 // припас припас --> припасти припас
wordform_score "продела" { существительное } = -1 // продел продела --> продеть продела
wordform_score "просек" { существительное } = -1 // просека просек --> просечь просек
wordform_score "пущу" { существительное } = -1 // пуща пущу --> пустить пущу
wordform_score "пьяни" { глагол } = -1 // пьянь пьяни --> пьянить пьяни
wordform_score "сбою" { глагол } = -1 // сбой сбою --> сбоить сбою
wordform_score "свечу" { глагол } = -1 // свеча свечу --> светить свечу
wordform_score "секретарю" { глагол } = -1 // секретарь секретарю --> секретарить секретарю
wordform_score "случай" { глагол } = -5 // случай случай --> случать случай
wordform_score "случаю" { глагол } = -5 // случай случаю --> случать случаю
wordform_score "слюни" { глагол } = -1 // слюна слюни --> слюнить слюни
wordform_score "смог" { существительное } = -1 // смог смог --> смочь смог
wordform_score "смогу" { существительное } = -1 // смог смогу --> смочь смогу
wordform_score "собачат" { существительное } = -1 // собаченок собачат --> собачить собачат
wordform_score "совести" { глагол } = -1 // совесть совести --> совестить совести
wordform_score "спас" { существительное } = -1 // спас спас --> спасти спас
wordform_score "стай" { глагол } = -1 // стая стай --> стаять стай
wordform_score "стаю" { глагол } = -1 // стая стаю --> стаять стаю
wordform_score "струю" { глагол } = -1 // струя струю --> струить струю
wordform_score "стужу" { глагол } = -1 // стужа стужу --> студить стужу
wordform_score "сучат" { существительное } = -1 // сучонок сучат --> сучить сучат
wordform_score "тлей" { глагол } = -1 // тля тлей --> тлеть тлей
wordform_score "толщу" { глагол } = -1 // толща толщу --> толстить толщу
wordform_score "царю" { глагол } = -4 // царь царю --> царить царю ==> Ну а поздно вечером довелось удивиться и царю.
wordform_score "чащу" { глагол } = -1 // чаща чащу --> частить чащу
wordform_score "чаю" { глагол } = -10 // чай чаю --> чаять чаю
wordform_score "ширь" { глагол } = -1 // ширь ширь --> ширить ширь
wordform_score "штурману" { глагол } = -1 // штурман штурману --> штурмануть штурману
wordform_score "щурят" { существительное } = -1 // щуренок щурят --> щурить щурят
wordform_score "гноя" { деепричастие } = -4 // гной гноя --> гноя гноя
wordform_score "гостя" { деепричастие } = -1 // гость гостя --> гостя гостя
wordform_score "душа" { деепричастие } = -1 // душ душа --> душа душа
wordform_score "катя" { деепричастие } = -4 // Катя Катя --> катя катя
wordform_score "колея" { деепричастие } = -1 // колея колея --> колея колея
wordform_score "костя" { деепричастие } = -1 // Костя Костя --> костя костя
wordform_score "нарыв" { деепричастие } = -1 // нарыв нарыв --> нарыв нарыв
wordform_score "отлив" { деепричастие } = -1 // отлив отлив --> отлив отлив
wordform_score "отпоров" { существительное } = -1 // отпор отпоров --> отпоров отпоров
wordform_score "отрыв" { деепричастие } = -1 // отрыв отрыв --> отрыв отрыв
wordform_score "подлив" { существительное } = -1 // подлива подлив --> подлив подлив
wordform_score "покоя" { деепричастие } = -1 // покой покоя --> покоя покоя
wordform_score "прилив" { деепричастие } = -1 // прилив прилив --> прилив прилив
wordform_score "пузыря" { деепричастие } = -1 // пузырь пузыря --> пузыря пузыря
wordform_score "руля" { деепричастие } = -1 // руль руля --> руля руля
wordform_score "селя" { деепричастие } = -1 // сель селя --> селя селя
wordform_score "случая" { деепричастие } = -1 // случай случая --> случая случая
wordform_score "сторожа" { деепричастие } = -1 // сторож сторожа --> сторожа сторожа
wordform_score "суша" { деепричастие } = -1 // суша суша --> суша суша
wordform_score "туша" { деепричастие } = -1 // туш туша --> туша туша
wordform_score "хмеля" { деепричастие } = -1 // хмель хмеля --> хмеля хмеля
wordform_score "валя" { деепричастие } = -1 // Валя Валя --> валя валя
wordform_score "варя" { деепричастие } = -1 // Варя Варя --> варя варя
wordform_score "гвоздя" { деепричастие } = -1 // гвоздь гвоздя --> гвоздя гвоздя
wordform_score "голубя" { деепричастие } = -1 // голубь голубя --> голубя голубя
wordform_score "горя" { деепричастие } = -1 // горе горя --> горя горя
wordform_score "клея" { деепричастие } = -1 // клей клея --> клея клея
wordform_score "неволя" { деепричастие } = -1 // неволя неволя --> неволя неволя
wordform_score "отколов" { существительное } = -1 // откол отколов --> отколов отколов
wordform_score "переборов" { существительное } = -1 // перебор переборов --> переборов переборов
wordform_score "подлив" { существительное } = -1 // подлив подлив --> подлив подлив
wordform_score "подрыв" { деепричастие } = -1 // подрыв подрыв --> подрыв подрыв
wordform_score "полив" { деепричастие } = -1 // полив полив --> полив полив
wordform_score "пошив" { деепричастие } = -1 // пошив пошив --> пошив пошив
wordform_score "чая" { деепричастие } = -10 // чай чая --> чая чая
wordform_score "струя" { деепричастие } = -1 // струя струя --> струя струя
wordform_score "белков" { прилагательное } = -1 // белок белков --> белковый белков
wordform_score "витой" { существительное } = -1 // Вита Витой --> витой витой
wordform_score "вожатом" { прилагательное } = -1 // вожатый вожатом --> вожатый вожатом
wordform_score "вожатым" { прилагательное } = -1 // вожатый вожатым --> вожатый вожатым
wordform_score "вожатых" { прилагательное } = -1 // вожатый вожатых --> вожатый вожатых
wordform_score "гола" { прилагательное } = -1 // гол гола --> голый гола
wordform_score "вороной" { прилагательное } = -1 // ворона вороной --> вороной вороной
wordform_score "голы" { прилагательное } = -1 // гол голы --> голый голы
wordform_score "гусиной" { существительное } = -1 // Гусина Гусиной --> гусиный гусиной
wordform_score "гусиным" { существительное } = -1 // Гусин Гусиным --> гусиный гусиным
wordform_score "гусиными" { существительное } = -1 // Гусин Гусиными --> гусиный гусиными
wordform_score "добро" { прилагательное } = -1 // добро добро --> добрый добро
wordform_score "долги" { прилагательное } = -1 // долг долги --> долгий долги
wordform_score "готов" { существительное } = -1 // гот готов --> готовый готов
wordform_score "звонки" { прилагательное } = -1 // звонок звонки --> звонкий звонки
wordform_score "звонок" { прилагательное } = -1 // звонок звонок --> звонкий звонок
wordform_score "лаком" { прилагательное } = -1 // лак лаком --> лакомый лаком
wordform_score "лев" { прилагательное } = -1 // лев лев --> левый лев
wordform_score "лишаем" { прилагательное } = -1 // лишай лишаем --> лишаемый лишаем
wordform_score "сладка" { существительное } = -10 // сладка сладка --> сладкий сладка
wordform_score "сладкой" { существительное } = -1 // сладка сладкой --> сладкий сладкой
wordform_score "сладкою" { существительное } = -1 // сладка сладкою --> сладкий сладкою
wordform_score "сладок" { существительное } = -1 // сладка сладок --> сладкий сладок
wordform_score "темен" { существительное } = -1 // темя темен --> темный темен
wordform_score "тонной" { прилагательное } = -1 // тонна тонной --> тонный тонной
wordform_score "ужат" { существительное } = -1 // ужонок ужат --> ужатый ужат
wordform_score "этой" { существительное } = -5 // эта этой --> этот этой
wordform_score "рада" { существительное } = -1 // Рада Рада --> рад рада
wordform_score "рады" { существительное } = -1 // Рада Рады --> рад рады
wordform_score "столиком" { прилагательное } = -1 // столик столиком --> столикий столиком
wordform_score "теми" { существительное } = -1 // темь теми --> тот теми
wordform_score "тонною" { прилагательное } = -1 // тонна тонною --> тонный тонною
wordform_score "ужата" { существительное } = -1 // ужонок ужата --> ужатый ужата
wordform_score "эта" { существительное } = -3 // эта эта --> этот эта
wordform_score "этою" { существительное } = -1 // эта этою --> этот этою
wordform_score "эту" { существительное } = -3 // эта эту --> этот эту
// ------------------------
// Для имен и некоторых существительных на -ИЕ варианты множественного числа
// обычно не употребляются, поэтому мы можем априори предположить пониженную достоверность.
// Этот макрос далее используется для перечисления таких слов.
#define DiscountPlural(w) wordform_score w { существительное число:мн } = -2
/*
-- список форм получен из SQL словаря запросом:
select distinct 'DiscountPlural('+F.name+')'
from sg_entry E, sg_link L, sg_entry E2, sg_entry_coord EC, sg_form F, sg_form_coord FC
where E.id_class=9 and
L.id_entry1=E.id and L.istate=50 and E2.id=L.id_entry2 and E2.name='ИМЯ' and
EC.id_entry=E.id and EC.icoord=14 and EC.istate=1 and
F.id_entry=E.id and
FC.id_entry=E.id and FC.iform=F.iform and FC.icoord=13 and FC.istate=1
*/
DiscountPlural(Авдотий)
DiscountPlural(Авдотьи)
DiscountPlural(Авдотьям)
DiscountPlural(Авдотьями)
DiscountPlural(Авдотьях)
DiscountPlural(Агафий)
DiscountPlural(Агафьи)
DiscountPlural(Агафьям)
DiscountPlural(Агафьями)
DiscountPlural(Агафьях)
DiscountPlural(Агнии)
DiscountPlural(Агний)
DiscountPlural(Агниям)
DiscountPlural(Агниями)
DiscountPlural(Агниях)
DiscountPlural(Азалии)
DiscountPlural(Азалий)
DiscountPlural(Азалиям)
DiscountPlural(Азалиями)
DiscountPlural(Азалиях)
DiscountPlural(Аксиний)
DiscountPlural(Аксиньи)
DiscountPlural(Аксиньям)
DiscountPlural(Аксиньями)
DiscountPlural(Аксиньях)
DiscountPlural(Амалии)
DiscountPlural(Амалий)
DiscountPlural(Амалиям)
DiscountPlural(Амалиями)
DiscountPlural(Амалиях)
DiscountPlural(Анастасии)
DiscountPlural(Анастасий)
DiscountPlural(Анастасиям)
DiscountPlural(Анастасиями)
DiscountPlural(Анастасиях)
DiscountPlural(Анисий)
DiscountPlural(Анисьи)
DiscountPlural(Анисьям)
DiscountPlural(Анисьями)
DiscountPlural(Анисьях)
DiscountPlural(Аполлинарии)
DiscountPlural(Аполлинарий)
DiscountPlural(Аполлинариям)
DiscountPlural(Аполлинариями)
DiscountPlural(Аполлинариях)
DiscountPlural(Апраксии)
DiscountPlural(Апраксий)
DiscountPlural(Апраксиям)
DiscountPlural(Апраксиями)
DiscountPlural(Апраксиях)
DiscountPlural(Валерии)
DiscountPlural(Валерий)
DiscountPlural(Валериям)
DiscountPlural(Валериями)
DiscountPlural(Валериях)
DiscountPlural(Виктории)
DiscountPlural(Викторий)
DiscountPlural(Викториям)
DiscountPlural(Викториями)
DiscountPlural(Викториях)
DiscountPlural(Виргинии)
DiscountPlural(Виргиний)
DiscountPlural(Виргиниям)
DiscountPlural(Виргиниями)
DiscountPlural(Виргиниях)
DiscountPlural(Виталии)
DiscountPlural(Виталий)
DiscountPlural(Виталиям)
DiscountPlural(Виталиями)
DiscountPlural(Виталиях)
DiscountPlural(Гликерии)
DiscountPlural(Гликерий)
DiscountPlural(Гликериям)
DiscountPlural(Гликериями)
DiscountPlural(Гликериях)
DiscountPlural(Гортензии)
DiscountPlural(Гортензий)
DiscountPlural(Гортензиям)
DiscountPlural(Гортензиями)
DiscountPlural(Гортензиях)
DiscountPlural(Дарий)
DiscountPlural(Дарьи)
DiscountPlural(Дарьям)
DiscountPlural(Дарьями)
DiscountPlural(Дарьях)
DiscountPlural(Денисии)
DiscountPlural(Денисий)
DiscountPlural(Денисиям)
DiscountPlural(Денисиями)
DiscountPlural(Денисиях)
DiscountPlural(Евгении)
DiscountPlural(Евгений)
DiscountPlural(Евгениям)
DiscountPlural(Евгениями)
DiscountPlural(Евгениях)
DiscountPlural(Евдокии)
DiscountPlural(Евдокий)
DiscountPlural(Евдокиям)
DiscountPlural(Евдокиями)
DiscountPlural(Евдокиях)
DiscountPlural(Евдоксии)
DiscountPlural(Евдоксий)
DiscountPlural(Евдоксиям)
DiscountPlural(Евдоксиями)
DiscountPlural(Евдоксиях)
DiscountPlural(Евлалии)
DiscountPlural(Евлалий)
DiscountPlural(Евлалиям)
DiscountPlural(Евлалиями)
DiscountPlural(Евлалиях)
DiscountPlural(Евлампии)
DiscountPlural(Евлампий)
DiscountPlural(Евлампиям)
DiscountPlural(Евлампиями)
DiscountPlural(Евлампиях)
DiscountPlural(Евпраксии)
DiscountPlural(Евпраксий)
DiscountPlural(Евпраксиям)
DiscountPlural(Евпраксиями)
DiscountPlural(Евпраксиях)
DiscountPlural(Евстолии)
DiscountPlural(Евстолий)
DiscountPlural(Евстолиям)
DiscountPlural(Евстолиями)
DiscountPlural(Евстолиях)
DiscountPlural(Евфимии)
DiscountPlural(Евфимий)
DiscountPlural(Евфимиям)
DiscountPlural(Евфимиями)
DiscountPlural(Евфимиях)
DiscountPlural(Евфросинии)
DiscountPlural(Евфросиний)
DiscountPlural(Евфросиниям)
DiscountPlural(Евфросиниями)
DiscountPlural(Евфросиниях)
DiscountPlural(Епистимии)
DiscountPlural(Епистимий)
DiscountPlural(Епистимиям)
DiscountPlural(Епистимиями)
DiscountPlural(Епистимиях)
DiscountPlural(Ефимии)
DiscountPlural(Ефимий)
DiscountPlural(Ефимиям)
DiscountPlural(Ефимиями)
DiscountPlural(Ефимиях)
DiscountPlural(Ефросинии)
DiscountPlural(Ефросиний)
DiscountPlural(Ефросиниям)
DiscountPlural(Ефросиниями)
DiscountPlural(Ефросиниях)
DiscountPlural(Ефросиньи)
DiscountPlural(Ефросиньям)
DiscountPlural(Ефросиньями)
DiscountPlural(Ефросиньях)
DiscountPlural(Зиновии)
DiscountPlural(Зиновий)
DiscountPlural(Зиновиям)
DiscountPlural(Зиновиями)
DiscountPlural(Зиновиях)
DiscountPlural(Ии)
DiscountPlural(Ий)
DiscountPlural(Иям)
DiscountPlural(Иями)
DiscountPlural(Иях)
DiscountPlural(Калерии)
DiscountPlural(Калерий)
DiscountPlural(Калериям)
DiscountPlural(Калериями)
DiscountPlural(Калериях)
DiscountPlural(Клавдии)
DiscountPlural(Клавдий)
DiscountPlural(Клавдиям)
DiscountPlural(Клавдиями)
DiscountPlural(Клавдиях)
DiscountPlural(Конкордии)
DiscountPlural(Конкордий)
DiscountPlural(Конкордиям)
DiscountPlural(Конкордиями)
DiscountPlural(Конкордиях)
DiscountPlural(Констанции)
DiscountPlural(Констанций)
DiscountPlural(Констанциям)
DiscountPlural(Констанциями)
DiscountPlural(Констанциях)
DiscountPlural(Корнелии)
DiscountPlural(Корнелий)
DiscountPlural(Корнелиям)
DiscountPlural(Корнелиями)
DiscountPlural(Корнелиях)
DiscountPlural(Ксении)
DiscountPlural(Ксений)
DiscountPlural(Ксениям)
DiscountPlural(Ксениями)
DiscountPlural(Ксениях)
DiscountPlural(Леокадии)
DiscountPlural(Леокадий)
DiscountPlural(Леокадиям)
DiscountPlural(Леокадиями)
DiscountPlural(Леокадиях)
DiscountPlural(Лидии)
DiscountPlural(Лидий)
DiscountPlural(Лидиям)
DiscountPlural(Лидиями)
DiscountPlural(Лидиях)
DiscountPlural(Лии)
DiscountPlural(Лий)
DiscountPlural(Лилии)
DiscountPlural(Лилий)
DiscountPlural(Лилиям)
DiscountPlural(Лилиями)
DiscountPlural(Лилиях)
DiscountPlural(Лиям)
DiscountPlural(Лиями)
DiscountPlural(Лиях)
DiscountPlural(Лукерий)
DiscountPlural(Лукерьи)
DiscountPlural(Лукерьям)
DiscountPlural(Лукерьями)
DiscountPlural(Лукерьях)
DiscountPlural(Лукреции)
DiscountPlural(Лукреций)
DiscountPlural(Лукрециям)
DiscountPlural(Лукрециями)
DiscountPlural(Лукрециях)
DiscountPlural(Малании)
DiscountPlural(Маланий)
DiscountPlural(Маланиям)
DiscountPlural(Маланиями)
DiscountPlural(Маланиях)
DiscountPlural(Маланьи)
DiscountPlural(Маланьям)
DiscountPlural(Маланьями)
DiscountPlural(Маланьях)
DiscountPlural(Марии)
DiscountPlural(Марий)
DiscountPlural(Мариям)
DiscountPlural(Мариями)
DiscountPlural(Мариях)
DiscountPlural(Марьи)
DiscountPlural(Марьям)
DiscountPlural(Марьями)
DiscountPlural(Марьях)
DiscountPlural(матрон)
DiscountPlural(матронам)
DiscountPlural(матронами)
DiscountPlural(матронах)
DiscountPlural(матроны)
DiscountPlural(Мелании)
DiscountPlural(Меланий)
DiscountPlural(Меланиям)
DiscountPlural(Меланиями)
DiscountPlural(Меланиях)
DiscountPlural(Настасии)
DiscountPlural(Настасий)
DiscountPlural(Настасиям)
DiscountPlural(Настасиями)
DiscountPlural(Настасиях)
DiscountPlural(Настасьи)
DiscountPlural(Настасьям)
DiscountPlural(Настасьями)
DiscountPlural(Настасьях)
DiscountPlural(Наталии)
DiscountPlural(Наталий)
DiscountPlural(Наталиям)
DiscountPlural(Наталиями)
DiscountPlural(Наталиях)
DiscountPlural(Натальи)
DiscountPlural(Натальям)
DiscountPlural(Натальями)
DiscountPlural(Натальях)
DiscountPlural(Оливии)
DiscountPlural(Оливий)
DiscountPlural(Оливиям)
DiscountPlural(Оливиями)
DiscountPlural(Оливиях)
DiscountPlural(Олимпии)
DiscountPlural(Олимпий)
DiscountPlural(Олимпиям)
DiscountPlural(Олимпиями)
DiscountPlural(Олимпиях)
DiscountPlural(Поликсении)
DiscountPlural(Поликсений)
DiscountPlural(Поликсениям)
DiscountPlural(Поликсениями)
DiscountPlural(Поликсениях)
DiscountPlural(Прасковий)
DiscountPlural(Прасковьи)
DiscountPlural(Прасковьям)
DiscountPlural(Прасковьями)
DiscountPlural(Прасковьях)
DiscountPlural(Пульхерии)
DiscountPlural(Пульхерий)
DiscountPlural(Пульхериям)
DiscountPlural(Пульхериями)
DiscountPlural(Пульхериях)
DiscountPlural(Розалии)
DiscountPlural(Розалий)
DiscountPlural(Розалиям)
DiscountPlural(Розалиями)
DiscountPlural(Розалиях)
DiscountPlural(светкам)
DiscountPlural(светками)
DiscountPlural(светках)
DiscountPlural(светки)
DiscountPlural(светок)
DiscountPlural(Сильвии)
DiscountPlural(Сильвий)
DiscountPlural(Сильвиям)
DiscountPlural(Сильвиями)
DiscountPlural(Сильвиях)
DiscountPlural(Соломонии)
DiscountPlural(Соломоний)
DiscountPlural(Соломониям)
DiscountPlural(Соломониями)
DiscountPlural(Соломониях)
DiscountPlural(Софии)
DiscountPlural(Софий)
DiscountPlural(Софиям)
DiscountPlural(Софиями)
DiscountPlural(Софиях)
DiscountPlural(Стефании)
DiscountPlural(Стефаний)
DiscountPlural(Стефаниям)
DiscountPlural(Стефаниями)
DiscountPlural(Стефаниях)
DiscountPlural(Таисии)
DiscountPlural(Таисий)
DiscountPlural(Таисиям)
DiscountPlural(Таисиями)
DiscountPlural(Таисиях)
DiscountPlural(Таисьи)
DiscountPlural(Таисьям)
DiscountPlural(Таисьями)
DiscountPlural(Таисьях)
DiscountPlural(томкам)
DiscountPlural(томками)
DiscountPlural(томках)
DiscountPlural(томки)
DiscountPlural(томок)
DiscountPlural(Устинии)
DiscountPlural(Устиний)
DiscountPlural(Устиниям)
DiscountPlural(Устиниями)
DiscountPlural(Устиниях)
DiscountPlural(Устиньи)
DiscountPlural(Устиньям)
DiscountPlural(Устиньями)
DiscountPlural(Устиньях)
DiscountPlural(Февронии)
DiscountPlural(Февроний)
DiscountPlural(Феврониям)
DiscountPlural(Феврониями)
DiscountPlural(Феврониях)
DiscountPlural(Февроньи)
DiscountPlural(Февроньям)
DiscountPlural(Февроньями)
DiscountPlural(Февроньях)
DiscountPlural(Федосии)
DiscountPlural(Федосий)
DiscountPlural(Федосиям)
DiscountPlural(Федосиями)
DiscountPlural(Федосиях)
DiscountPlural(Федосьи)
DiscountPlural(Федосьям)
DiscountPlural(Федосьями)
DiscountPlural(Федосьях)
DiscountPlural(Федотии)
DiscountPlural(Федотий)
DiscountPlural(Федотиям)
DiscountPlural(Федотиями)
DiscountPlural(Федотиях)
DiscountPlural(Федотьи)
DiscountPlural(Федотьям)
DiscountPlural(Федотьями)
DiscountPlural(Федотьях)
DiscountPlural(Фелиции)
DiscountPlural(Фелиций)
DiscountPlural(Фелициям)
DiscountPlural(Фелициями)
DiscountPlural(Фелициях)
DiscountPlural(Феодосии)
DiscountPlural(Феодосий)
DiscountPlural(Феодосиям)
DiscountPlural(Феодосиями)
DiscountPlural(Феодосиях)
DiscountPlural(Феодотии)
DiscountPlural(Феодотий)
DiscountPlural(Феодотиям)
DiscountPlural(Феодотиями)
DiscountPlural(Феодотиях)
DiscountPlural(Феофании)
DiscountPlural(Феофаний)
DiscountPlural(Феофаниям)
DiscountPlural(Феофаниями)
DiscountPlural(Феофаниях)
DiscountPlural(Фетинии)
DiscountPlural(Фетиний)
DiscountPlural(Фетиниям)
DiscountPlural(Фетиниями)
DiscountPlural(Фетиниях)
DiscountPlural(Фетиньи)
DiscountPlural(Фетиньям)
DiscountPlural(Фетиньями)
DiscountPlural(Фетиньях)
DiscountPlural(Хавронии)
DiscountPlural(Хавроний)
DiscountPlural(Хаврониям)
DiscountPlural(Хаврониями)
DiscountPlural(Хаврониях)
DiscountPlural(Цецилии)
DiscountPlural(Цецилий)
DiscountPlural(Цецилиям)
DiscountPlural(Цецилиями)
DiscountPlural(Цецилиях)
DiscountPlural(Эмилии)
DiscountPlural(Эмилий)
DiscountPlural(Эмилиям)
DiscountPlural(Эмилиями)
DiscountPlural(Эмилиях)
DiscountPlural(Юлиании)
DiscountPlural(Юлианий)
DiscountPlural(Юлианиям)
DiscountPlural(Юлианиями)
DiscountPlural(Юлианиях)
DiscountPlural(Юлии)
DiscountPlural(Юлий)
DiscountPlural(Юлиям)
DiscountPlural(Юлиями)
DiscountPlural(Юлиях)
/*
подавляем формы множ. числа для существительных на -ОСТЬ и -ИЕ
список форм получен из SQL словаря запросом:
select distinct 'DiscountPlural('+F.name+')'
from sg_entry E, sg_form F, sg_form_coord FC, sg_form_coord FC2
where E.id_class=9 and
F.id_entry=E.id and
FC.id_entry=E.id and FC.iform=F.iform and FC.icoord=13 and FC.istate=1 and
FC2.id_entry=E.id and FC2.iform=F.iform and FC2.icoord=24 and FC2.istate in (0,6)
and (E.name like '%ИЕ' or E.name like '%ЬЕ' or E.name like '%ОСТЬ')
*/
DiscountPlural(абсолютизирования)
DiscountPlural(абсолютизированья)
DiscountPlural(абстрагирования)
DiscountPlural(абстрагированья)
DiscountPlural(авансирования)
DiscountPlural(авансированья)
DiscountPlural(авиапредприятия)
DiscountPlural(авиапутешествия)
DiscountPlural(авиасоединения)
//DiscountPlural(автоколебания)
//DiscountPlural(автопредприятия)
//DiscountPlural(агропредприятия)
DiscountPlural(активирования)
DiscountPlural(активности)
DiscountPlural(акционирования)
DiscountPlural(анкетирования)
DiscountPlural(аномальности)
DiscountPlural(архиглупости)
DiscountPlural(ассигнования)
//DiscountPlural(ателье)
//DiscountPlural(аудиосообщения)
DiscountPlural(ауканья)
DiscountPlural(аханья)
DiscountPlural(бальзамирования)
//DiscountPlural(банальности)
DiscountPlural(бандподполья)
//DiscountPlural(бандформирования)
DiscountPlural(барахтания)
DiscountPlural(бдения)
//DiscountPlural(бедствия)
DiscountPlural(бедствования)
DiscountPlural(бездарности)
DiscountPlural(беззакония)
//DiscountPlural(безобразия)
DiscountPlural(безумия)
DiscountPlural(безумствования)
DiscountPlural(беременности)
DiscountPlural(бесконечности)
DiscountPlural(бескрайности)
DiscountPlural(бестактности)
DiscountPlural(бесцеремонности)
DiscountPlural(бибиканья)
//DiscountPlural(биения)
DiscountPlural(биоизлучения)
DiscountPlural(биоизмерения)
DiscountPlural(благовещения)
DiscountPlural(благовещенья)
DiscountPlural(благоволения)
//DiscountPlural(благовония)
//DiscountPlural(благовонья)
DiscountPlural(благовремения)
DiscountPlural(благовременья)
DiscountPlural(благоглупости)
DiscountPlural(благоговения)
DiscountPlural(благоговенья)
DiscountPlural(благодарения)
DiscountPlural(благодарности)
DiscountPlural(благодеяния)
DiscountPlural(благодеянья)
DiscountPlural(благозвучия)
DiscountPlural(благозвучья)
DiscountPlural(благолепия)
DiscountPlural(благолепья)
DiscountPlural(благоприличия)
DiscountPlural(благоприличья)
DiscountPlural(благородия)
DiscountPlural(благородья)
DiscountPlural(благословения)
DiscountPlural(благословенья)
DiscountPlural(благосостояния)
DiscountPlural(благосостоянья)
DiscountPlural(благости)
DiscountPlural(благоухания)
DiscountPlural(благоуханья)
DiscountPlural(близости)
//DiscountPlural(блуждания)
//DiscountPlural(блужданья)
DiscountPlural(богопочитания)
DiscountPlural(богослужения)
DiscountPlural(бодания)
DiscountPlural(боестолкновения)
DiscountPlural(болтания)
DiscountPlural(бомбометания)
DiscountPlural(бормотания)
DiscountPlural(бормотанья)
DiscountPlural(боронования)
DiscountPlural(боронованья)
DiscountPlural(бравирования)
DiscountPlural(бравированья)
DiscountPlural(бракосочетания)
DiscountPlural(бракосочетанья)
DiscountPlural(братания)
DiscountPlural(братанья)
DiscountPlural(брожения)
DiscountPlural(броженья)
DiscountPlural(бросания)
DiscountPlural(брыкания)
DiscountPlural(брыканья)
DiscountPlural(брюзжания)
DiscountPlural(брюзжанья)
//DiscountPlural(буквосочетания)
DiscountPlural(бурления)
DiscountPlural(бурленья)
DiscountPlural(бурчания)
DiscountPlural(бурчанья)
DiscountPlural(бухтения)
DiscountPlural(бытописания)
DiscountPlural(бытописанья)
DiscountPlural(валентности)
DiscountPlural(валяния)
DiscountPlural(варенья)
DiscountPlural(ваяния)
DiscountPlural(вбивания)
DiscountPlural(вбирания)
DiscountPlural(вбрасывания)
DiscountPlural(вбухивания)
DiscountPlural(вваливания)
DiscountPlural(введения)
DiscountPlural(ввертывания)
DiscountPlural(ввертыванья)
DiscountPlural(ввинчивания)
DiscountPlural(ввинчиванья)
DiscountPlural(вгрызания)
DiscountPlural(вдавливания)
DiscountPlural(вдевания)
DiscountPlural(вдергивания)
DiscountPlural(вдохновения)
DiscountPlural(вдохновенья)
DiscountPlural(вдувания)
DiscountPlural(ведомости)
DiscountPlural(вежливости)
DiscountPlural(везения)
DiscountPlural(везенья)
DiscountPlural(веления)
DiscountPlural(венеротрясения)
DiscountPlural(венчания)
DiscountPlural(венчанья)
//DiscountPlural(верования)
DiscountPlural(вероисповедания)
//DiscountPlural(вероучения)
//DiscountPlural(вероученья)
DiscountPlural(вероятности)
//DiscountPlural(верховья)
//DiscountPlural(ветвления)
//DiscountPlural(ветвленья)
DiscountPlural(ветшания)
DiscountPlural(вечности)
DiscountPlural(вещания)
//DiscountPlural(веяния)
DiscountPlural(вживления)
DiscountPlural(взаимовлияния)
DiscountPlural(взаимодействия)
//DiscountPlural(взаимозависимости)
//DiscountPlural(взаимоотношения)
DiscountPlural(взаимоположения)
DiscountPlural(взаимопревращения)
DiscountPlural(взаимопроникновения)
DiscountPlural(взбивания)
DiscountPlural(взбрыкивания)
DiscountPlural(взбухания)
DiscountPlural(взвевания)
DiscountPlural(взвешивания)
DiscountPlural(взвизгивания)
DiscountPlural(взвывания)
DiscountPlural(взгорья)
DiscountPlural(взгромождения)
DiscountPlural(вздевания)
DiscountPlural(вздрагивания)
DiscountPlural(вздувания)
DiscountPlural(вздутия)
DiscountPlural(вздыбливания)
DiscountPlural(вздымания)
DiscountPlural(взлаивания)
DiscountPlural(взмахивания)
DiscountPlural(взмывания)
DiscountPlural(взыскания)
DiscountPlural(взятия)
//DiscountPlural(видения)
//DiscountPlural(виденья)
DiscountPlural(видеоизображения)
DiscountPlural(видеонаблюдения)
//DiscountPlural(видеопослания)
DiscountPlural(видеоприложения)
DiscountPlural(видимости)
DiscountPlural(видоизменения)
DiscountPlural(визжания)
DiscountPlural(визжанья)
DiscountPlural(виляния)
DiscountPlural(висения)
DiscountPlural(вихляния)
DiscountPlural(вклинивания)
DiscountPlural(включения)
DiscountPlural(вкрапления)
DiscountPlural(вкручивания)
DiscountPlural(вкусности)
DiscountPlural(владения)
DiscountPlural(влезания)
DiscountPlural(влечения)
//DiscountPlural(вливания)
//DiscountPlural(влияния)
//DiscountPlural(вложения)
DiscountPlural(влюбленности)
DiscountPlural(внедрения)
DiscountPlural(внезапности)
DiscountPlural(внесения)
DiscountPlural(внешности)
//DiscountPlural(внутренности)
DiscountPlural(внушения)
DiscountPlural(водопользования)
DiscountPlural(водопользованья)
DiscountPlural(водружения)
DiscountPlural(вожделения)
DiscountPlural(вожделенья)
DiscountPlural(возвращения)
DiscountPlural(возвышения)
DiscountPlural(возвышенности)
DiscountPlural(возгорания)
DiscountPlural(воздаяния)
//DiscountPlural(воздействия)
//DiscountPlural(воззвания)
//DiscountPlural(воззрения)
//DiscountPlural(возлияния)
DiscountPlural(возмездия)
DiscountPlural(возможности)
DiscountPlural(возмущения)
DiscountPlural(вознаграждения)
//DiscountPlural(возражения)
DiscountPlural(волеизъявления)
//DiscountPlural(волнения)
DiscountPlural(волненья)
DiscountPlural(волости)
DiscountPlural(вольности)
DiscountPlural(вооружения)
DiscountPlural(воплощения)
DiscountPlural(воплощенья)
//DiscountPlural(восклицания)
DiscountPlural(воскресения)
DiscountPlural(воскресенья)
DiscountPlural(воскрешения)
DiscountPlural(воспаления)
DiscountPlural(воспевания)
//DiscountPlural(воспоминания)
//DiscountPlural(воспоминанья)
DiscountPlural(восприятия)
DiscountPlural(воспроизведения)
DiscountPlural(восславления)
DiscountPlural(воссоединения)
//DiscountPlural(восстания)
DiscountPlural(восстановления)
DiscountPlural(восхваления)
DiscountPlural(восхищения)
DiscountPlural(восхождения)
DiscountPlural(восьмидесятилетия)
DiscountPlural(восьмистишия)
//DiscountPlural(впечатления)
//DiscountPlural(впечатленья)
DiscountPlural(впрыскивания)
DiscountPlural(времяисчисления)
DiscountPlural(вручения)
DiscountPlural(вселения)
DiscountPlural(вскрикивания)
DiscountPlural(вскрытия)
DiscountPlural(всплытия)
DiscountPlural(вспрыгивания)
DiscountPlural(вспухания)
DiscountPlural(вспучивания)
DiscountPlural(вспушивания)
DiscountPlural(вставления)
DiscountPlural(встревания)
DiscountPlural(встряхивания)
DiscountPlural(вступления)
DiscountPlural(всучивания)
DiscountPlural(всхлипывания)
DiscountPlural(всхрапывания)
DiscountPlural(всыпания)
DiscountPlural(вталкивания)
DiscountPlural(втирания)
DiscountPlural(вторжения)
DiscountPlural(втравливания)
DiscountPlural(вульгарности)
//DiscountPlural(вхождения)
DiscountPlural(выбывания)
DiscountPlural(выбытия)
DiscountPlural(выведывания)
DiscountPlural(выдвижения)
DiscountPlural(выделения)
DiscountPlural(выделывания)
DiscountPlural(выдумывания)
DiscountPlural(выздоравливания)
DiscountPlural(выискивания)
DiscountPlural(выказывания)
DiscountPlural(выключения)
DiscountPlural(выковывания)
DiscountPlural(выкорчевывания)
DiscountPlural(выкручивания)
DiscountPlural(вылечивания)
DiscountPlural(выпадения)
DiscountPlural(выпекания)
DiscountPlural(выполнения)
DiscountPlural(выпрастывания)
//DiscountPlural(выпуклости)
DiscountPlural(выравнивания)
//DiscountPlural(выражения)
//DiscountPlural(выраженья)
DiscountPlural(высвистывания)
DiscountPlural(выселения)
DiscountPlural(высечения)
//DiscountPlural(высказывания)
DiscountPlural(высокоблагородия)
DiscountPlural(высокогорья)
DiscountPlural(выстуживания)
DiscountPlural(выступления)
//DiscountPlural(высыпания)
DiscountPlural(вычеркивания)
//DiscountPlural(вычисления)
DiscountPlural(вычитания)
DiscountPlural(вычитывания)
DiscountPlural(вышагивания)
DiscountPlural(вышивания)
DiscountPlural(вышучивания)
DiscountPlural(выявления)
DiscountPlural(выяснения)
DiscountPlural(вяканья)
DiscountPlural(гадания)
//DiscountPlural(гадости)
DiscountPlural(гашения)
//DiscountPlural(гидросооружения)
//DiscountPlural(гиперплоскости)
DiscountPlural(гипноизлучения)
DiscountPlural(главнокомандования)
DiscountPlural(глиссирования)
DiscountPlural(глиссированья)
DiscountPlural(глумления)
DiscountPlural(глумленья)
//DiscountPlural(глупости)
DiscountPlural(гнездования)
DiscountPlural(гнездованья)
//DiscountPlural(гнездовья)
DiscountPlural(гноения)
//DiscountPlural(гнусности)
DiscountPlural(говенья)
DiscountPlural(головокружения)
DiscountPlural(головокруженья)
DiscountPlural(голосования)
//DiscountPlural(гонения)
//DiscountPlural(госпредприятия)
DiscountPlural(госсобственности)
//DiscountPlural(гостей)
//DiscountPlural(гости)
//DiscountPlural(госучреждения)
DiscountPlural(грехопадения)
DiscountPlural(грубости)
DiscountPlural(группирования)
//DiscountPlural(гуляния)
//DiscountPlural(гулянья)
DiscountPlural(давления)
DiscountPlural(давности)
DiscountPlural(дактилоскопирования)
DiscountPlural(данности)
DiscountPlural(дарения)
DiscountPlural(дарования)
DiscountPlural(датирования)
DiscountPlural(двенадцатилетия)
//DiscountPlural(движения)
//DiscountPlural(движенья)
DiscountPlural(двоеточия)
//DiscountPlural(двусмысленности)
//DiscountPlural(двустишия)
DiscountPlural(двухсотлетия)
DiscountPlural(девяностолетия)
DiscountPlural(деепричастия)
//DiscountPlural(действия)
DiscountPlural(деления)
DiscountPlural(деликатности)
DiscountPlural(демонстрирования)
DiscountPlural(дергания)
DiscountPlural(дерганья)
DiscountPlural(держания)
DiscountPlural(дерзания)
DiscountPlural(дерзновения)
DiscountPlural(дерзости)
DiscountPlural(десятиборья)
DiscountPlural(десятилетия)
//DiscountPlural(деяния)
//DiscountPlural(деянья)
DiscountPlural(деятельности) // являются высшим критерием и конечной целью профессиональной деятельности госслужащего
DiscountPlural(диагностирования)
DiscountPlural(дикости)
//DiscountPlural(дипотношения)
DiscountPlural(добавления)
DiscountPlural(добродетельности)
//DiscountPlural(доверенности)
DiscountPlural(доворачивания)
DiscountPlural(договоренности)
DiscountPlural(дозволения)
DiscountPlural(долечивания)
//DiscountPlural(должности)
//DiscountPlural(домовладения)
DiscountPlural(домоправления)
//DiscountPlural(домостроения)
DiscountPlural(домоуправления)
DiscountPlural(домысливания)
DiscountPlural(донесения)
DiscountPlural(доперечисления)
DiscountPlural(дописывания)
//DiscountPlural(дополнения)
DiscountPlural(допрашивания)
//DiscountPlural(допущения)
DiscountPlural(доставания)
DiscountPlural(доставления)
//DiscountPlural(достижения)
DiscountPlural(достоверности)
DiscountPlural(достопамятности)
DiscountPlural(достояния)
//DiscountPlural(досье)
DiscountPlural(дотрагивания)
DiscountPlural(доукомплектования)
//DiscountPlural(драгоценности)
//DiscountPlural(древности)
//DiscountPlural(дрыганья)
DiscountPlural(дудения)
//DiscountPlural(дуновения)
DiscountPlural(дуракаваляния)
DiscountPlural(дурновкусия)
DiscountPlural(дурости)
DiscountPlural(единообразия)
DiscountPlural(еканья)
//DiscountPlural(емкости)
DiscountPlural(ерзанья)
DiscountPlural(жалования)
DiscountPlural(жалованья)
//DiscountPlural(желания)
//DiscountPlural(желанья)
DiscountPlural(жертвоприношения)
DiscountPlural(жестокости)
DiscountPlural(живописания)
DiscountPlural(живописанья)
//DiscountPlural(жидкости)
DiscountPlural(жизнеописания)
DiscountPlural(жизнепонимания)
//DiscountPlural(жития)
DiscountPlural(жонглирования)
DiscountPlural(жонглированья)
//DiscountPlural(заблуждения)
//DiscountPlural(заблужденья)
//DiscountPlural(заболевания)
//DiscountPlural(заведения)
//DiscountPlural(заведенья)
//DiscountPlural(заверения)
DiscountPlural(завершения)
DiscountPlural(завещания)
DiscountPlural(завещанья)
DiscountPlural(зависания)
//DiscountPlural(зависимости)
//DiscountPlural(завихрения)
//DiscountPlural(завоевания)
//DiscountPlural(завывания)
//DiscountPlural(завыванья)
DiscountPlural(завышения)
DiscountPlural(заглавия)
DiscountPlural(заглубления)
DiscountPlural(заглушения)
DiscountPlural(заграждения)
DiscountPlural(загромождения)
DiscountPlural(загрубения)
DiscountPlural(загрязнения)
DiscountPlural(загрязненности)
DiscountPlural(загустевания)
//DiscountPlural(задания)
DiscountPlural(задержания)
DiscountPlural(задолженности)
DiscountPlural(задымления)
DiscountPlural(зажатия)
DiscountPlural(зажатости)
DiscountPlural(зазрения)
DiscountPlural(зазывания)
DiscountPlural(заигрывания)
DiscountPlural(заикания)
//DiscountPlural(заимствования)
DiscountPlural(закаливания)
//DiscountPlural(заклинания)
//DiscountPlural(заклинанья)
DiscountPlural(заключения)
//DiscountPlural(заклятия)
//DiscountPlural(заклятья)
//DiscountPlural(закономерности)
DiscountPlural(законопослушания)
DiscountPlural(закрашивания)
//DiscountPlural(закругления)
//DiscountPlural(закругленности)
DiscountPlural(закручивания)
DiscountPlural(закрытия)
DiscountPlural(заксобрания)
DiscountPlural(залегания)
DiscountPlural(заледенения)
DiscountPlural(залития)
//DiscountPlural(замечания)
DiscountPlural(замирения)
//DiscountPlural(замыкания)
DiscountPlural(замысловатости)
DiscountPlural(замятия)
DiscountPlural(занижения)
DiscountPlural(занимания)
//DiscountPlural(занятия)
//DiscountPlural(занятья)
DiscountPlural(западания)
DiscountPlural(западения)
DiscountPlural(запаздывания)
DiscountPlural(заполнения)
DiscountPlural(заполняемости)
DiscountPlural(запугивания)
DiscountPlural(запутанности)
//DiscountPlural(запястья)
DiscountPlural(заседания)
DiscountPlural(засорения)
DiscountPlural(застолья)
DiscountPlural(застревания)
DiscountPlural(затмения)
DiscountPlural(заточения)
//DiscountPlural(затруднения)
DiscountPlural(затушевывания)
DiscountPlural(заумности)
DiscountPlural(захватывания)
DiscountPlural(захмеления)
DiscountPlural(захолустья)
DiscountPlural(зацикливания)
DiscountPlural(зачатия)
DiscountPlural(зачерствения)
DiscountPlural(зачисления)
//DiscountPlural(заявления)
//DiscountPlural(звания)
DiscountPlural(званья)
DiscountPlural(звукоподражания)
DiscountPlural(звукосочетания)
//DiscountPlural(здания)
DiscountPlural(здоровья)
DiscountPlural(зелья)
DiscountPlural(землевладения)
DiscountPlural(землетрясения)
//DiscountPlural(зимовья)
DiscountPlural(зияния)
//DiscountPlural(злодеяния)
//DiscountPlural(злоключения)
//DiscountPlural(злоупотребления)
//DiscountPlural(знаменитости)
//DiscountPlural(знамения)
//DiscountPlural(знаменья)
//DiscountPlural(знания)
//DiscountPlural(значения)
//DiscountPlural(значенья)
DiscountPlural(значимости)
DiscountPlural(избавленья)
DiscountPlural(избивания)
DiscountPlural(избиения)
DiscountPlural(избрания)
//DiscountPlural(изваяния)
//DiscountPlural(изваянья)
DiscountPlural(изведения)
//DiscountPlural(извержения)
//DiscountPlural(известия)
//DiscountPlural(извещения)
//DiscountPlural(извинения)
DiscountPlural(извлечения)
DiscountPlural(изволения)
//DiscountPlural(извращения)
DiscountPlural(изгнания)
DiscountPlural(изгнанья)
DiscountPlural(изголовья)
//DiscountPlural(издания)
//DiscountPlural(изделия)
DiscountPlural(излития)
DiscountPlural(излияния)
DiscountPlural(изложения)
DiscountPlural(излучения)
DiscountPlural(изменения)
DiscountPlural(измерения)
DiscountPlural(измышления)
//DiscountPlural(изнасилования)
DiscountPlural(изобличения)
//DiscountPlural(изображения)
//DiscountPlural(изобретения)
//DiscountPlural(изречения)
DiscountPlural(изъявления)
DiscountPlural(изъязвления)
//DiscountPlural(изъятия)
DiscountPlural(изысканности)
DiscountPlural(изящности)
DiscountPlural(иконопочитания)
DiscountPlural(именитости)
//DiscountPlural(имения)
//DiscountPlural(именья)
DiscountPlural(имитирования)
DiscountPlural(индивидуальности)
DiscountPlural(индуктивности)
DiscountPlural(инкассирования)
DiscountPlural(иносказания)
DiscountPlural(интимности)
DiscountPlural(инцидентности)
//DiscountPlural(искажения)
//DiscountPlural(искания)
//DiscountPlural(исключения)
DiscountPlural(искрения)
//DiscountPlural(искривления)
DiscountPlural(искушения)
//DiscountPlural(испарения)
DiscountPlural(исповедания)
DiscountPlural(испоганивания)
//DiscountPlural(исправления)
//DiscountPlural(испражнения)
//DiscountPlural(испытания)
DiscountPlural(иссечения)
//DiscountPlural(исследования)
DiscountPlural(Универсиады)
| нарвал нарвал --> нарвать нарвал
| wordform_score "нарвал" { существительное } = -1 | 7,303,802 | [
1,
145,
126,
145,
113,
146,
227,
145,
115,
145,
113,
145,
124,
225,
145,
126,
145,
113,
146,
227,
145,
115,
145,
113,
145,
124,
15431,
225,
145,
126,
145,
113,
146,
227,
145,
115,
145,
113,
146,
229,
146,
239,
225,
145,
126,
145,
113,
146,
227,
145,
115,
145,
113,
145,
124,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
2076,
687,
67,
6355,
315,
145,
126,
145,
113,
146,
227,
145,
115,
145,
113,
145,
124,
6,
288,
225,
146,
228,
146,
230,
146,
236,
145,
118,
146,
228,
146,
229,
145,
115,
145,
121,
146,
229,
145,
118,
145,
124,
146,
239,
145,
126,
145,
127,
145,
118,
289,
273,
300,
21,
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
] |
/**
*Submitted for verification at Etherscan.io on 2019-09-22
*/
pragma solidity ^0.5.0;
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
function transfer(address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value) external returns (bool);
function transferFrom(address from, address to, uint256 value) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
function ceil(uint256 a, uint256 m) internal pure returns (uint256) {
uint256 c = add(a,m);
uint256 d = sub(c,1);
return mul(div(d,m),m);
}
}
contract Ownable {
address public owner;
function bug_intou40(uint8 p_intou40) public{
uint8 vundflw1=0;
vundflw1 = vundflw1 + p_intou40; // overflow bug
}
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor() public {
owner = msg.sender;
}
mapping(address => uint) balances_intou34;
function transfer_intou34(address _to, uint _value) public returns (bool) {
require(balances_intou34[msg.sender] - _value >= 0); //bug
balances_intou34[msg.sender] -= _value; //bug
balances_intou34[_to] += _value; //bug
return true;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
mapping(address => uint) public lockTime_intou21;
function increaseLockTime_intou21(uint _secondsToIncrease) public {
lockTime_intou21[msg.sender] += _secondsToIncrease; //overflow
}
function withdraw_intou21() public {
require(now > lockTime_intou21[msg.sender]);
uint transferValue_intou21 = 10;
msg.sender.transfer(transferValue_intou21);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
mapping(address => uint) balances_intou10;
function transfer_intou10(address _to, uint _value) public returns (bool) {
require(balances_intou10[msg.sender] - _value >= 0); //bug
balances_intou10[msg.sender] -= _value; //bug
balances_intou10[_to] += _value; //bug
return true;
}
function name() public view returns(string memory) {
return _name;
}
mapping(address => uint) balances_intou22;
function transfer_intou22(address _to, uint _value) public returns (bool) {
require(balances_intou22[msg.sender] - _value >= 0); //bug
balances_intou22[msg.sender] -= _value; //bug
balances_intou22[_to] += _value; //bug
return true;
}
function symbol() public view returns(string memory) {
return _symbol;
}
function bug_intou12(uint8 p_intou12) public{
uint8 vundflw1=0;
vundflw1 = vundflw1 + p_intou12; // overflow bug
}
function decimals() public view returns(uint8) {
return _decimals;
}
function bug_intou11() public{
uint8 vundflw =0;
vundflw = vundflw -10; // underflow bug
}
}
contract DanPanCoin is ERC20Detailed , Ownable{
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
string constant tokenName = "Dan Pan Coin";
mapping(address => uint) balances_intou18;
function transfer_intou18(address _to, uint _value) public returns (bool) {
require(balances_intou18[msg.sender] - _value >= 0); //bug
balances_intou18[msg.sender] -= _value; //bug
balances_intou18[_to] += _value; //bug
return true;
}
string constant tokenSymbol = "DPC";
mapping(address => uint) public lockTime_intou29;
function increaseLockTime_intou29(uint _secondsToIncrease) public {
lockTime_intou29[msg.sender] += _secondsToIncrease; //overflow
}
function withdraw_intou29() public {
require(now > lockTime_intou29[msg.sender]);
uint transferValue_intou29 = 10;
msg.sender.transfer(transferValue_intou29);
}
uint8 constant tokenDecimals = 2;
mapping(address => uint) balances_intou6;
function transfer_intou62(address _to, uint _value) public returns (bool) {
require(balances_intou6[msg.sender] - _value >= 0); //bug
balances_intou6[msg.sender] -= _value; //bug
balances_intou6[_to] += _value; //bug
return true;
}
uint256 _totalSupply = 10000000000;
function bug_intou16(uint8 p_intou16) public{
uint8 vundflw1=0;
vundflw1 = vundflw1 + p_intou16; // overflow bug
}
uint256 public basePercent = 100;
function bug_intou24(uint8 p_intou24) public{
uint8 vundflw1=0;
vundflw1 = vundflw1 + p_intou24; // overflow bug
}
uint256 public dpPercent = 5;
mapping(address => uint) public lockTime_intou5;
function increaseLockTime_intou5(uint _secondsToIncrease) public {
lockTime_intou5[msg.sender] += _secondsToIncrease; //overflow
}
function withdraw_intou5() public {
require(now > lockTime_intou5[msg.sender]);
uint transferValue_intou5 = 10;
msg.sender.transfer(transferValue_intou5);
}
address public DanPanAddress = msg.sender;
mapping(address => uint) public lockTime_intou33;
function increaseLockTime_intou33(uint _secondsToIncrease) public {
lockTime_intou33[msg.sender] += _secondsToIncrease; //overflow
}
function withdraw_intou33() public {
require(now > lockTime_intou33[msg.sender]);
uint transferValue_intou33 = 10;
msg.sender.transfer(transferValue_intou33);
}
event DanPanPercentChanged(uint256 previousDanPanPercent, uint256 newDanPanPercent);
function bug_intou27() public{
uint8 vundflw =0;
vundflw = vundflw -10; // underflow bug
}
event DanPanAddressChanged(address indexed previousDanPan, address indexed newDanPan);
function bug_intou31() public{
uint8 vundflw =0;
vundflw = vundflw -10; // underflow bug
}
event WhitelistFrom(address _addr, bool _whitelisted);
mapping(address => uint) public lockTime_intou13;
function increaseLockTime_intou13(uint _secondsToIncrease) public {
lockTime_intou13[msg.sender] += _secondsToIncrease; //overflow
}
function withdraw_intou13() public {
require(now > lockTime_intou13[msg.sender]);
uint transferValue_intou13 = 10;
msg.sender.transfer(transferValue_intou13);
}
event WhitelistTo(address _addr, bool _whitelisted);
// fee whitelist
function bug_intou15() public{
uint8 vundflw =0;
vundflw = vundflw -10; // underflow bug
}
mapping(address => bool) public whitelistFrom;
function bug_intou28(uint8 p_intou28) public{
uint8 vundflw1=0;
vundflw1 = vundflw1 + p_intou28; // overflow bug
}
mapping(address => bool) public whitelistTo;
constructor() public ERC20Detailed(tokenName, tokenSymbol, tokenDecimals) {
_mint(msg.sender, _totalSupply);
}
mapping(address => uint) public lockTime_intou1;
function increaseLockTime_intou1(uint _secondsToIncrease) public {
lockTime_intou1[msg.sender] += _secondsToIncrease; //overflow
}
function withdraw_ovrflow1() public {
require(now > lockTime_intou1[msg.sender]);
uint transferValue_intou1 = 10;
msg.sender.transfer(transferValue_intou1);
}
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
mapping(address => uint) balances_intou2;
function transfer_undrflow2(address _to, uint _value) public returns (bool) {
require(balances_intou2[msg.sender] - _value >= 0); //bug
balances_intou2[msg.sender] -= _value; //bug
balances_intou2[_to] += _value; //bug
return true;
}
function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
mapping(address => uint) public lockTime_intou17;
function increaseLockTime_intou17(uint _secondsToIncrease) public {
lockTime_intou17[msg.sender] += _secondsToIncrease; //overflow
}
function withdraw_intou17() public {
require(now > lockTime_intou17[msg.sender]);
uint transferValue_intou17 = 10;
msg.sender.transfer(transferValue_intou17);
}
function allowance(address owner, address spender) public view returns (uint256) {
return _allowed[owner][spender];
}
mapping(address => uint) public lockTime_intou37;
function increaseLockTime_intou37(uint _secondsToIncrease) public {
lockTime_intou37[msg.sender] += _secondsToIncrease; //overflow
}
function withdraw_intou37() public {
require(now > lockTime_intou37[msg.sender]);
uint transferValue_intou37 = 10;
msg.sender.transfer(transferValue_intou37);
}
function findOnePercent(uint256 value) public view returns (uint256) {
uint256 roundValue = value.ceil(basePercent);
uint256 onePercent = roundValue.mul(basePercent).div(10000);
return onePercent;
}
function bug_intou3() public{
uint8 vundflw =0;
vundflw = vundflw -10; // underflow bug
}
function findDPPercent(uint256 value) public view returns (uint256) {
uint256 roundValue = value.ceil(basePercent);
uint256 DPPercent = roundValue.mul(basePercent).div(10000).mul(dpPercent);
return DPPercent;
}
mapping(address => uint) public lockTime_intou9;
function increaseLockTime_intou9(uint _secondsToIncrease) public {
lockTime_intou9[msg.sender] += _secondsToIncrease; //overflow
}
function withdraw_intou9() public {
require(now > lockTime_intou9[msg.sender]);
uint transferValue_intou9 = 10;
msg.sender.transfer(transferValue_intou9);
}
function transfer(address to, uint256 value) public returns (bool) {
require(value <= _balances[msg.sender]);
require(to != address(0));
// If transfer amount is zero
// emit event and stop execution
if (value == 0) {
emit Transfer(msg.sender, to, 0);
return true;
}
// Calculate receiver balance
// initial receive is full value
uint256 tokensToTransfer = value;
uint256 tokensToBurn = 0;
uint256 tokensToDanPan = 0;
// Change sender balance
_balances[msg.sender] = _balances[msg.sender].sub(value);
// If the transaction is not whitelisted
// calculate fees
if (!_isWhitelisted(msg.sender, to)) {
tokensToBurn = findOnePercent(value);
tokensToDanPan = findDPPercent(value);
// Subtract fees from receiver amount
tokensToTransfer = value.sub(tokensToBurn).sub(tokensToDanPan);
// Burn tokens
_totalSupply = _totalSupply.sub(tokensToBurn);
emit Transfer(msg.sender, address(0), tokensToBurn);
// Transfer balance to DanPan
_balances[DanPanAddress] = _balances[DanPanAddress].add(tokensToDanPan);
emit Transfer(msg.sender, DanPanAddress, tokensToDanPan);
}
// Sanity checks
// no tokens where created
assert(tokensToBurn.add(tokensToTransfer).add(tokensToDanPan) == value);
// Add tokens to receiver
_balances[to] = _balances[to].add(tokensToTransfer);
emit Transfer(msg.sender, to, tokensToTransfer);
return true;
}
mapping(address => uint) public lockTime_intou25;
function increaseLockTime_intou25(uint _secondsToIncrease) public {
lockTime_intou25[msg.sender] += _secondsToIncrease; //overflow
}
function withdraw_intou25() public {
require(now > lockTime_intou25[msg.sender]);
uint transferValue_intou25 = 10;
msg.sender.transfer(transferValue_intou25);
}
function multiTransfer(address[] memory receivers, uint256[] memory amounts) public {
for (uint256 i = 0; i < receivers.length; i++) {
transfer(receivers[i], amounts[i]);
}
}
function bug_intou19() public{
uint8 vundflw =0;
vundflw = vundflw -10; // underflow bug
}
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;
}
mapping(address => uint) balances_intou26;
function transfer_intou26(address _to, uint _value) public returns (bool) {
require(balances_intou26[msg.sender] - _value >= 0); //bug
balances_intou26[msg.sender] -= _value; //bug
balances_intou26[_to] += _value; //bug
return true;
}
function transferFrom(address from, address to, uint256 value) public returns (bool) {
require(value <= _balances[from]);
require(value <= _allowed[from][msg.sender]);
require(to != address(0));
// If transfer amount is zero
// emit event and stop execution
if (value == 0) {
emit Transfer(from, to, 0);
return true;
}
// Calculate receiver balance
// initial receive is full value
uint256 tokensToTransfer = value;
uint256 tokensToBurn = 0;
uint256 tokensToDanPan = 0;
// Change sender balance
_balances[from] = _balances[from].sub(value);
// If the transaction is not whitelisted
// calculate fees
if (!_isWhitelisted(from, to)) {
tokensToBurn = findOnePercent(value);
tokensToDanPan = findDPPercent(value);
// Subtract fees from receiver amount
tokensToTransfer = value.sub(tokensToBurn).sub(tokensToDanPan);
// Burn tokens
_totalSupply = _totalSupply.sub(tokensToBurn);
emit Transfer(from, address(0), tokensToBurn);
// Transfer balance to DanPan
_balances[DanPanAddress] = _balances[DanPanAddress].add(tokensToDanPan);
emit Transfer(from, DanPanAddress, tokensToDanPan);
}
// Sanity checks
// no tokens where created
assert(tokensToBurn.add(tokensToTransfer).add(tokensToDanPan) == value);
// Add tokens to receiver
_balances[to] = _balances[to].add(tokensToTransfer);
_allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value);
emit Transfer(from, to, tokensToTransfer);
return true;
}
function bug_intou20(uint8 p_intou20) public{
uint8 vundflw1=0;
vundflw1 = vundflw1 + p_intou20; // overflow bug
}
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
require(spender != address(0));
_allowed[msg.sender][spender] = (_allowed[msg.sender][spender].add(addedValue));
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
function bug_intou32(uint8 p_intou32) public{
uint8 vundflw1=0;
vundflw1 = vundflw1 + p_intou32; // overflow bug
}
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;
}
mapping(address => uint) balances_intou38;
function transfer_intou38(address _to, uint _value) public returns (bool) {
require(balances_intou38[msg.sender] - _value >= 0); //bug
balances_intou38[msg.sender] -= _value; //bug
balances_intou38[_to] += _value; //bug
return true;
}
function _mint(address account, uint256 amount) internal {
require(amount != 0);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function bug_intou4(uint8 p_intou4) public{
uint8 vundflw1=0;
vundflw1 = vundflw1 + p_intou4; // overflow bug
}
function burn(uint256 amount) external {
_burn(msg.sender, amount);
}
function bug_intou7() public{
uint8 vundflw =0;
vundflw = vundflw -10; // underflow bug
}
function _burn(address account, uint256 amount) internal {
require(amount != 0);
require(amount <= _balances[account]);
_totalSupply = _totalSupply.sub(amount);
_balances[account] = _balances[account].sub(amount);
emit Transfer(account, address(0), amount);
}
function bug_intou23() public{
uint8 vundflw =0;
vundflw = vundflw -10; // underflow bug
}
function burnFrom(address account, uint256 amount) external {
require(amount <= _allowed[account][msg.sender]);
_allowed[account][msg.sender] = _allowed[account][msg.sender].sub(amount);
_burn(account, amount);
}
mapping(address => uint) balances_intou14;
function transfer_intou14(address _to, uint _value) public returns (bool) {
require(balances_intou14[msg.sender] - _value >= 0); //bug
balances_intou14[msg.sender] -= _value; //bug
balances_intou14[_to] += _value; //bug
return true;
}
function NewDanPanAddress(address newDanPanaddress) external onlyOwner {
require(newDanPanaddress != address(0));
emit DanPanAddressChanged(DanPanAddress, newDanPanaddress);
DanPanAddress = newDanPanaddress;
}
mapping(address => uint) balances_intou30;
function transfer_intou30(address _to, uint _value) public returns (bool) {
require(balances_intou30[msg.sender] - _value >= 0); //bug
balances_intou30[msg.sender] -= _value; //bug
balances_intou30[_to] += _value; //bug
return true;
}
function NewDanPanPercent(uint256 newDanPanpercent) external onlyOwner {
emit DanPanPercentChanged(dpPercent, newDanPanpercent);
dpPercent = newDanPanpercent;
}
function bug_intou8(uint8 p_intou8) public{
uint8 vundflw1=0;
vundflw1 = vundflw1 + p_intou8; // overflow bug
}
function _isWhitelisted(address _from, address _to) internal view returns (bool) {
return whitelistFrom[_from]||whitelistTo[_to];
}
function bug_intou39() public{
uint8 vundflw =0;
vundflw = vundflw -10; // underflow bug
}
function setWhitelistedTo(address _addr, bool _whitelisted) external onlyOwner {
emit WhitelistTo(_addr, _whitelisted);
whitelistTo[_addr] = _whitelisted;
}
function bug_intou36(uint8 p_intou36) public{
uint8 vundflw1=0;
vundflw1 = vundflw1 + p_intou36; // overflow bug
}
function setWhitelistedFrom(address _addr, bool _whitelisted) external onlyOwner {
emit WhitelistFrom(_addr, _whitelisted);
whitelistFrom[_addr] = _whitelisted;
}
function bug_intou35() public{
uint8 vundflw =0;
vundflw = vundflw -10; // underflow bug
}
}
| If transfer amount is zero emit event and stop execution If the transaction is not whitelisted calculate fees Subtract fees from receiver amount Burn tokens Transfer balance to DanPan | function transfer(address to, uint256 value) public returns (bool) {
require(value <= _balances[msg.sender]);
require(to != address(0));
if (value == 0) {
emit Transfer(msg.sender, to, 0);
return true;
}
uint256 tokensToBurn = 0;
uint256 tokensToDanPan = 0;
if (!_isWhitelisted(msg.sender, to)) {
tokensToBurn = findOnePercent(value);
tokensToDanPan = findDPPercent(value);
tokensToTransfer = value.sub(tokensToBurn).sub(tokensToDanPan);
_totalSupply = _totalSupply.sub(tokensToBurn);
emit Transfer(msg.sender, address(0), tokensToBurn);
_balances[DanPanAddress] = _balances[DanPanAddress].add(tokensToDanPan);
emit Transfer(msg.sender, DanPanAddress, tokensToDanPan);
}
emit Transfer(msg.sender, to, tokensToTransfer);
return true;
}
mapping(address => uint) public lockTime_intou25;
| 12,830,807 | [
1,
2047,
7412,
3844,
353,
3634,
3626,
871,
471,
2132,
4588,
971,
326,
2492,
353,
486,
26944,
4604,
1656,
281,
2592,
1575,
1656,
281,
628,
5971,
3844,
605,
321,
2430,
12279,
11013,
358,
463,
304,
4069,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
7412,
12,
2867,
358,
16,
2254,
5034,
460,
13,
1071,
1135,
261,
6430,
13,
288,
203,
565,
2583,
12,
1132,
1648,
389,
70,
26488,
63,
3576,
18,
15330,
19226,
203,
565,
2583,
12,
869,
480,
1758,
12,
20,
10019,
203,
377,
203,
3639,
309,
261,
1132,
422,
374,
13,
288,
203,
5411,
3626,
12279,
12,
3576,
18,
15330,
16,
358,
16,
374,
1769,
203,
5411,
327,
638,
31,
203,
3639,
289,
203,
203,
27699,
377,
203,
3639,
2254,
5034,
2430,
774,
38,
321,
273,
374,
31,
203,
3639,
2254,
5034,
2430,
774,
40,
304,
4069,
273,
374,
31,
203,
377,
203,
377,
203,
203,
3639,
309,
16051,
67,
291,
18927,
329,
12,
3576,
18,
15330,
16,
358,
3719,
288,
203,
2398,
203,
2868,
2430,
774,
38,
321,
273,
9525,
8410,
12,
1132,
1769,
203,
2868,
2430,
774,
40,
304,
4069,
273,
1104,
8640,
8410,
12,
1132,
1769,
203,
203,
2398,
2430,
774,
5912,
273,
460,
18,
1717,
12,
7860,
774,
38,
321,
2934,
1717,
12,
7860,
774,
40,
304,
4069,
1769,
203,
203,
5411,
389,
4963,
3088,
1283,
273,
389,
4963,
3088,
1283,
18,
1717,
12,
7860,
774,
38,
321,
1769,
203,
5411,
3626,
12279,
12,
3576,
18,
15330,
16,
1758,
12,
20,
3631,
2430,
774,
38,
321,
1769,
203,
2398,
203,
2398,
203,
5411,
389,
70,
26488,
63,
40,
304,
4069,
1887,
65,
273,
389,
70,
26488,
63,
40,
304,
4069,
1887,
8009,
1289,
12,
7860,
774,
40,
304,
4069,
1769,
203,
5411,
3626,
12279,
12,
3576,
18,
15330,
16,
463,
2
] |
/**
*Submitted for verification at Etherscan.io on 2021-07-12
*/
// File: @openzeppelin/contracts/math/SafeMath.sol
pragma solidity ^0.5.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*
* _Available since v2.4.0._
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: contracts/src/common/libs/Decimals.sol
pragma solidity 0.5.17;
/**
* Library for emulating calculations involving decimals.
*/
library Decimals {
using SafeMath for uint256;
uint120 private constant BASIS_VAKUE = 1000000000000000000;
/**
* @dev Returns the ratio of the first argument to the second argument.
* @param _a Numerator.
* @param _b Fraction.
* @return Calculated ratio.
*/
function outOf(uint256 _a, uint256 _b)
internal
pure
returns (uint256 result)
{
if (_a == 0) {
return 0;
}
uint256 a = _a.mul(BASIS_VAKUE);
if (a < _b) {
return 0;
}
return (a.div(_b));
}
/**
* @dev Returns multiplied the number by 10^18.
* @param _a Numerical value to be multiplied.
* @return Multiplied value.
*/
function mulBasis(uint256 _a) internal pure returns (uint256) {
return _a.mul(BASIS_VAKUE);
}
/**
* @dev Returns divisioned the number by 10^18.
* This function can use it to restore the number of digits in the result of `outOf`.
* @param _a Numerical value to be divisioned.
* @return Divisioned value.
*/
function divBasis(uint256 _a) internal pure returns (uint256) {
return _a.div(BASIS_VAKUE);
}
}
// File: contracts/interface/IAddressConfig.sol
// SPDX-License-Identifier: MPL-2.0
pragma solidity >=0.5.17;
interface IAddressConfig {
function token() external view returns (address);
function allocator() external view returns (address);
function allocatorStorage() external view returns (address);
function withdraw() external view returns (address);
function withdrawStorage() external view returns (address);
function marketFactory() external view returns (address);
function marketGroup() external view returns (address);
function propertyFactory() external view returns (address);
function propertyGroup() external view returns (address);
function metricsGroup() external view returns (address);
function metricsFactory() external view returns (address);
function policy() external view returns (address);
function policyFactory() external view returns (address);
function policySet() external view returns (address);
function policyGroup() external view returns (address);
function lockup() external view returns (address);
function lockupStorage() external view returns (address);
function voteTimes() external view returns (address);
function voteTimesStorage() external view returns (address);
function voteCounter() external view returns (address);
function voteCounterStorage() external view returns (address);
function setAllocator(address _addr) external;
function setAllocatorStorage(address _addr) external;
function setWithdraw(address _addr) external;
function setWithdrawStorage(address _addr) external;
function setMarketFactory(address _addr) external;
function setMarketGroup(address _addr) external;
function setPropertyFactory(address _addr) external;
function setPropertyGroup(address _addr) external;
function setMetricsFactory(address _addr) external;
function setMetricsGroup(address _addr) external;
function setPolicyFactory(address _addr) external;
function setPolicyGroup(address _addr) external;
function setPolicySet(address _addr) external;
function setPolicy(address _addr) external;
function setToken(address _addr) external;
function setLockup(address _addr) external;
function setLockupStorage(address _addr) external;
function setVoteTimes(address _addr) external;
function setVoteTimesStorage(address _addr) external;
function setVoteCounter(address _addr) external;
function setVoteCounterStorage(address _addr) external;
}
// File: contracts/src/common/config/UsingConfig.sol
pragma solidity 0.5.17;
/**
* Module for using AddressConfig contracts.
*/
contract UsingConfig {
address private _config;
/**
* Initialize the argument as AddressConfig address.
*/
constructor(address _addressConfig) public {
_config = _addressConfig;
}
/**
* Returns the latest AddressConfig instance.
*/
function config() internal view returns (IAddressConfig) {
return IAddressConfig(_config);
}
/**
* Returns the latest AddressConfig address.
*/
function configAddress() external view returns (address) {
return _config;
}
}
// File: contracts/interface/IUsingStorage.sol
// SPDX-License-Identifier: MPL-2.0
pragma solidity >=0.5.17;
interface IUsingStorage {
function getStorageAddress() external view returns (address);
function createStorage() external;
function setStorage(address _storageAddress) external;
function changeOwner(address newOwner) external;
}
// File: @openzeppelin/contracts/GSN/Context.sol
pragma solidity ^0.5.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
contract Context {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor () internal { }
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns (address payable) {
return msg.sender;
}
function _msgData() internal view returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: @openzeppelin/contracts/ownership/Ownable.sol
pragma solidity ^0.5.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Returns true if the caller is the current owner.
*/
function isOwner() public view returns (bool) {
return _msgSender() == _owner;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File: contracts/src/common/storage/EternalStorage.sol
pragma solidity 0.5.17;
/**
* Module for persisting states.
* Stores a map for `uint256`, `string`, `address`, `bytes32`, `bool`, and `int256` type with `bytes32` type as a key.
*/
contract EternalStorage {
address private currentOwner = msg.sender;
mapping(bytes32 => uint256) private uIntStorage;
mapping(bytes32 => string) private stringStorage;
mapping(bytes32 => address) private addressStorage;
mapping(bytes32 => bytes32) private bytesStorage;
mapping(bytes32 => bool) private boolStorage;
mapping(bytes32 => int256) private intStorage;
/**
* Modifiers to validate that only the owner can execute.
*/
modifier onlyCurrentOwner() {
require(msg.sender == currentOwner, "not current owner");
_;
}
/**
* Transfer the owner.
* Only the owner can execute this function.
*/
function changeOwner(address _newOwner) external {
require(msg.sender == currentOwner, "not current owner");
currentOwner = _newOwner;
}
// *** Getter Methods ***
/**
* Returns the value of the `uint256` type that mapped to the given key.
*/
function getUint(bytes32 _key) external view returns (uint256) {
return uIntStorage[_key];
}
/**
* Returns the value of the `string` type that mapped to the given key.
*/
function getString(bytes32 _key) external view returns (string memory) {
return stringStorage[_key];
}
/**
* Returns the value of the `address` type that mapped to the given key.
*/
function getAddress(bytes32 _key) external view returns (address) {
return addressStorage[_key];
}
/**
* Returns the value of the `bytes32` type that mapped to the given key.
*/
function getBytes(bytes32 _key) external view returns (bytes32) {
return bytesStorage[_key];
}
/**
* Returns the value of the `bool` type that mapped to the given key.
*/
function getBool(bytes32 _key) external view returns (bool) {
return boolStorage[_key];
}
/**
* Returns the value of the `int256` type that mapped to the given key.
*/
function getInt(bytes32 _key) external view returns (int256) {
return intStorage[_key];
}
// *** Setter Methods ***
/**
* Maps a value of `uint256` type to a given key.
* Only the owner can execute this function.
*/
function setUint(bytes32 _key, uint256 _value) external onlyCurrentOwner {
uIntStorage[_key] = _value;
}
/**
* Maps a value of `string` type to a given key.
* Only the owner can execute this function.
*/
function setString(bytes32 _key, string calldata _value)
external
onlyCurrentOwner
{
stringStorage[_key] = _value;
}
/**
* Maps a value of `address` type to a given key.
* Only the owner can execute this function.
*/
function setAddress(bytes32 _key, address _value)
external
onlyCurrentOwner
{
addressStorage[_key] = _value;
}
/**
* Maps a value of `bytes32` type to a given key.
* Only the owner can execute this function.
*/
function setBytes(bytes32 _key, bytes32 _value) external onlyCurrentOwner {
bytesStorage[_key] = _value;
}
/**
* Maps a value of `bool` type to a given key.
* Only the owner can execute this function.
*/
function setBool(bytes32 _key, bool _value) external onlyCurrentOwner {
boolStorage[_key] = _value;
}
/**
* Maps a value of `int256` type to a given key.
* Only the owner can execute this function.
*/
function setInt(bytes32 _key, int256 _value) external onlyCurrentOwner {
intStorage[_key] = _value;
}
// *** Delete Methods ***
/**
* Deletes the value of the `uint256` type that mapped to the given key.
* Only the owner can execute this function.
*/
function deleteUint(bytes32 _key) external onlyCurrentOwner {
delete uIntStorage[_key];
}
/**
* Deletes the value of the `string` type that mapped to the given key.
* Only the owner can execute this function.
*/
function deleteString(bytes32 _key) external onlyCurrentOwner {
delete stringStorage[_key];
}
/**
* Deletes the value of the `address` type that mapped to the given key.
* Only the owner can execute this function.
*/
function deleteAddress(bytes32 _key) external onlyCurrentOwner {
delete addressStorage[_key];
}
/**
* Deletes the value of the `bytes32` type that mapped to the given key.
* Only the owner can execute this function.
*/
function deleteBytes(bytes32 _key) external onlyCurrentOwner {
delete bytesStorage[_key];
}
/**
* Deletes the value of the `bool` type that mapped to the given key.
* Only the owner can execute this function.
*/
function deleteBool(bytes32 _key) external onlyCurrentOwner {
delete boolStorage[_key];
}
/**
* Deletes the value of the `int256` type that mapped to the given key.
* Only the owner can execute this function.
*/
function deleteInt(bytes32 _key) external onlyCurrentOwner {
delete intStorage[_key];
}
}
// File: contracts/src/common/storage/UsingStorage.sol
pragma solidity 0.5.17;
/**
* Module for contrast handling EternalStorage.
*/
contract UsingStorage is Ownable, IUsingStorage {
address private _storage;
/**
* Modifier to verify that EternalStorage is set.
*/
modifier hasStorage() {
require(_storage != address(0), "storage is not set");
_;
}
/**
* Returns the set EternalStorage instance.
*/
function eternalStorage()
internal
view
hasStorage
returns (EternalStorage)
{
return EternalStorage(_storage);
}
/**
* Returns the set EternalStorage address.
*/
function getStorageAddress() external view hasStorage returns (address) {
return _storage;
}
/**
* Create a new EternalStorage contract.
* This function call will fail if the EternalStorage contract is already set.
* Also, only the owner can execute it.
*/
function createStorage() external onlyOwner {
require(_storage == address(0), "storage is set");
EternalStorage tmp = new EternalStorage();
_storage = address(tmp);
}
/**
* Assigns the EternalStorage contract that has already been created.
* Only the owner can execute this function.
*/
function setStorage(address _storageAddress) external onlyOwner {
_storage = _storageAddress;
}
/**
* Delegates the owner of the current EternalStorage contract.
* Only the owner can execute this function.
*/
function changeOwner(address newOwner) external onlyOwner {
EternalStorage(_storage).changeOwner(newOwner);
}
}
// File: contracts/src/lockup/LockupStorage.sol
pragma solidity 0.5.17;
contract LockupStorage is UsingStorage {
using SafeMath for uint256;
uint256 private constant BASIS = 100000000000000000000000000000000;
//AllValue
function setStorageAllValue(uint256 _value) internal {
bytes32 key = getStorageAllValueKey();
eternalStorage().setUint(key, _value);
}
function getStorageAllValue() public view returns (uint256) {
bytes32 key = getStorageAllValueKey();
return eternalStorage().getUint(key);
}
function getStorageAllValueKey() private pure returns (bytes32) {
return keccak256(abi.encodePacked("_allValue"));
}
//Value
function setStorageValue(
address _property,
address _sender,
uint256 _value
) internal {
bytes32 key = getStorageValueKey(_property, _sender);
eternalStorage().setUint(key, _value);
}
function getStorageValue(address _property, address _sender)
public
view
returns (uint256)
{
bytes32 key = getStorageValueKey(_property, _sender);
return eternalStorage().getUint(key);
}
function getStorageValueKey(address _property, address _sender)
private
pure
returns (bytes32)
{
return keccak256(abi.encodePacked("_value", _property, _sender));
}
//PropertyValue
function setStoragePropertyValue(address _property, uint256 _value)
internal
{
bytes32 key = getStoragePropertyValueKey(_property);
eternalStorage().setUint(key, _value);
}
function getStoragePropertyValue(address _property)
public
view
returns (uint256)
{
bytes32 key = getStoragePropertyValueKey(_property);
return eternalStorage().getUint(key);
}
function getStoragePropertyValueKey(address _property)
private
pure
returns (bytes32)
{
return keccak256(abi.encodePacked("_propertyValue", _property));
}
//InterestPrice
function setStorageInterestPrice(address _property, uint256 _value)
internal
{
// The previously used function
// This function is only used in testing
eternalStorage().setUint(getStorageInterestPriceKey(_property), _value);
}
function getStorageInterestPrice(address _property)
public
view
returns (uint256)
{
return eternalStorage().getUint(getStorageInterestPriceKey(_property));
}
function getStorageInterestPriceKey(address _property)
private
pure
returns (bytes32)
{
return keccak256(abi.encodePacked("_interestTotals", _property));
}
//LastInterestPrice
function setStorageLastInterestPrice(
address _property,
address _user,
uint256 _value
) internal {
eternalStorage().setUint(
getStorageLastInterestPriceKey(_property, _user),
_value
);
}
function getStorageLastInterestPrice(address _property, address _user)
public
view
returns (uint256)
{
return
eternalStorage().getUint(
getStorageLastInterestPriceKey(_property, _user)
);
}
function getStorageLastInterestPriceKey(address _property, address _user)
private
pure
returns (bytes32)
{
return
keccak256(
abi.encodePacked("_lastLastInterestPrice", _property, _user)
);
}
//LastSameRewardsAmountAndBlock
function setStorageLastSameRewardsAmountAndBlock(
uint256 _amount,
uint256 _block
) internal {
uint256 record = _amount.mul(BASIS).add(_block);
eternalStorage().setUint(
getStorageLastSameRewardsAmountAndBlockKey(),
record
);
}
function getStorageLastSameRewardsAmountAndBlock()
public
view
returns (uint256 _amount, uint256 _block)
{
uint256 record = eternalStorage().getUint(
getStorageLastSameRewardsAmountAndBlockKey()
);
uint256 amount = record.div(BASIS);
uint256 blockNumber = record.sub(amount.mul(BASIS));
return (amount, blockNumber);
}
function getStorageLastSameRewardsAmountAndBlockKey()
private
pure
returns (bytes32)
{
return keccak256(abi.encodePacked("_LastSameRewardsAmountAndBlock"));
}
//CumulativeGlobalRewards
function setStorageCumulativeGlobalRewards(uint256 _value) internal {
eternalStorage().setUint(
getStorageCumulativeGlobalRewardsKey(),
_value
);
}
function getStorageCumulativeGlobalRewards() public view returns (uint256) {
return eternalStorage().getUint(getStorageCumulativeGlobalRewardsKey());
}
function getStorageCumulativeGlobalRewardsKey()
private
pure
returns (bytes32)
{
return keccak256(abi.encodePacked("_cumulativeGlobalRewards"));
}
//PendingWithdrawal
function setStoragePendingInterestWithdrawal(
address _property,
address _user,
uint256 _value
) internal {
eternalStorage().setUint(
getStoragePendingInterestWithdrawalKey(_property, _user),
_value
);
}
function getStoragePendingInterestWithdrawal(
address _property,
address _user
) public view returns (uint256) {
return
eternalStorage().getUint(
getStoragePendingInterestWithdrawalKey(_property, _user)
);
}
function getStoragePendingInterestWithdrawalKey(
address _property,
address _user
) private pure returns (bytes32) {
return
keccak256(
abi.encodePacked("_pendingInterestWithdrawal", _property, _user)
);
}
//DIP4GenesisBlock
function setStorageDIP4GenesisBlock(uint256 _block) internal {
eternalStorage().setUint(getStorageDIP4GenesisBlockKey(), _block);
}
function getStorageDIP4GenesisBlock() public view returns (uint256) {
return eternalStorage().getUint(getStorageDIP4GenesisBlockKey());
}
function getStorageDIP4GenesisBlockKey() private pure returns (bytes32) {
return keccak256(abi.encodePacked("_dip4GenesisBlock"));
}
//lastStakedInterestPrice
function setStorageLastStakedInterestPrice(
address _property,
address _user,
uint256 _value
) internal {
eternalStorage().setUint(
getStorageLastStakedInterestPriceKey(_property, _user),
_value
);
}
function getStorageLastStakedInterestPrice(address _property, address _user)
public
view
returns (uint256)
{
return
eternalStorage().getUint(
getStorageLastStakedInterestPriceKey(_property, _user)
);
}
function getStorageLastStakedInterestPriceKey(
address _property,
address _user
) private pure returns (bytes32) {
return
keccak256(
abi.encodePacked("_lastStakedInterestPrice", _property, _user)
);
}
//lastStakesChangedCumulativeReward
function setStorageLastStakesChangedCumulativeReward(uint256 _value)
internal
{
eternalStorage().setUint(
getStorageLastStakesChangedCumulativeRewardKey(),
_value
);
}
function getStorageLastStakesChangedCumulativeReward()
public
view
returns (uint256)
{
return
eternalStorage().getUint(
getStorageLastStakesChangedCumulativeRewardKey()
);
}
function getStorageLastStakesChangedCumulativeRewardKey()
private
pure
returns (bytes32)
{
return
keccak256(abi.encodePacked("_lastStakesChangedCumulativeReward"));
}
//LastCumulativeHoldersRewardPrice
function setStorageLastCumulativeHoldersRewardPrice(uint256 _holders)
internal
{
eternalStorage().setUint(
getStorageLastCumulativeHoldersRewardPriceKey(),
_holders
);
}
function getStorageLastCumulativeHoldersRewardPrice()
public
view
returns (uint256)
{
return
eternalStorage().getUint(
getStorageLastCumulativeHoldersRewardPriceKey()
);
}
function getStorageLastCumulativeHoldersRewardPriceKey()
private
pure
returns (bytes32)
{
return keccak256(abi.encodePacked("0lastCumulativeHoldersRewardPrice"));
}
//LastCumulativeInterestPrice
function setStorageLastCumulativeInterestPrice(uint256 _interest) internal {
eternalStorage().setUint(
getStorageLastCumulativeInterestPriceKey(),
_interest
);
}
function getStorageLastCumulativeInterestPrice()
public
view
returns (uint256)
{
return
eternalStorage().getUint(
getStorageLastCumulativeInterestPriceKey()
);
}
function getStorageLastCumulativeInterestPriceKey()
private
pure
returns (bytes32)
{
return keccak256(abi.encodePacked("0lastCumulativeInterestPrice"));
}
//LastCumulativeHoldersRewardAmountPerProperty
function setStorageLastCumulativeHoldersRewardAmountPerProperty(
address _property,
uint256 _value
) internal {
eternalStorage().setUint(
getStorageLastCumulativeHoldersRewardAmountPerPropertyKey(
_property
),
_value
);
}
function getStorageLastCumulativeHoldersRewardAmountPerProperty(
address _property
) public view returns (uint256) {
return
eternalStorage().getUint(
getStorageLastCumulativeHoldersRewardAmountPerPropertyKey(
_property
)
);
}
function getStorageLastCumulativeHoldersRewardAmountPerPropertyKey(
address _property
) private pure returns (bytes32) {
return
keccak256(
abi.encodePacked(
"0lastCumulativeHoldersRewardAmountPerProperty",
_property
)
);
}
//LastCumulativeHoldersRewardPricePerProperty
function setStorageLastCumulativeHoldersRewardPricePerProperty(
address _property,
uint256 _price
) internal {
eternalStorage().setUint(
getStorageLastCumulativeHoldersRewardPricePerPropertyKey(_property),
_price
);
}
function getStorageLastCumulativeHoldersRewardPricePerProperty(
address _property
) public view returns (uint256) {
return
eternalStorage().getUint(
getStorageLastCumulativeHoldersRewardPricePerPropertyKey(
_property
)
);
}
function getStorageLastCumulativeHoldersRewardPricePerPropertyKey(
address _property
) private pure returns (bytes32) {
return
keccak256(
abi.encodePacked(
"0lastCumulativeHoldersRewardPricePerProperty",
_property
)
);
}
//cap
function setStorageCap(uint256 _cap) internal {
eternalStorage().setUint(getStorageCapKey(), _cap);
}
function getStorageCap() public view returns (uint256) {
return eternalStorage().getUint(getStorageCapKey());
}
function getStorageCapKey() private pure returns (bytes32) {
return keccak256(abi.encodePacked("_cap"));
}
//CumulativeHoldersRewardCap
function setStorageCumulativeHoldersRewardCap(uint256 _value) internal {
eternalStorage().setUint(
getStorageCumulativeHoldersRewardCapKey(),
_value
);
}
function getStorageCumulativeHoldersRewardCap()
public
view
returns (uint256)
{
return
eternalStorage().getUint(getStorageCumulativeHoldersRewardCapKey());
}
function getStorageCumulativeHoldersRewardCapKey()
private
pure
returns (bytes32)
{
return keccak256(abi.encodePacked("_cumulativeHoldersRewardCap"));
}
//LastCumulativeHoldersPriceCap
function setStorageLastCumulativeHoldersPriceCap(uint256 _value) internal {
eternalStorage().setUint(
getStorageLastCumulativeHoldersPriceCapKey(),
_value
);
}
function getStorageLastCumulativeHoldersPriceCap()
public
view
returns (uint256)
{
return
eternalStorage().getUint(
getStorageLastCumulativeHoldersPriceCapKey()
);
}
function getStorageLastCumulativeHoldersPriceCapKey()
private
pure
returns (bytes32)
{
return keccak256(abi.encodePacked("_lastCumulativeHoldersPriceCap"));
}
//InitialCumulativeHoldersRewardCap
function setStorageInitialCumulativeHoldersRewardCap(
address _property,
uint256 _value
) internal {
eternalStorage().setUint(
getStorageInitialCumulativeHoldersRewardCapKey(_property),
_value
);
}
function getStorageInitialCumulativeHoldersRewardCap(address _property)
public
view
returns (uint256)
{
return
eternalStorage().getUint(
getStorageInitialCumulativeHoldersRewardCapKey(_property)
);
}
function getStorageInitialCumulativeHoldersRewardCapKey(address _property)
private
pure
returns (bytes32)
{
return
keccak256(
abi.encodePacked(
"_initialCumulativeHoldersRewardCap",
_property
)
);
}
//FallbackInitialCumulativeHoldersRewardCap
function setStorageFallbackInitialCumulativeHoldersRewardCap(uint256 _value)
internal
{
eternalStorage().setUint(
getStorageFallbackInitialCumulativeHoldersRewardCapKey(),
_value
);
}
function getStorageFallbackInitialCumulativeHoldersRewardCap()
public
view
returns (uint256)
{
return
eternalStorage().getUint(
getStorageFallbackInitialCumulativeHoldersRewardCapKey()
);
}
function getStorageFallbackInitialCumulativeHoldersRewardCapKey()
private
pure
returns (bytes32)
{
return
keccak256(
abi.encodePacked("_fallbackInitialCumulativeHoldersRewardCap")
);
}
}
// File: contracts/interface/IDevMinter.sol
// SPDX-License-Identifier: MPL-2.0
pragma solidity >=0.5.17;
interface IDevMinter {
function mint(address account, uint256 amount) external returns (bool);
function renounceMinter() external;
}
// File: contracts/interface/IProperty.sol
// SPDX-License-Identifier: MPL-2.0
pragma solidity >=0.5.17;
interface IProperty {
function author() external view returns (address);
function changeAuthor(address _nextAuthor) external;
function changeName(string calldata _name) external;
function changeSymbol(string calldata _symbol) external;
function withdraw(address _sender, uint256 _value) external;
}
// File: contracts/interface/IPolicy.sol
// SPDX-License-Identifier: MPL-2.0
pragma solidity >=0.5.17;
interface IPolicy {
function rewards(uint256 _lockups, uint256 _assets)
external
view
returns (uint256);
function holdersShare(uint256 _amount, uint256 _lockups)
external
view
returns (uint256);
function authenticationFee(uint256 _assets, uint256 _propertyAssets)
external
view
returns (uint256);
function marketApproval(uint256 _agree, uint256 _opposite)
external
view
returns (bool);
function policyApproval(uint256 _agree, uint256 _opposite)
external
view
returns (bool);
function marketVotingBlocks() external view returns (uint256);
function policyVotingBlocks() external view returns (uint256);
function shareOfTreasury(uint256 _supply) external view returns (uint256);
function treasury() external view returns (address);
function capSetter() external view returns (address);
}
// File: contracts/interface/IAllocator.sol
// SPDX-License-Identifier: MPL-2.0
pragma solidity >=0.5.17;
interface IAllocator {
function beforeBalanceChange(
address _property,
address _from,
address _to
) external;
function calculateMaxRewardsPerBlock() external view returns (uint256);
}
// File: contracts/interface/ILockup.sol
// SPDX-License-Identifier: MPL-2.0
pragma solidity >=0.5.17;
interface ILockup {
function lockup(
address _from,
address _property,
uint256 _value
) external;
function update() external;
function withdraw(address _property, uint256 _amount) external;
function calculateCumulativeRewardPrices()
external
view
returns (
uint256 _reward,
uint256 _holders,
uint256 _interest,
uint256 _holdersCap
);
function calculateRewardAmount(address _property)
external
view
returns (uint256, uint256);
/**
* caution!!!this function is deprecated!!!
* use calculateRewardAmount
*/
function calculateCumulativeHoldersRewardAmount(address _property)
external
view
returns (uint256);
function getPropertyValue(address _property)
external
view
returns (uint256);
function getAllValue() external view returns (uint256);
function getValue(address _property, address _sender)
external
view
returns (uint256);
function calculateWithdrawableInterestAmount(
address _property,
address _user
) external view returns (uint256);
function cap() external view returns (uint256);
function updateCap(uint256 _cap) external;
function devMinter() external view returns (address);
}
// File: contracts/interface/IMetricsGroup.sol
// SPDX-License-Identifier: MPL-2.0
pragma solidity >=0.5.17;
interface IMetricsGroup {
function addGroup(address _addr) external;
function removeGroup(address _addr) external;
function isGroup(address _addr) external view returns (bool);
function totalIssuedMetrics() external view returns (uint256);
function hasAssets(address _property) external view returns (bool);
function getMetricsCountPerProperty(address _property)
external
view
returns (uint256);
function totalAuthenticatedProperties() external view returns (uint256);
}
// File: contracts/src/lockup/Lockup.sol
pragma solidity 0.5.17;
// prettier-ignore
/**
* A contract that manages the staking of DEV tokens and calculates rewards.
* Staking and the following mechanism determines that reward calculation.
*
* Variables:
* -`M`: Maximum mint amount per block determined by Allocator contract
* -`B`: Number of blocks during staking
* -`P`: Total number of staking locked up in a Property contract
* -`S`: Total number of staking locked up in all Property contracts
* -`U`: Number of staking per account locked up in a Property contract
*
* Formula:
* Staking Rewards = M * B * (P / S) * (U / P)
*
* Note:
* -`M`, `P` and `S` vary from block to block, and the variation cannot be predicted.
* -`B` is added every time the Ethereum block is created.
* - Only `U` and `B` are predictable variables.
* - As `M`, `P` and `S` cannot be observed from a staker, the "cumulative sum" is often used to calculate ratio variation with history.
* - Reward withdrawal always withdraws the total withdrawable amount.
*
* Scenario:
* - Assume `M` is fixed at 500
* - Alice stakes 100 DEV on Property-A (Alice's staking state on Property-A: `M`=500, `B`=0, `P`=100, `S`=100, `U`=100)
* - After 10 blocks, Bob stakes 60 DEV on Property-B (Alice's staking state on Property-A: `M`=500, `B`=10, `P`=100, `S`=160, `U`=100)
* - After 10 blocks, Carol stakes 40 DEV on Property-A (Alice's staking state on Property-A: `M`=500, `B`=20, `P`=140, `S`=200, `U`=100)
* - After 10 blocks, Alice withdraws Property-A staking reward. The reward at this time is 5000 DEV (10 blocks * 500 DEV) + 3125 DEV (10 blocks * 62.5% * 500 DEV) + 2500 DEV (10 blocks * 50% * 500 DEV).
*/
contract Lockup is ILockup, UsingConfig, LockupStorage {
using SafeMath for uint256;
using Decimals for uint256;
address public devMinter;
struct RewardPrices {
uint256 reward;
uint256 holders;
uint256 interest;
uint256 holdersCap;
}
event Lockedup(address _from, address _property, uint256 _value);
event UpdateCap(uint256 _cap);
/**
* Initialize the passed address as AddressConfig address and Devminter.
*/
constructor(address _config, address _devMinter)
public
UsingConfig(_config)
{
devMinter = _devMinter;
}
/**
* Adds staking.
* Only the Dev contract can execute this function.
*/
function lockup(
address _from,
address _property,
uint256 _value
) external {
/**
* Validates the sender is Dev contract.
*/
require(msg.sender == config().token(), "this is illegal address");
/**
* Validates _value is not 0.
*/
require(_value != 0, "illegal lockup value");
/**
* Validates the passed Property has greater than 1 asset.
*/
require(
IMetricsGroup(config().metricsGroup()).hasAssets(_property),
"unable to stake to unauthenticated property"
);
/**
* Since the reward per block that can be withdrawn will change with the addition of staking,
* saves the undrawn withdrawable reward before addition it.
*/
RewardPrices memory prices = updatePendingInterestWithdrawal(
_property,
_from
);
/**
* Saves variables that should change due to the addition of staking.
*/
updateValues(true, _from, _property, _value, prices);
emit Lockedup(_from, _property, _value);
}
/**
* Withdraw staking.
* Releases staking, withdraw rewards, and transfer the staked and withdraw rewards amount to the sender.
*/
function withdraw(address _property, uint256 _amount) external {
/**
* Validates the sender is staking to the target Property.
*/
require(
hasValue(_property, msg.sender, _amount),
"insufficient tokens staked"
);
/**
* Withdraws the staking reward
*/
RewardPrices memory prices = _withdrawInterest(_property);
/**
* Transfer the staked amount to the sender.
*/
if (_amount != 0) {
IProperty(_property).withdraw(msg.sender, _amount);
}
/**
* Saves variables that should change due to the canceling staking..
*/
updateValues(false, msg.sender, _property, _amount, prices);
}
/**
* get cap
*/
function cap() external view returns (uint256) {
return getStorageCap();
}
/**
* set cap
*/
function updateCap(uint256 _cap) external {
address setter = IPolicy(config().policy()).capSetter();
require(setter == msg.sender, "illegal access");
/**
* Updates cumulative amount of the holders reward cap
*/
(
,
uint256 holdersPrice,
,
uint256 cCap
) = calculateCumulativeRewardPrices();
// TODO: When this function is improved to be called on-chain, the source of `getStorageLastCumulativeHoldersPriceCap` can be rewritten to `getStorageLastCumulativeHoldersRewardPrice`.
setStorageCumulativeHoldersRewardCap(cCap);
setStorageLastCumulativeHoldersPriceCap(holdersPrice);
setStorageCap(_cap);
emit UpdateCap(_cap);
}
/**
* Returns the latest cap
*/
function _calculateLatestCap(uint256 _holdersPrice)
private
view
returns (uint256)
{
uint256 cCap = getStorageCumulativeHoldersRewardCap();
uint256 lastHoldersPrice = getStorageLastCumulativeHoldersPriceCap();
uint256 additionalCap = _holdersPrice.sub(lastHoldersPrice).mul(
getStorageCap()
);
return cCap.add(additionalCap);
}
/**
* Store staking states as a snapshot.
*/
function beforeStakesChanged(
address _property,
address _user,
RewardPrices memory _prices
) private {
/**
* Gets latest cumulative holders reward for the passed Property.
*/
uint256 cHoldersReward = _calculateCumulativeHoldersRewardAmount(
_prices.holders,
_property
);
/**
* Sets `InitialCumulativeHoldersRewardCap`.
* Records this value only when the "first staking to the passed Property" is transacted.
*/
if (
getStorageLastCumulativeHoldersRewardPricePerProperty(_property) ==
0 &&
getStorageInitialCumulativeHoldersRewardCap(_property) == 0 &&
getStoragePropertyValue(_property) == 0
) {
setStorageInitialCumulativeHoldersRewardCap(
_property,
_prices.holdersCap
);
}
/**
* Store each value.
*/
setStorageLastStakedInterestPrice(_property, _user, _prices.interest);
setStorageLastStakesChangedCumulativeReward(_prices.reward);
setStorageLastCumulativeHoldersRewardPrice(_prices.holders);
setStorageLastCumulativeInterestPrice(_prices.interest);
setStorageLastCumulativeHoldersRewardAmountPerProperty(
_property,
cHoldersReward
);
setStorageLastCumulativeHoldersRewardPricePerProperty(
_property,
_prices.holders
);
setStorageCumulativeHoldersRewardCap(_prices.holdersCap);
setStorageLastCumulativeHoldersPriceCap(_prices.holders);
}
/**
* Gets latest value of cumulative sum of the reward amount, cumulative sum of the holders reward per stake, and cumulative sum of the stakers reward per stake.
*/
function calculateCumulativeRewardPrices()
public
view
returns (
uint256 _reward,
uint256 _holders,
uint256 _interest,
uint256 _holdersCap
)
{
uint256 lastReward = getStorageLastStakesChangedCumulativeReward();
uint256 lastHoldersPrice = getStorageLastCumulativeHoldersRewardPrice();
uint256 lastInterestPrice = getStorageLastCumulativeInterestPrice();
uint256 allStakes = getStorageAllValue();
/**
* Gets latest cumulative sum of the reward amount.
*/
(uint256 reward, ) = dry();
uint256 mReward = reward.mulBasis();
/**
* Calculates reward unit price per staking.
* Later, the last cumulative sum of the reward amount is subtracted because to add the last recorded holder/staking reward.
*/
uint256 price = allStakes > 0
? mReward.sub(lastReward).div(allStakes)
: 0;
/**
* Calculates the holders reward out of the total reward amount.
*/
uint256 holdersShare = IPolicy(config().policy()).holdersShare(
price,
allStakes
);
/**
* Calculates and returns each reward.
*/
uint256 holdersPrice = holdersShare.add(lastHoldersPrice);
uint256 interestPrice = price.sub(holdersShare).add(lastInterestPrice);
uint256 cCap = _calculateLatestCap(holdersPrice);
return (mReward, holdersPrice, interestPrice, cCap);
}
/**
* Calculates cumulative sum of the holders reward per Property.
* To save computing resources, it receives the latest holder rewards from a caller.
*/
function _calculateCumulativeHoldersRewardAmount(
uint256 _holdersPrice,
address _property
) private view returns (uint256) {
(uint256 cHoldersReward, uint256 lastReward) = (
getStorageLastCumulativeHoldersRewardAmountPerProperty(_property),
getStorageLastCumulativeHoldersRewardPricePerProperty(_property)
);
/**
* `cHoldersReward` contains the calculation of `lastReward`, so subtract it here.
*/
uint256 additionalHoldersReward = _holdersPrice.sub(lastReward).mul(
getStoragePropertyValue(_property)
);
/**
* Calculates and returns the cumulative sum of the holder reward by adds the last recorded holder reward and the latest holder reward.
*/
return cHoldersReward.add(additionalHoldersReward);
}
/**
* Calculates cumulative sum of the holders reward per Property.
* caution!!!this function is deprecated!!!
* use calculateRewardAmount
*/
function calculateCumulativeHoldersRewardAmount(address _property)
external
view
returns (uint256)
{
(, uint256 holders, , ) = calculateCumulativeRewardPrices();
return _calculateCumulativeHoldersRewardAmount(holders, _property);
}
/**
* Calculates holders reward and cap per Property.
*/
function calculateRewardAmount(address _property)
external
view
returns (uint256, uint256)
{
(
,
uint256 holders,
,
uint256 holdersCap
) = calculateCumulativeRewardPrices();
uint256 initialCap = _getInitialCap(_property);
/**
* Calculates the cap
*/
uint256 capValue = holdersCap.sub(initialCap);
return (
_calculateCumulativeHoldersRewardAmount(holders, _property),
capValue
);
}
function _getInitialCap(address _property) private view returns (uint256) {
uint256 initialCap = getStorageInitialCumulativeHoldersRewardCap(
_property
);
if (initialCap > 0) {
return initialCap;
}
// Fallback when there is a data past staked.
if (
getStorageLastCumulativeHoldersRewardPricePerProperty(_property) >
0 ||
getStoragePropertyValue(_property) > 0
) {
return getStorageFallbackInitialCumulativeHoldersRewardCap();
}
return 0;
}
/**
* Updates cumulative sum of the maximum mint amount calculated by Allocator contract, the latest maximum mint amount per block,
* and the last recorded block number.
* The cumulative sum of the maximum mint amount is always added.
* By recording that value when the staker last stakes, the difference from the when the staker stakes can be calculated.
*/
function update() public {
/**
* Gets the cumulative sum of the maximum mint amount and the maximum mint number per block.
*/
(uint256 _nextRewards, uint256 _amount) = dry();
/**
* Records each value and the latest block number.
*/
setStorageCumulativeGlobalRewards(_nextRewards);
setStorageLastSameRewardsAmountAndBlock(_amount, block.number);
}
/**
* Referring to the values recorded in each storage to returns the latest cumulative sum of the maximum mint amount and the latest maximum mint amount per block.
*/
function dry()
private
view
returns (uint256 _nextRewards, uint256 _amount)
{
/**
* Gets the latest mint amount per block from Allocator contract.
*/
uint256 rewardsAmount = IAllocator(config().allocator())
.calculateMaxRewardsPerBlock();
/**
* Gets the maximum mint amount per block, and the last recorded block number from `LastSameRewardsAmountAndBlock` storage.
*/
(
uint256 lastAmount,
uint256 lastBlock
) = getStorageLastSameRewardsAmountAndBlock();
/**
* If the recorded maximum mint amount per block and the result of the Allocator contract are different,
* the result of the Allocator contract takes precedence as a maximum mint amount per block.
*/
uint256 lastMaxRewards = lastAmount == rewardsAmount
? rewardsAmount
: lastAmount;
/**
* Calculates the difference between the latest block number and the last recorded block number.
*/
uint256 blocks = lastBlock > 0 ? block.number.sub(lastBlock) : 0;
/**
* Adds the calculated new cumulative maximum mint amount to the recorded cumulative maximum mint amount.
*/
uint256 additionalRewards = lastMaxRewards.mul(blocks);
uint256 nextRewards = getStorageCumulativeGlobalRewards().add(
additionalRewards
);
/**
* Returns the latest theoretical cumulative sum of maximum mint amount and maximum mint amount per block.
*/
return (nextRewards, rewardsAmount);
}
/**
* Returns the staker reward as interest.
*/
function _calculateInterestAmount(address _property, address _user)
private
view
returns (
uint256 _amount,
uint256 _interestPrice,
RewardPrices memory _prices
)
{
/**
* Get the amount the user is staking for the Property.
*/
uint256 lockedUpPerAccount = getStorageValue(_property, _user);
/**
* Gets the cumulative sum of the interest price recorded the last time you withdrew.
*/
uint256 lastInterest = getStorageLastStakedInterestPrice(
_property,
_user
);
/**
* Gets the latest cumulative sum of the interest price.
*/
(
uint256 reward,
uint256 holders,
uint256 interest,
uint256 holdersCap
) = calculateCumulativeRewardPrices();
/**
* Calculates and returns the latest withdrawable reward amount from the difference.
*/
uint256 result = interest >= lastInterest
? interest.sub(lastInterest).mul(lockedUpPerAccount).divBasis()
: 0;
return (
result,
interest,
RewardPrices(reward, holders, interest, holdersCap)
);
}
/**
* Returns the total rewards currently available for withdrawal. (For calling from inside the contract)
*/
function _calculateWithdrawableInterestAmount(
address _property,
address _user
) private view returns (uint256 _amount, RewardPrices memory _prices) {
/**
* If the passed Property has not authenticated, returns always 0.
*/
if (
IMetricsGroup(config().metricsGroup()).hasAssets(_property) == false
) {
return (0, RewardPrices(0, 0, 0, 0));
}
/**
* Gets the reward amount in saved without withdrawal.
*/
uint256 pending = getStoragePendingInterestWithdrawal(_property, _user);
/**
* Gets the reward amount of before DIP4.
*/
uint256 legacy = __legacyWithdrawableInterestAmount(_property, _user);
/**
* Gets the latest withdrawal reward amount.
*/
(
uint256 amount,
,
RewardPrices memory prices
) = _calculateInterestAmount(_property, _user);
/**
* Returns the sum of all values.
*/
uint256 withdrawableAmount = amount.add(pending).add(legacy);
return (withdrawableAmount, prices);
}
/**
* Returns the total rewards currently available for withdrawal. (For calling from external of the contract)
*/
function calculateWithdrawableInterestAmount(
address _property,
address _user
) public view returns (uint256) {
(uint256 amount, ) = _calculateWithdrawableInterestAmount(
_property,
_user
);
return amount;
}
/**
* Withdraws staking reward as an interest.
*/
function _withdrawInterest(address _property)
private
returns (RewardPrices memory _prices)
{
/**
* Gets the withdrawable amount.
*/
(
uint256 value,
RewardPrices memory prices
) = _calculateWithdrawableInterestAmount(_property, msg.sender);
/**
* Sets the unwithdrawn reward amount to 0.
*/
setStoragePendingInterestWithdrawal(_property, msg.sender, 0);
/**
* Updates the staking status to avoid double rewards.
*/
setStorageLastStakedInterestPrice(
_property,
msg.sender,
prices.interest
);
__updateLegacyWithdrawableInterestAmount(_property, msg.sender);
/**
* Mints the reward.
*/
require(
IDevMinter(devMinter).mint(msg.sender, value),
"dev mint failed"
);
/**
* Since the total supply of tokens has changed, updates the latest maximum mint amount.
*/
update();
return prices;
}
/**
* Status updates with the addition or release of staking.
*/
function updateValues(
bool _addition,
address _account,
address _property,
uint256 _value,
RewardPrices memory _prices
) private {
beforeStakesChanged(_property, _account, _prices);
/**
* If added staking:
*/
if (_addition) {
/**
* Updates the current staking amount of the protocol total.
*/
addAllValue(_value);
/**
* Updates the current staking amount of the Property.
*/
addPropertyValue(_property, _value);
/**
* Updates the user's current staking amount in the Property.
*/
addValue(_property, _account, _value);
/**
* If released staking:
*/
} else {
/**
* Updates the current staking amount of the protocol total.
*/
subAllValue(_value);
/**
* Updates the current staking amount of the Property.
*/
subPropertyValue(_property, _value);
/**
* Updates the current staking amount of the Property.
*/
subValue(_property, _account, _value);
}
/**
* Since each staking amount has changed, updates the latest maximum mint amount.
*/
update();
}
/**
* Returns the staking amount of the protocol total.
*/
function getAllValue() external view returns (uint256) {
return getStorageAllValue();
}
/**
* Adds the staking amount of the protocol total.
*/
function addAllValue(uint256 _value) private {
uint256 value = getStorageAllValue();
value = value.add(_value);
setStorageAllValue(value);
}
/**
* Subtracts the staking amount of the protocol total.
*/
function subAllValue(uint256 _value) private {
uint256 value = getStorageAllValue();
value = value.sub(_value);
setStorageAllValue(value);
}
/**
* Returns the user's staking amount in the Property.
*/
function getValue(address _property, address _sender)
external
view
returns (uint256)
{
return getStorageValue(_property, _sender);
}
/**
* Adds the user's staking amount in the Property.
*/
function addValue(
address _property,
address _sender,
uint256 _value
) private {
uint256 value = getStorageValue(_property, _sender);
value = value.add(_value);
setStorageValue(_property, _sender, value);
}
/**
* Subtracts the user's staking amount in the Property.
*/
function subValue(
address _property,
address _sender,
uint256 _value
) private {
uint256 value = getStorageValue(_property, _sender);
value = value.sub(_value);
setStorageValue(_property, _sender, value);
}
/**
* Returns whether the user is staking in the Property.
*/
function hasValue(
address _property,
address _sender,
uint256 _amount
) private view returns (bool) {
uint256 value = getStorageValue(_property, _sender);
return value >= _amount;
}
/**
* Returns the staking amount of the Property.
*/
function getPropertyValue(address _property)
external
view
returns (uint256)
{
return getStoragePropertyValue(_property);
}
/**
* Adds the staking amount of the Property.
*/
function addPropertyValue(address _property, uint256 _value) private {
uint256 value = getStoragePropertyValue(_property);
value = value.add(_value);
setStoragePropertyValue(_property, value);
}
/**
* Subtracts the staking amount of the Property.
*/
function subPropertyValue(address _property, uint256 _value) private {
uint256 value = getStoragePropertyValue(_property);
uint256 nextValue = value.sub(_value);
setStoragePropertyValue(_property, nextValue);
}
/**
* Saves the latest reward amount as an undrawn amount.
*/
function updatePendingInterestWithdrawal(address _property, address _user)
private
returns (RewardPrices memory _prices)
{
/**
* Gets the latest reward amount.
*/
(
uint256 withdrawableAmount,
RewardPrices memory prices
) = _calculateWithdrawableInterestAmount(_property, _user);
/**
* Saves the amount to `PendingInterestWithdrawal` storage.
*/
setStoragePendingInterestWithdrawal(
_property,
_user,
withdrawableAmount
);
/**
* Updates the reward amount of before DIP4 to prevent further addition it.
*/
__updateLegacyWithdrawableInterestAmount(_property, _user);
return prices;
}
/**
* Returns the reward amount of the calculation model before DIP4.
* It can be calculated by subtracting "the last cumulative sum of reward unit price" from
* "the current cumulative sum of reward unit price," and multiplying by the staking amount.
*/
function __legacyWithdrawableInterestAmount(
address _property,
address _user
) private view returns (uint256) {
uint256 _last = getStorageLastInterestPrice(_property, _user);
uint256 price = getStorageInterestPrice(_property);
uint256 priceGap = price.sub(_last);
uint256 lockedUpValue = getStorageValue(_property, _user);
uint256 value = priceGap.mul(lockedUpValue);
return value.divBasis();
}
/**
* Updates and treats the reward of before DIP4 as already received.
*/
function __updateLegacyWithdrawableInterestAmount(
address _property,
address _user
) private {
uint256 interestPrice = getStorageInterestPrice(_property);
if (getStorageLastInterestPrice(_property, _user) != interestPrice) {
setStorageLastInterestPrice(_property, _user, interestPrice);
}
}
function ___setFallbackInitialCumulativeHoldersRewardCap(uint256 _value)
external
onlyOwner
{
setStorageFallbackInitialCumulativeHoldersRewardCap(_value);
}
} | CumulativeHoldersRewardCap | function setStorageCumulativeHoldersRewardCap(uint256 _value) internal {
eternalStorage().setUint(
getStorageCumulativeHoldersRewardCapKey(),
_value
);
}
| 5,442,620 | [
1,
39,
11276,
27003,
17631,
1060,
4664,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
444,
3245,
39,
11276,
27003,
17631,
1060,
4664,
12,
11890,
5034,
389,
1132,
13,
2713,
288,
203,
565,
225,
847,
82,
287,
3245,
7675,
542,
5487,
12,
203,
1377,
13840,
39,
11276,
27003,
17631,
1060,
4664,
653,
9334,
203,
1377,
389,
1132,
203,
565,
11272,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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;
/**
* Math operations with safety checks
*/
library SafeMath {
function mul(uint a, uint b) internal returns (uint) {
uint c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint a, uint b) internal returns (uint) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint a, uint b) internal returns (uint) {
assert(b <= a);
return a - b;
}
function add(uint a, uint b) internal returns (uint) {
uint c = a + b;
assert(c >= a);
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;
}
function assert(bool assertion) internal {
if (!assertion) {
throw;
}
}
}
/**
* @title Shareable
* @dev inheritable "property" contract that enables methods to be protected by requiring the
* acquiescence of either a single, or, crucially, each of a number of, designated owners.
* @dev Usage: use modifiers onlyowner (just own owned) or onlymanyowners(hash), whereby the same hash must be provided by some number (specified in constructor) of the set of owners (specified in the constructor) before the interior is executed.
*/
contract Shareable {
// struct for the status of a pending operation.
struct PendingState {
uint yetNeeded;
uint ownersDone;
uint index;
}
// the number of owners that must confirm the same operation before it is run.
uint public required;
// list of owners
address[256] owners;
// index on the list of owners to allow reverse lookup
mapping(address => uint) ownerIndex;
// the ongoing operations.
mapping(bytes32 => PendingState) pendings;
bytes32[] pendingsIndex;
// this contract only has six types of events: it can accept a confirmation, in which case
// we record owner and operation (hash) alongside it.
event Confirmation(address owner, bytes32 operation);
event Revoke(address owner, bytes32 operation);
// simple single-sig function modifier.
modifier onlyOwner {
if (!isOwner(msg.sender)) {
throw;
}
_;
}
/**
* @dev Modifier for multisig functions.
* @param _operation The operation must have an intrinsic hash in order that later attempts can be
* realised as the same underlying operation and thus count as confirmations.
*/
modifier onlymanyowners(bytes32 _operation) {
if (confirmAndCheck(_operation)) {
_;
}
}
/**
* @dev Constructor is given the number of sigs required to do protected "onlymanyowners"
* transactions as well as the selection of addresses capable of confirming them.
* @param _owners A list of owners.
* @param _required The amount required for a transaction to be approved.
*/
function Shareable(address[] _owners, uint _required) {
owners[1] = msg.sender;
ownerIndex[msg.sender] = 1;
for (uint i = 0; i < _owners.length; ++i) {
owners[2 + i] = _owners[i];
ownerIndex[_owners[i]] = 2 + i;
}
required = _required;
if (required > owners.length) {
throw;
}
}
/**
* @dev Revokes a prior confirmation of the given operation.
* @param _operation A string identifying the operation.
*/
function revoke(bytes32 _operation) external {
uint index = ownerIndex[msg.sender];
// make sure they're an owner
if (index == 0) {
return;
}
uint ownerIndexBit = 2**index;
var pending = pendings[_operation];
if (pending.ownersDone & ownerIndexBit > 0) {
pending.yetNeeded++;
pending.ownersDone -= ownerIndexBit;
Revoke(msg.sender, _operation);
}
}
/**
* @dev Gets an owner by 0-indexed position (using numOwners as the count)
* @param ownerIndex Uint The index of the owner
* @return The address of the owner
*/
function getOwner(uint ownerIndex) external constant returns (address) {
return address(owners[ownerIndex + 1]);
}
/**
* @dev Checks if given address is an owner.
* @param _addr address The address which you want to check.
* @return True if the address is an owner and fase otherwise.
*/
function isOwner(address _addr) constant returns (bool) {
return ownerIndex[_addr] > 0;
}
/**
* @dev Function to check is specific owner has already confirme the operation.
* @param _operation The operation identifier.
* @param _owner The owner address.
* @return True if the owner has confirmed and false otherwise.
*/
function hasConfirmed(bytes32 _operation, address _owner) constant returns (bool) {
var pending = pendings[_operation];
uint index = ownerIndex[_owner];
// make sure they're an owner
if (index == 0) {
return false;
}
// determine the bit to set for this owner.
uint ownerIndexBit = 2**index;
return !(pending.ownersDone & ownerIndexBit == 0);
}
/**
* @dev Confirm and operation and checks if it's already executable.
* @param _operation The operation identifier.
* @return Returns true when operation can be executed.
*/
function confirmAndCheck(bytes32 _operation) internal returns (bool) {
// determine what index the present sender is:
uint index = ownerIndex[msg.sender];
// make sure they're an owner
if (index == 0) {
throw;
}
var pending = pendings[_operation];
// if we're not yet working on this operation, switch over and reset the confirmation status.
if (pending.yetNeeded == 0) {
// reset count of confirmations needed.
pending.yetNeeded = required;
// reset which owners have confirmed (none) - set our bitmap to 0.
pending.ownersDone = 0;
pending.index = pendingsIndex.length++;
pendingsIndex[pending.index] = _operation;
}
// determine the bit to set for this owner.
uint ownerIndexBit = 2**index;
// make sure we (the message sender) haven't confirmed this operation previously.
if (pending.ownersDone & ownerIndexBit == 0) {
Confirmation(msg.sender, _operation);
// ok - check if count is enough to go ahead.
if (pending.yetNeeded <= 1) {
// enough confirmations: reset and run interior.
delete pendingsIndex[pendings[_operation].index];
delete pendings[_operation];
return true;
} else {
// not enough: record that this owner in particular confirmed.
pending.yetNeeded--;
pending.ownersDone |= ownerIndexBit;
}
}
return false;
}
/**
* @dev Clear the pending list.
*/
function clearPending() internal {
uint length = pendingsIndex.length;
for (uint i = 0; i < length; ++i) {
if (pendingsIndex[i] != 0) {
delete pendings[pendingsIndex[i]];
}
}
delete pendingsIndex;
}
}
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20Basic {
uint public totalSupply;
function balanceOf(address who) constant returns (uint);
function transfer(address to, uint value);
event Transfer(address indexed from, address indexed to, uint 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 (uint);
function transferFrom(address from, address to, uint value);
function approve(address spender, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint;
mapping(address => uint) balances;
/**
* @dev Fix for the ERC20 short address attack.
*/
modifier onlyPayloadSize(uint size) {
if(msg.data.length < size + 4) {
throw;
}
_;
}
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint _value) onlyPayloadSize(2 * 32) {
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint representing the amount owned by the passed address.
*/
function balanceOf(address _owner) constant returns (uint balance) {
return balances[_owner];
}
}
/**
* @title Standard ERC20 token
*
* @dev Implemantation of the basic standart 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 BasicToken, ERC20 {
mapping (address => mapping (address => uint)) 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 uint the amout of tokens to be transfered
*/
function transferFrom(address _from, address _to, uint _value) onlyPayloadSize(3 * 32) {
var _allowance = allowed[_from][msg.sender];
// Check is not needed because sub(_allowance, _value) will already throw if this condition is not met
// if (_value > _allowance) throw;
balances[_to] = balances[_to].add(_value);
balances[_from] = balances[_from].sub(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
Transfer(_from, _to, _value);
}
/**
* @dev Aprove the passed address to spend the specified amount of tokens on beahlf of msg.sender.
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint _value) {
// To change the approve amount you first have to reduce the addresses`
// allowance to zero by calling `approve(_spender, 0)` if it is not
// already 0 to mitigate the race condition described here:
// https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
if ((_value != 0) && (allowed[msg.sender][_spender] != 0)) throw;
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
}
/**
* @dev Function to check the amount of tokens than 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 uint specifing the amount of tokens still avaible for the spender.
*/
function allowance(address _owner, address _spender) constant returns (uint remaining) {
return allowed[_owner][_spender];
}
}
/**
* @title BTH
* @notice BTC + ETH = BTH
*/
contract BTH is StandardToken, Shareable {
using SafeMath for uint256;
/*
* Constants
*/
string public constant name = "Bether";
string public constant symbol = "BTH";
uint256 public constant decimals = 18;
string public version = "1.0";
uint256 public constant INITIAL_SUBSIDY = 50 * 10**decimals;
uint256 public constant HASH_RATE_MULTIPLIER = 1;
/*
* Events
*/
event LogContribution(address indexed _miner, uint256 _value, uint256 _hashRate, uint256 _block, uint256 _halving);
event LogClaimHalvingSubsidy(address indexed _miner, uint256 _block, uint256 _halving, uint256 _value);
event LogRemainingHalvingSubsidy(uint256 _halving, uint256 _value);
event LogPause(bytes32 indexed _hash);
event LogUnPause(bytes32 indexed _hash);
event LogBTHFoundationWalletChanged(address indexed _wallet);
event LogPollCreated(bytes32 indexed _hash);
event LogPollDeleted(bytes32 indexed _hash);
event LogPollVoted(bytes32 indexed _hash, address indexed _miner, uint256 _hashRate);
event LogPollApproved(bytes32 indexed _hash);
/*
* Storage vars
*/
mapping (uint256 => HalvingHashRate) halvingsHashRate; // Holds the accumulated hash rate per halving
mapping (uint256 => Subsidy) halvingsSubsidies; // Stores the remaining subsidy per halving
mapping (address => Miner) miners; // Miners data
mapping (bytes32 => Poll) polls; // Contract polls
address public bthFoundationWallet;
uint256 public subsidyHalvingInterval;
uint256 public maxHalvings;
uint256 public genesis;
uint256 public totalHashRate;
bool public paused;
struct HalvingHashRate {
bool carried; // Indicates that the previous hash rate have been added to the halving
uint256 rate; // Hash rate of the halving
}
struct Miner {
uint256 block; // Miner block, used to calculate in which halving is the miner
uint256 totalHashRate; // Accumulated miner hash rate
mapping (uint256 => MinerHashRate) hashRate;
}
struct MinerHashRate {
bool carried;
uint256 rate;
}
struct Subsidy {
bool claimed; // Flag that indicates that the subsidy has been claimed at least one time, just to
// compute the initial halving subsidy value
uint256 value; // Remaining subsidy of a halving
}
struct Poll {
bool exists; // Indicates that the poll is created
string title; // Title of the poll, it's the poll indentifier so it must be unique
mapping (address => bool) votes; // Control who have voted
uint8 percentage; // Percentage which determines if the poll has been approved
uint256 hashRate; // Summed hash rate of all the voters
bool approved; // True if the poll has been approved
uint256 approvalBlock; // Block in which the poll was approved
uint256 approvalHashRate; // Hash rate that caused the poll approval
uint256 approvalTotalHashRate; // Total has rate in when the poll was approved
}
/*
* Modifiers
*/
modifier notBeforeGenesis() {
require(block.number >= genesis);
_;
}
modifier nonZero(uint256 _value) {
require(_value > 0);
_;
}
modifier nonZeroAddress(address _address) {
require(_address != address(0));
_;
}
modifier nonZeroValued() {
require(msg.value != 0);
_;
}
modifier nonZeroLength(address[] array) {
require(array.length != 0);
_;
}
modifier notPaused() {
require(!paused);
_;
}
modifier notGreaterThanCurrentBlock(uint256 _block) {
require(_block <= currentBlock());
_;
}
modifier isMiner(address _address) {
require(miners[_address].block != 0);
_;
}
modifier pollApproved(bytes32 _hash) {
require(polls[_hash].approved);
_;
}
/*
* Public functions
*/
/**
@notice Contract constructor
@param _bthFoundationMembers are the addresses that control the BTH contract
@param _required number of memers needed to execute management functions of the contract
@param _bthFoundationWallet wallet that holds all the contract contributions
@param _genesis block number in which the BTH contract will be active
@param _subsidyHalvingInterval number of blocks which comprises a halving
@param _maxHalvings number of halvings that will generate BTH
**/
function BTH(
address[] _bthFoundationMembers,
uint256 _required,
address _bthFoundationWallet,
uint256 _genesis,
uint256 _subsidyHalvingInterval,
uint256 _maxHalvings
) Shareable( _bthFoundationMembers, _required)
nonZeroLength(_bthFoundationMembers)
nonZero(_required)
nonZeroAddress(_bthFoundationWallet)
nonZero(_genesis)
nonZero(_subsidyHalvingInterval)
nonZero(_maxHalvings)
{
// Genesis block must be greater or equal than the current block
if (_genesis < block.number) throw;
bthFoundationWallet = _bthFoundationWallet;
subsidyHalvingInterval = _subsidyHalvingInterval;
maxHalvings = _maxHalvings;
genesis = _genesis;
totalSupply = 0;
totalHashRate = 0;
paused = false;
}
/**
@notice Contract desctruction function
@param _hash poll hash that authorizes the function call
**/
function kill(bytes32 _hash)
external
pollApproved(_hash)
onlymanyowners(sha3(msg.data))
{
selfdestruct(bthFoundationWallet);
}
/**
@notice Contract desctruction function with ethers redirection
@param _hash poll hash that authorizes the function call
**/
function killTo(address _to, bytes32 _hash)
external
nonZeroAddress(_to)
pollApproved(_hash)
onlymanyowners(sha3(msg.data))
{
selfdestruct(_to);
}
/**
@notice Pause the contract operations
@param _hash poll hash that authorizes the pause
**/
function pause(bytes32 _hash)
external
pollApproved(_hash)
onlymanyowners(sha3(msg.data))
notBeforeGenesis
{
if (!paused) {
paused = true;
LogPause(_hash);
}
}
/**
@notice Unpause the contract operations
@param _hash poll hash that authorizes the unpause
**/
function unPause(bytes32 _hash)
external
pollApproved(_hash)
onlymanyowners(sha3(msg.data))
notBeforeGenesis
{
if (paused) {
paused = false;
LogUnPause(_hash);
}
}
/**
@notice Set the bthFoundation wallet
@param _wallet new wallet address
**/
function setBTHFoundationWallet(address _wallet)
external
onlymanyowners(sha3(msg.data))
nonZeroAddress(_wallet)
{
bthFoundationWallet = _wallet;
LogBTHFoundationWalletChanged(_wallet);
}
/**
@notice Returns the current BTH block
@return current bth block number
**/
function currentBlock()
public
constant
notBeforeGenesis
returns(uint256)
{
return block.number.sub(genesis);
}
/**
@notice Calculates the halving number of a given block
@param _block block number
@return the halving of the block
**/
function blockHalving(uint256 _block)
public
constant
notBeforeGenesis
returns(uint256)
{
return _block.div(subsidyHalvingInterval);
}
/**
@notice Calculate the offset of a given block
@return the offset of the block in a halving
**/
function blockOffset(uint256 _block)
public
constant
notBeforeGenesis
returns(uint256)
{
return _block % subsidyHalvingInterval;
}
/**
@notice Determine the current halving number
@return the current halving
**/
function currentHalving()
public
constant
notBeforeGenesis
returns(uint256)
{
return blockHalving(currentBlock());
}
/**
@notice Compute the starting block of a halving
@return the initial halving block
**/
function halvingStartBlock(uint256 _halving)
public
constant
notBeforeGenesis
returns(uint256)
{
return _halving.mul(subsidyHalvingInterval);
}
/**
@notice Calculate the total subsidy of a block
@param _block block number
@return the total amount that will be shared with the miners
**/
function blockSubsidy(uint256 _block)
public
constant
notBeforeGenesis
returns(uint256)
{
uint256 halvings = _block.div(subsidyHalvingInterval);
if (halvings >= maxHalvings) return 0;
uint256 subsidy = INITIAL_SUBSIDY >> halvings;
return subsidy;
}
/**
@notice Computes the subsidy of a full halving
@param _halving halving
@return the total amount that will be shared with the miners in this halving
**/
function halvingSubsidy(uint256 _halving)
public
constant
notBeforeGenesis
returns(uint256)
{
uint256 startBlock = halvingStartBlock(_halving);
return blockSubsidy(startBlock).mul(subsidyHalvingInterval);
}
/// @notice Fallback function which implements how miners participate in BTH
function()
payable
{
contribute(msg.sender);
}
/**
@notice Contribute to the mining of BTH on behalf of another miner
@param _miner address that will receive the subsidies
@return true if success
**/
function proxiedContribution(address _miner)
public
payable
returns (bool)
{
if (_miner == address(0)) {
// In case the _miner parameter is invalid, redirect the asignment
// to the transaction sender
return contribute(msg.sender);
} else {
return contribute(_miner);
}
}
/**
@notice Contribute to the mining of BTH
@param _miner address that will receive the subsidies
@return true if success
**/
function contribute(address _miner)
internal
notBeforeGenesis
nonZeroValued
notPaused
returns (bool)
{
uint256 block = currentBlock();
uint256 halving = currentHalving();
uint256 hashRate = HASH_RATE_MULTIPLIER.mul(msg.value);
Miner miner = miners[_miner];
// First of all use the contribute to synchronize the hash rate of the previous halvings
if (halving != 0 && halving < maxHalvings) {
uint256 I;
uint256 n = 0;
for (I = halving - 1; I > 0; I--) {
if (!halvingsHashRate[I].carried) {
n = n.add(1);
} else {
break;
}
}
for (I = halving - n; I < halving; I++) {
if (!halvingsHashRate[I].carried) {
halvingsHashRate[I].carried = true;
halvingsHashRate[I].rate = halvingsHashRate[I].rate.add(halvingsHashRate[I - 1].rate);
}
}
}
// Increase the halving hash rate accordingly, after maxHalvings the halvings hash rate are not needed and therefore not updated
if (halving < maxHalvings) {
halvingsHashRate[halving].rate = halvingsHashRate[halving].rate.add(hashRate);
}
// After updating the halving hash rate, do the miner contribution
// If it's the very first time the miner participates in the BTH token, assign an initial block
// This block is used with two porpouses:
// - To account in which halving the miner is
// - To know the offset inside the halving and allow only claimings after the miner offset
if (miner.block == 0) {
miner.block = block;
}
// Add this hash rate to the miner at the current halving
miner.hashRate[halving].rate = miner.hashRate[halving].rate.add(hashRate);
miner.totalHashRate = miner.totalHashRate.add(hashRate);
// Increase the total hash rate
totalHashRate = totalHashRate.add(hashRate);
// Send contribution to the BTH foundation multisig wallet
if (!bthFoundationWallet.send(msg.value)) {
throw;
}
// Log the contribute call
LogContribution(_miner, msg.value, hashRate, block, halving);
return true;
}
/**
@notice Miners subsidies must be claimed by the miners calling claimHalvingsSubsidies(_n)
@param _n number of halvings to claim
@return the total amount claimed and successfully assigned as BTH to the miner
**/
function claimHalvingsSubsidies(uint256 _n)
public
notBeforeGenesis
notPaused
isMiner(msg.sender)
returns(uint256)
{
Miner miner = miners[msg.sender];
uint256 start = blockHalving(miner.block);
uint256 end = start.add(_n);
if (end > currentHalving()) {
return 0;
}
uint256 subsidy = 0;
uint256 totalSubsidy = 0;
uint256 unclaimed = 0;
uint256 hashRate = 0;
uint256 K;
// Claim each unclaimed halving subsidy
for(K = start; K < end && K < maxHalvings; K++) {
// Check if the total hash rate has been carried, otherwise the current halving
// hash rate needs to be updated carrying the total from the last carried
HalvingHashRate halvingHashRate = halvingsHashRate[K];
if (!halvingHashRate.carried) {
halvingHashRate.carried = true;
halvingHashRate.rate = halvingHashRate.rate.add(halvingsHashRate[K-1].rate);
}
// Accumulate the miner hash rate as all the contributions are accounted in the contribution
// and needs to be summed up to reflect the accumulated value
MinerHashRate minerHashRate = miner.hashRate[K];
if (!minerHashRate.carried) {
minerHashRate.carried = true;
minerHashRate.rate = minerHashRate.rate.add(miner.hashRate[K-1].rate);
}
hashRate = minerHashRate.rate;
if (hashRate != 0){
// If the halving to claim is the last claimable, check the offsets
if (K == currentHalving().sub(1)) {
if (currentBlock() % subsidyHalvingInterval < miner.block % subsidyHalvingInterval) {
// Finish the loop
continue;
}
}
Subsidy sub = halvingsSubsidies[K];
if (!sub.claimed) {
sub.claimed = true;
sub.value = halvingSubsidy(K);
}
unclaimed = sub.value;
subsidy = halvingSubsidy(K).mul(hashRate).div(halvingHashRate.rate);
if (subsidy > unclaimed) {
subsidy = unclaimed;
}
totalSubsidy = totalSubsidy.add(subsidy);
sub.value = sub.value.sub(subsidy);
LogClaimHalvingSubsidy(msg.sender, miner.block, K, subsidy);
LogRemainingHalvingSubsidy(K, sub.value);
}
// Move the miner to the next halving
miner.block = miner.block.add(subsidyHalvingInterval);
}
// If K is less than end, the loop exited because K < maxHalvings, so
// move the miner end - K halvings
if (K < end) {
miner.block = miner.block.add(subsidyHalvingInterval.mul(end.sub(K)));
}
if (totalSubsidy != 0){
balances[msg.sender] = balances[msg.sender].add(totalSubsidy);
totalSupply = totalSupply.add(totalSubsidy);
}
return totalSubsidy;
}
/**
@notice Compute the number of halvings claimable by the miner caller
@return number of halvings that a miner is allowed to claim
**/
function claimableHalvings()
public
constant
returns(uint256)
{
return claimableHalvingsOf(msg.sender);
}
/**
@notice Computes the number of halvings claimable by the miner
@return number of halvings that a miner is entitled claim
**/
function claimableHalvingsOf(address _miner)
public
constant
notBeforeGenesis
isMiner(_miner)
returns(uint256)
{
Miner miner = miners[_miner];
uint256 halving = currentHalving();
uint256 minerHalving = blockHalving(miner.block);
// Halvings can be claimed when they are finished
if (minerHalving == halving) {
return 0;
} else {
// Check the miner offset
if (currentBlock() % subsidyHalvingInterval < miner.block % subsidyHalvingInterval) {
// In this case the miner offset is behind the current block offset, so it must wait
// till the block offset is greater or equal than his offset
return halving.sub(minerHalving).sub(1);
} else {
return halving.sub(minerHalving);
}
}
}
/**
@notice Claim all the unclaimed halving subsidies of a miner
@return total amount of BTH assigned to the miner
**/
function claim()
public
notBeforeGenesis
notPaused
isMiner(msg.sender)
returns(uint256)
{
return claimHalvingsSubsidies(claimableHalvings());
}
/**
@notice ERC20 transfer function overridden to disable transfers when paused
**/
function transfer(address _to, uint _value)
public
notPaused
{
super.transfer(_to, _value);
}
/**
@notice ERC20 transferFrom function overridden to disable transfers when paused
**/
function transferFrom(address _from, address _to, uint _value)
public
notPaused
{
super.transferFrom(_from, _to, _value);
}
// Poll functions
/**
@notice Create a new poll
@param _title poll title
@param _percentage percentage of hash rate that must vote to approve the poll
**/
function createPoll(string _title, uint8 _percentage)
external
onlymanyowners(sha3(msg.data))
{
bytes32 hash = sha3(_title);
Poll poll = polls[hash];
if (poll.exists) {
throw;
}
if (_percentage < 1 || _percentage > 100) {
throw;
}
poll.exists = true;
poll.title = _title;
poll.percentage = _percentage;
poll.hashRate = 0;
poll.approved = false;
poll.approvalBlock = 0;
poll.approvalHashRate = 0;
poll.approvalTotalHashRate = 0;
LogPollCreated(hash);
}
/**
@notice Delete a poll
@param _hash sha3 of the poll title, also arg of LogPollCreated event
**/
function deletePoll(bytes32 _hash)
external
onlymanyowners(sha3(msg.data))
{
Poll poll = polls[_hash];
if (poll.exists) {
delete polls[_hash];
LogPollDeleted(_hash);
}
}
/**
@notice Retreive the poll data
@param _hash sha3 of the poll title, also arg of LogPollCreated event
@return an array with the poll data
**/
function getPoll(bytes32 _hash)
external
constant
returns(bool, string, uint8, uint256, uint256, bool, uint256, uint256, uint256)
{
Poll poll = polls[_hash];
return (poll.exists, poll.title, poll.percentage, poll.hashRate, totalHashRate,
poll.approved, poll.approvalBlock, poll.approvalHashRate, poll.approvalTotalHashRate);
}
function vote(bytes32 _hash)
external
isMiner(msg.sender)
{
Poll poll = polls[_hash];
if (poll.exists) {
if (!poll.votes[msg.sender]) {
// msg.sender has not yet voted
Miner miner = miners[msg.sender];
poll.votes[msg.sender] = true;
poll.hashRate = poll.hashRate.add(miner.totalHashRate);
// Log the vote
LogPollVoted(_hash, msg.sender, miner.totalHashRate);
// Check if the poll has succeeded
if (!poll.approved) {
if (poll.hashRate.mul(100).div(totalHashRate) >= poll.percentage) {
poll.approved = true;
poll.approvalBlock = block.number;
poll.approvalHashRate = poll.hashRate;
poll.approvalTotalHashRate = totalHashRate;
LogPollApproved(_hash);
}
}
}
}
}
/*
* Internal functions
*/
/*
* Web3 call functions
*/
/**
@notice Return the blocks per halving
@return blocks per halving
**/
function getHalvingBlocks()
public
constant
notBeforeGenesis
returns(uint256)
{
return subsidyHalvingInterval;
}
/**
@notice Return the block in which the miner is
@return the last block number mined by the miner
**/
function getMinerBlock()
public
constant
returns(uint256)
{
return getBlockOf(msg.sender);
}
/**
@notice Return the block in which the miner is
@return the last block number mined by the miner
**/
function getBlockOf(address _miner)
public
constant
notBeforeGenesis
isMiner(_miner)
returns(uint256)
{
return miners[_miner].block;
}
/**
@notice Return the miner halving (starting halving or last claimed)
@return last claimed or starting halving of the miner
**/
function getHalvingOf(address _miner)
public
constant
notBeforeGenesis
isMiner(_miner)
returns(uint256)
{
return blockHalving(miners[_miner].block);
}
/**
@notice Return the miner halving (starting halving or last claimed)
@return last claimed or starting halving of the miner
**/
function getMinerHalving()
public
constant
returns(uint256)
{
return getHalvingOf(msg.sender);
}
/**
@notice Total hash rate of a miner in a halving
@param _miner address of the miner
@return miner total accumulated hash rate
**/
function getMinerHalvingHashRateOf(address _miner)
public
constant
notBeforeGenesis
isMiner(_miner)
returns(uint256)
{
Miner miner = miners[_miner];
uint256 halving = getMinerHalving();
MinerHashRate hashRate = miner.hashRate[halving];
if (halving == 0) {
return hashRate.rate;
} else {
if (!hashRate.carried) {
return hashRate.rate.add(miner.hashRate[halving - 1].rate);
} else {
return hashRate.rate;
}
}
}
/**
@notice Total hash rate of a miner in a halving
@return miner total accumulated hash rate
**/
function getMinerHalvingHashRate()
public
constant
returns(uint256)
{
return getMinerHalvingHashRateOf(msg.sender);
}
/**
@notice Compute the miner halvings offset
@param _miner address of the miner
@return miner halving offset
**/
function getMinerOffsetOf(address _miner)
public
constant
notBeforeGenesis
isMiner(_miner)
returns(uint256)
{
return blockOffset(miners[_miner].block);
}
/**
@notice Compute the miner halvings offset
@return miner halving offset
**/
function getMinerOffset()
public
constant
returns(uint256)
{
return getMinerOffsetOf(msg.sender);
}
/**
@notice Calculate the hash rate of a miner in a halving
@dev Take into account that the rate can be uncarried
@param _halving number of halving
@return (carried, rate) a tuple with the rate and if the value has been carried from previous halvings
**/
function getHashRateOf(address _miner, uint256 _halving)
public
constant
notBeforeGenesis
isMiner(_miner)
returns(bool, uint256)
{
require(_halving <= currentHalving());
Miner miner = miners[_miner];
MinerHashRate hashRate = miner.hashRate[_halving];
return (hashRate.carried, hashRate.rate);
}
/**
@notice Calculate the halving hash rate of a miner
@dev Take into account that the rate can be uncarried
@param _miner address of the miner
@return (carried, rate) a tuple with the rate and if the value has been carried from previous halvings
**/
function getHashRateOfCurrentHalving(address _miner)
public
constant
returns(bool, uint256)
{
return getHashRateOf(_miner, currentHalving());
}
/**
@notice Calculate the halving hash rate of a miner
@dev Take into account that the rate can be uncarried
@param _halving numer of the miner halving
@return (carried, rate) a tuple with the rate and if the value has been carried from previous halvings
**/
function getMinerHashRate(uint256 _halving)
public
constant
returns(bool, uint256)
{
return getHashRateOf(msg.sender, _halving);
}
/**
@notice Calculate the halving hash rate of a miner
@dev Take into account that the rate can be uncarried
@return (carried, rate) a tuple with the rate and if the value has been carried from previous halvings
**/
function getMinerHashRateCurrentHalving()
public
constant
returns(bool, uint256)
{
return getHashRateOf(msg.sender, currentHalving());
}
/**
@notice Total hash rate of a miner
@return miner total accumulated hash rate
**/
function getTotalHashRateOf(address _miner)
public
constant
notBeforeGenesis
isMiner(_miner)
returns(uint256)
{
return miners[_miner].totalHashRate;
}
/**
@notice Total hash rate of a miner
@return miner total accumulated hash rate
**/
function getTotalHashRate()
public
constant
returns(uint256)
{
return getTotalHashRateOf(msg.sender);
}
/**
@notice Computes the remaining subsidy pending of being claimed for a given halving
@param _halving number of halving
@return the remaining subsidy of a halving
**/
function getUnclaimedHalvingSubsidy(uint256 _halving)
public
constant
notBeforeGenesis
returns(uint256)
{
require(_halving < currentHalving());
if (!halvingsSubsidies[_halving].claimed) {
// In the case that the halving subsidy hasn't been instantiated
// (.claimed is false) return the full halving subsidy
return halvingSubsidy(_halving);
} else {
// Otherwise return the remaining halving subsidy
halvingsSubsidies[_halving].value;
}
}
} | * @title Shareable @dev inheritable "property" contract that enables methods to be protected by requiring the acquiescence of either a single, or, crucially, each of a number of, designated owners. @dev Usage: use modifiers onlyowner (just own owned) or onlymanyowners(hash), whereby the same hash must be provided by some number (specified in constructor) of the set of owners (specified in the constructor) before the interior is executed./ struct for the status of a pending operation. | contract Shareable {
struct PendingState {
uint yetNeeded;
uint ownersDone;
uint index;
}
bytes32[] pendingsIndex;
event Revoke(address owner, bytes32 operation);
uint public required;
address[256] owners;
mapping(address => uint) ownerIndex;
mapping(bytes32 => PendingState) pendings;
event Confirmation(address owner, bytes32 operation);
modifier onlyOwner {
if (!isOwner(msg.sender)) {
throw;
}
_;
}
modifier onlyOwner {
if (!isOwner(msg.sender)) {
throw;
}
_;
}
modifier onlymanyowners(bytes32 _operation) {
if (confirmAndCheck(_operation)) {
_;
}
}
modifier onlymanyowners(bytes32 _operation) {
if (confirmAndCheck(_operation)) {
_;
}
}
function Shareable(address[] _owners, uint _required) {
owners[1] = msg.sender;
ownerIndex[msg.sender] = 1;
for (uint i = 0; i < _owners.length; ++i) {
owners[2 + i] = _owners[i];
ownerIndex[_owners[i]] = 2 + i;
}
required = _required;
if (required > owners.length) {
throw;
}
}
function Shareable(address[] _owners, uint _required) {
owners[1] = msg.sender;
ownerIndex[msg.sender] = 1;
for (uint i = 0; i < _owners.length; ++i) {
owners[2 + i] = _owners[i];
ownerIndex[_owners[i]] = 2 + i;
}
required = _required;
if (required > owners.length) {
throw;
}
}
function Shareable(address[] _owners, uint _required) {
owners[1] = msg.sender;
ownerIndex[msg.sender] = 1;
for (uint i = 0; i < _owners.length; ++i) {
owners[2 + i] = _owners[i];
ownerIndex[_owners[i]] = 2 + i;
}
required = _required;
if (required > owners.length) {
throw;
}
}
function revoke(bytes32 _operation) external {
uint index = ownerIndex[msg.sender];
if (index == 0) {
return;
}
uint ownerIndexBit = 2**index;
var pending = pendings[_operation];
if (pending.ownersDone & ownerIndexBit > 0) {
pending.yetNeeded++;
pending.ownersDone -= ownerIndexBit;
Revoke(msg.sender, _operation);
}
}
function revoke(bytes32 _operation) external {
uint index = ownerIndex[msg.sender];
if (index == 0) {
return;
}
uint ownerIndexBit = 2**index;
var pending = pendings[_operation];
if (pending.ownersDone & ownerIndexBit > 0) {
pending.yetNeeded++;
pending.ownersDone -= ownerIndexBit;
Revoke(msg.sender, _operation);
}
}
function revoke(bytes32 _operation) external {
uint index = ownerIndex[msg.sender];
if (index == 0) {
return;
}
uint ownerIndexBit = 2**index;
var pending = pendings[_operation];
if (pending.ownersDone & ownerIndexBit > 0) {
pending.yetNeeded++;
pending.ownersDone -= ownerIndexBit;
Revoke(msg.sender, _operation);
}
}
function getOwner(uint ownerIndex) external constant returns (address) {
return address(owners[ownerIndex + 1]);
}
function isOwner(address _addr) constant returns (bool) {
return ownerIndex[_addr] > 0;
}
function hasConfirmed(bytes32 _operation, address _owner) constant returns (bool) {
var pending = pendings[_operation];
uint index = ownerIndex[_owner];
if (index == 0) {
return false;
}
return !(pending.ownersDone & ownerIndexBit == 0);
}
function hasConfirmed(bytes32 _operation, address _owner) constant returns (bool) {
var pending = pendings[_operation];
uint index = ownerIndex[_owner];
if (index == 0) {
return false;
}
return !(pending.ownersDone & ownerIndexBit == 0);
}
uint ownerIndexBit = 2**index;
function confirmAndCheck(bytes32 _operation) internal returns (bool) {
uint index = ownerIndex[msg.sender];
if (index == 0) {
throw;
}
var pending = pendings[_operation];
if (pending.yetNeeded == 0) {
pending.yetNeeded = required;
pending.ownersDone = 0;
pending.index = pendingsIndex.length++;
pendingsIndex[pending.index] = _operation;
}
if (pending.ownersDone & ownerIndexBit == 0) {
Confirmation(msg.sender, _operation);
if (pending.yetNeeded <= 1) {
delete pendingsIndex[pendings[_operation].index];
delete pendings[_operation];
return true;
pending.yetNeeded--;
pending.ownersDone |= ownerIndexBit;
}
}
return false;
}
function confirmAndCheck(bytes32 _operation) internal returns (bool) {
uint index = ownerIndex[msg.sender];
if (index == 0) {
throw;
}
var pending = pendings[_operation];
if (pending.yetNeeded == 0) {
pending.yetNeeded = required;
pending.ownersDone = 0;
pending.index = pendingsIndex.length++;
pendingsIndex[pending.index] = _operation;
}
if (pending.ownersDone & ownerIndexBit == 0) {
Confirmation(msg.sender, _operation);
if (pending.yetNeeded <= 1) {
delete pendingsIndex[pendings[_operation].index];
delete pendings[_operation];
return true;
pending.yetNeeded--;
pending.ownersDone |= ownerIndexBit;
}
}
return false;
}
function confirmAndCheck(bytes32 _operation) internal returns (bool) {
uint index = ownerIndex[msg.sender];
if (index == 0) {
throw;
}
var pending = pendings[_operation];
if (pending.yetNeeded == 0) {
pending.yetNeeded = required;
pending.ownersDone = 0;
pending.index = pendingsIndex.length++;
pendingsIndex[pending.index] = _operation;
}
if (pending.ownersDone & ownerIndexBit == 0) {
Confirmation(msg.sender, _operation);
if (pending.yetNeeded <= 1) {
delete pendingsIndex[pendings[_operation].index];
delete pendings[_operation];
return true;
pending.yetNeeded--;
pending.ownersDone |= ownerIndexBit;
}
}
return false;
}
uint ownerIndexBit = 2**index;
function confirmAndCheck(bytes32 _operation) internal returns (bool) {
uint index = ownerIndex[msg.sender];
if (index == 0) {
throw;
}
var pending = pendings[_operation];
if (pending.yetNeeded == 0) {
pending.yetNeeded = required;
pending.ownersDone = 0;
pending.index = pendingsIndex.length++;
pendingsIndex[pending.index] = _operation;
}
if (pending.ownersDone & ownerIndexBit == 0) {
Confirmation(msg.sender, _operation);
if (pending.yetNeeded <= 1) {
delete pendingsIndex[pendings[_operation].index];
delete pendings[_operation];
return true;
pending.yetNeeded--;
pending.ownersDone |= ownerIndexBit;
}
}
return false;
}
function confirmAndCheck(bytes32 _operation) internal returns (bool) {
uint index = ownerIndex[msg.sender];
if (index == 0) {
throw;
}
var pending = pendings[_operation];
if (pending.yetNeeded == 0) {
pending.yetNeeded = required;
pending.ownersDone = 0;
pending.index = pendingsIndex.length++;
pendingsIndex[pending.index] = _operation;
}
if (pending.ownersDone & ownerIndexBit == 0) {
Confirmation(msg.sender, _operation);
if (pending.yetNeeded <= 1) {
delete pendingsIndex[pendings[_operation].index];
delete pendings[_operation];
return true;
pending.yetNeeded--;
pending.ownersDone |= ownerIndexBit;
}
}
return false;
}
} else {
function clearPending() internal {
uint length = pendingsIndex.length;
for (uint i = 0; i < length; ++i) {
if (pendingsIndex[i] != 0) {
delete pendings[pendingsIndex[i]];
}
}
delete pendingsIndex;
}
function clearPending() internal {
uint length = pendingsIndex.length;
for (uint i = 0; i < length; ++i) {
if (pendingsIndex[i] != 0) {
delete pendings[pendingsIndex[i]];
}
}
delete pendingsIndex;
}
function clearPending() internal {
uint length = pendingsIndex.length;
for (uint i = 0; i < length; ++i) {
if (pendingsIndex[i] != 0) {
delete pendings[pendingsIndex[i]];
}
}
delete pendingsIndex;
}
}
| 971,107 | [
1,
9535,
429,
225,
6811,
429,
315,
4468,
6,
6835,
716,
19808,
2590,
358,
506,
4750,
635,
29468,
326,
1721,
372,
606,
71,
802,
434,
3344,
279,
2202,
16,
578,
16,
4422,
5286,
6261,
16,
1517,
434,
279,
1300,
434,
16,
25264,
25937,
18,
225,
10858,
30,
999,
10429,
1338,
8443,
261,
3732,
4953,
16199,
13,
578,
1338,
9353,
995,
414,
12,
2816,
3631,
1625,
1637,
326,
1967,
1651,
1297,
506,
2112,
635,
2690,
1300,
261,
13827,
316,
3885,
13,
434,
326,
444,
434,
25937,
261,
13827,
316,
326,
3885,
13,
1865,
326,
26230,
353,
7120,
18,
19,
1958,
364,
326,
1267,
434,
279,
4634,
1674,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] | [
1,
16351,
25805,
429,
288,
203,
203,
225,
1958,
16034,
1119,
288,
203,
565,
2254,
4671,
11449,
31,
203,
565,
2254,
25937,
7387,
31,
203,
565,
2254,
770,
31,
203,
225,
289,
203,
203,
203,
225,
1731,
1578,
8526,
31472,
899,
1016,
31,
203,
203,
203,
225,
871,
23863,
12,
2867,
3410,
16,
1731,
1578,
1674,
1769,
203,
203,
203,
225,
2254,
1071,
1931,
31,
203,
225,
1758,
63,
5034,
65,
25937,
31,
203,
225,
2874,
12,
2867,
516,
2254,
13,
3410,
1016,
31,
203,
225,
2874,
12,
3890,
1578,
516,
16034,
1119,
13,
31472,
899,
31,
203,
225,
871,
17580,
367,
12,
2867,
3410,
16,
1731,
1578,
1674,
1769,
203,
225,
9606,
1338,
5541,
288,
203,
565,
309,
16051,
291,
5541,
12,
3576,
18,
15330,
3719,
288,
203,
1377,
604,
31,
203,
565,
289,
203,
565,
389,
31,
203,
225,
289,
203,
203,
225,
9606,
1338,
5541,
288,
203,
565,
309,
16051,
291,
5541,
12,
3576,
18,
15330,
3719,
288,
203,
1377,
604,
31,
203,
565,
289,
203,
565,
389,
31,
203,
225,
289,
203,
203,
225,
9606,
1338,
9353,
995,
414,
12,
3890,
1578,
389,
7624,
13,
288,
203,
565,
309,
261,
10927,
31151,
24899,
7624,
3719,
288,
203,
1377,
389,
31,
203,
565,
289,
203,
225,
289,
203,
203,
225,
9606,
1338,
9353,
995,
414,
12,
3890,
1578,
389,
7624,
13,
288,
203,
565,
309,
261,
10927,
31151,
24899,
7624,
3719,
288,
203,
1377,
389,
31,
203,
565,
289,
203,
225,
289,
203,
203,
225,
445,
25805,
429,
12,
2867,
8526,
389,
2
] |
./partial_match/42/0x20A02F27a25db188B7f068aF93BF31fbAB631Fff/sources/AthleteData.sol | Find athletes have same distance | function sameDistance(uint distance) public{
for(uint i=0; i<athletes.length; i++){
if(athletes[i].distance == distance)
memberDistance.push(athletes[i].name);
}
}
| 3,465,434 | [
1,
3125,
225,
421,
1810,
281,
1240,
1967,
3888,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
1967,
7200,
12,
11890,
3888,
13,
1071,
95,
203,
3639,
364,
12,
11890,
277,
33,
20,
31,
277,
32,
421,
1810,
281,
18,
2469,
31,
277,
27245,
95,
203,
5411,
309,
12,
421,
1810,
281,
63,
77,
8009,
8969,
422,
3888,
13,
203,
7734,
3140,
7200,
18,
6206,
12,
421,
1810,
281,
63,
77,
8009,
529,
1769,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.11;
// ---------------------- Built with 💘 for everyone --------------------------
/// @author Kinois Le Roi
/// @title SmACV1 [Smart Ads Contract V1] - This contract enables addresses to deploy smart ads.
/// Token : Paid Per Click - The winning crypto of the internet.
/// Symbol : PPeC - Spelled [P:E:K]
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
/// @title PPeC : Paid Per Click [ERC20] Interface
// ----------------------------------------------------------------------------
interface PPeC {
/// Transfer `amount` tokens to `to`.
function transfer(address to, uint256 amount) external returns (bool);
/// Get the amount of tokens owned by account `owner`.
function balanceOf(address owner) external view returns(uint256);
/// Get treasury address.
function treasury() external view returns(address);
/// Get founder address.
function founder() external view returns(address);
}
// ----------------------------------------------------------------------------
/// @title AdCreator : Smart Ads Contract Creator [SmACCor] - Enables addresses to publish Ads.
/// @notice Smart Ads cannot be updated once promoted.
// ----------------------------------------------------------------------------
contract AdCreator {
// Define public constant variables.
address PPeCAddress = 0xE1498556390645cA488320fe979bC72BdecB6A57;
address public founder;
address public treasury;
uint256 public minClaimerBalance;
uint256 public minReward;
uint256 public promoterFee;
uint256 public claimerFee;
bool public paused = false;
mapping(address => uint256) public pledged;
mapping(address => bool) public delegateContract;
mapping(address => SmACV1[]) public promoterAds;
SmACV1[] public advertisements;
// Set immutable values.
constructor(uint256 minReward_, uint256 minBalance_) {
founder = PPeC(PPeCAddress).founder();
treasury = PPeC(PPeCAddress).treasury();
minClaimerBalance = minBalance_;
minReward = minReward_;
promoterFee = 2000;
claimerFee = 5000;
}
// Events that will be emitted on changes.
event Pause();
event Unpause();
event RemoveAd();
event LaunchAd(
string link,
string title,
uint256 reach,
uint256 reward,
uint256 budget,
uint256 indexed created,
address indexed promoter,
address indexed adsContract
);
// Errors that describe failures.
// The triple-slash comments are so-called natspec
// comments. They will be shown when the user
// is asked to confirm a transaction or
// when an error is displayed. (source: solidity.org)
/// The budget exceeds your balance.
/// Your budget is `budget`, however your balance is `balance`.
error BudgetExceedBalance(uint256 budget, uint256 balance);
/// Your balance pledged `pledged` cannot exceeds your balance `balance`.
error PledgeExceedBalance(uint256 pledged, uint256 balance);
/// Your reward `reward` is lower than (`minReward`) the minimum required.
error RewardTooLow(uint256 reward, uint256 minReward);
/// The index entered `index` is out of bound.
error IndexOutOfBound(uint256 index);
/// You are not a delegate Contract.
error NotDelegateContract();
/// Make a function callable only when the contract is not paused.
modifier whenNotPaused() {
require(paused == false, "All publications have been paused.");
_;
}
/// Make a function callable only when the contract is paused.
modifier whenPaused() {
require(paused);
_;
}
/// Make a function callable only by the founder.
modifier onlyFounder() {
require(msg.sender == founder, "Your are not the Founder.");
_;
}
/// Launch a smart advertisement.
function launchAd(string memory title, string memory link, uint256 reach, uint256 reward)
whenNotPaused
public
returns(bool success)
{
require(reach >= 30, "You must enter at least 30.");
uint256 PromoterBalance = PPeC(PPeCAddress).balanceOf(msg.sender);
uint256 balancePledged = pledged[msg.sender];
uint256 budget = reach * reward;
if (budget > PromoterBalance)
revert BudgetExceedBalance(budget, PromoterBalance);
if (balancePledged + budget > PromoterBalance)
revert PledgeExceedBalance(balancePledged, PromoterBalance);
if (reward < minReward)
revert RewardTooLow(reward, minReward);
pledged[msg.sender] += budget;
SmACV1 newAdvertisement = new SmACV1(
msg.sender,
PPeCAddress,
link,
title,
reach,
reward,
minReward,
claimerFee,
promoterFee,
minClaimerBalance
);
advertisements.push(newAdvertisement);
promoterAds[msg.sender].push(newAdvertisement);
delegateContract[address(newAdvertisement)] = true;
// See {event LaunchAds}
emit LaunchAd(
link,
title,
reach,
reward,
budget,
block.timestamp,
msg.sender,
address(newAdvertisement)
);
return true;
}
/// Remove an advertisement from the array.
function removeAd(uint256 index) public onlyFounder returns(bool removed) {
if (index >= advertisements.length)
revert IndexOutOfBound(index);
for (uint256 i = index; i < advertisements.length - 1; i++) {
advertisements[i] = advertisements[i + 1];
}
advertisements.pop();
emit RemoveAd();
return true;
}
/// Update promoter's pledged balance.
function updatePledged(address promoter, uint256 amount) public returns(bool success) {
if (delegateContract[msg.sender] != true)
revert NotDelegateContract();
pledged[promoter] = amount;
return true;
}
/// Change minimum reward to `newMin`.
function setMinReward(uint256 newMin) public onlyFounder returns(bool success) {
minReward = newMin;
return true;
}
/// Change the minimum balance a claimer must have before claiming rewards to `newMin`.
function setMinClaimerBalance(uint256 newMin) public onlyFounder returns(bool success) {
minClaimerBalance = newMin;
return true;
}
/// Change promoters' fee to `newFee`.
function setPromoterFee(uint256 newFee) public onlyFounder returns(bool success) {
promoterFee = newFee;
return true;
}
/// Change claimers' fee to `newFee`.
function setClaimerFee(uint256 newFee) public onlyFounder returns(bool success) {
claimerFee = newFee;
return true;
}
/// Pause advertisement publication.
function pause() public onlyFounder whenNotPaused returns(bool success) {
paused = true;
// See {event Pause}
emit Pause();
return true;
}
/// Unpause advertisement publication.
function unpause() public onlyFounder whenPaused returns(bool success) {
paused = false;
// See {event Unpause}
emit Unpause();
return true;
}
/// Get the number of advertisements in our array.
function promotionCount() public view returns(uint256) {
return advertisements.length;
}
/// Get the amount of tokens owned by account `owner`.
function balanceOf(address owner) public view returns(uint256) {
return PPeC(PPeCAddress).balanceOf(owner);
}
/// Get the number of advertisements for `promoter`.
function promoterAdCount(address promoter) public view returns(uint256) {
return promoterAds[promoter].length;
}
/// Get the balances and ad count of `owner`.
function ownerInfo(address owner) public view returns(uint256 wallet, uint256 pledge, uint256 adCount) {
return (
PPeC(PPeCAddress).balanceOf(owner),
pledged[owner],
promoterAds[owner].length
);
}
/// Get the contract information.
function contractInfo() public view returns(uint256, uint256, uint256, uint256, uint256, uint256) {
return (
PPeC(PPeCAddress).balanceOf(treasury),
advertisements.length,
minClaimerBalance,
promoterFee,
claimerFee,
minReward
);
}
}
// ----------------------------------------------------------------------------
/// @title SmACCor : AdCreator [Smart ads Contract Creator] Interface.
// ----------------------------------------------------------------------------
interface SmACCor {
function updatePledged(address promoter, uint256 amount) external returns(bool);
function pledged(address owner) external view returns(uint256);
}
// ----------------------------------------------------------------------------
/// @title Advertisement : Defines the sturcture of an advertisement.
// ----------------------------------------------------------------------------
struct Advertisement {
string link;
string title;
uint256 reach;
uint256 reward;
uint256 budget;
uint256 created;
uint256 expired;
uint256 claimers;
uint256 scamReport;
address promoter;
}
// ----------------------------------------------------------------------------
/// @title SmACV1 : Smart Ads Contract [SmAC V1] Version 1.
// ----------------------------------------------------------------------------
contract SmACV1 {
// Define public constant variables.
address PPeCAddress;
address public adCreatorAddress;
uint256 public minClaimerBalance;
uint256 public minReward;
uint256 promoterFee;
uint256 claimerFee;
Advertisement public Ads;
mapping(address => mapping(address => bool)) claimed;
// Set immutable values.
constructor(
address eoa,
address PPeCAddress_,
string memory link_,
string memory title_,
uint256 reach_,
uint256 reward_,
uint256 minReward_,
uint256 claimerFee_,
uint256 promoterFee_,
uint256 minClaimerBalance_
) {
Ads.link = link_;
Ads.title = title_;
Ads.promoter = eoa;
Ads.reach = reach_;
Ads.budget = reach_ * reward_;
Ads.reward = reward_;
Ads.created = block.timestamp;
Ads.expired = Ads.created + 15 days;
Ads.claimers = 0;
Ads.scamReport = 0;
minReward = minReward_;
claimerFee = claimerFee_;
PPeCAddress = PPeCAddress_;
promoterFee = promoterFee_;
adCreatorAddress = msg.sender;
minClaimerBalance = minClaimerBalance_;
}
// Events that will be emitted on changes.
event Scam();
event Destroy();
event ScamReport();
event Claim(address indexed claimer, uint256 reward);
event DelegateCleaner(address indexed claimer, uint256 reward);
/// You have already claimed the reward.
error Claimed();
/// You do not have enough tokens to claim rewards.
error NotEnoughTokens(uint256 minBalance, uint256 balance);
/// Reward exceed coffer balance.
error NotEnoughReward(uint256 reward, uint256 coffer);
/// The promotion has expired.
error PromotionEnded();
/// The promotion has not expired.
error PromotionRunning();
/// The promoter refund/claim date has not passed.
error CannotClean();
/// @dev Make a function not callable by the founder nor the promoter.
modifier notOwners() {
require(msg.sender != Ads.promoter, "Your are the Promoter.");
require(msg.sender != PPeC(PPeCAddress).founder(), "Your are the Founder.");
_;
}
/// @dev Make a function callable only by the founder.
modifier onlyFounder() {
require(msg.sender == PPeC(PPeCAddress).founder(), "Your are not the Founder.");
_;
}
/// @dev Make a function callable only by the promoter.
modifier onlyPromoter() {
require(msg.sender == Ads.promoter, "Your are not the Promoter.");
_;
}
/// Claim rewards.
function claim() public notOwners {
uint256 claimerBalance = PPeC(PPeCAddress).balanceOf(msg.sender);
bool claimedStatus = claimed[address(this)][msg.sender];
if (claimedStatus == true)
revert Claimed();
if (minClaimerBalance > claimerBalance)
revert NotEnoughTokens(minClaimerBalance, claimerBalance);
if (Ads.reward > cofferBalance() || Ads.reward > Ads.budget)
revert NotEnoughReward(Ads.reward, cofferBalance());
if (block.timestamp > Ads.expired)
revert PromotionEnded();
claimed[address(this)][msg.sender] = true;
Ads.claimers += 1;
_transfer(msg.sender, claimerFee, Ads.reward, Ads.reward);
// feedback.
emit Claim(msg.sender, Ads.reward);
}
/// Claim leftover rewards after advertisement expires.
function destroy() public onlyPromoter {
if (block.timestamp < Ads.expired)
revert PromotionRunning();
_extraTokenCheck(Ads.promoter, promoterFee, cofferBalance());
// feedback.
emit Destroy();
}
/// Claim leftover tokens 4 days after advertisement expires.
function delegateCleaner() public notOwners {
if (block.timestamp < Ads.expired + 4 days)
revert CannotClean();
_extraTokenCheck(msg.sender, claimerFee, cofferBalance());
// feedback.
emit DelegateCleaner(msg.sender, cofferBalance());
}
/// Empty the contract's tokens and make it harder for
/// the promoter to advertise.
function scam() public onlyFounder returns (bool success) {
SmACCor(adCreatorAddress).updatePledged(Ads.promoter, 10000000000E18);
PPeC(PPeCAddress).transfer(PPeC(PPeCAddress).treasury(), cofferBalance());
Ads.budget = 0;
// feedbacks.
emit Scam();
return true;
}
/// Report this SmAC as a scam.
function scamReport() public returns (bool reported) {
uint256 claimerBalance = PPeC(PPeCAddress).balanceOf(msg.sender);
bool claimedStatus = claimed[address(this)][msg.sender];
if (claimedStatus == true)
revert Claimed();
if (minClaimerBalance > claimerBalance)
revert NotEnoughTokens(minClaimerBalance, claimerBalance);
if (block.timestamp > Ads.expired)
revert PromotionEnded();
claimed[address(this)][msg.sender] = true;
Ads.scamReport += 1;
// feedbacks.
emit ScamReport();
return true;
}
// Reusable function
function _transfer(address receiver, uint256 fee, uint256 reward, uint256 unPledged)
internal
virtual
returns(bool success)
{
uint256 treasuryShare = ((reward * 100) * fee) / 1000000;
uint256 receiverShare = reward - treasuryShare;
uint256 pledged = SmACCor(adCreatorAddress).pledged(Ads.promoter);
SmACCor(adCreatorAddress).updatePledged(Ads.promoter, pledged - unPledged);
Ads.budget -= unPledged;
PPeC(PPeCAddress).transfer(PPeC(PPeCAddress).treasury(), treasuryShare);
PPeC(PPeCAddress).transfer(receiver, receiverShare);
return true;
}
// Reusable function
function _extraTokenCheck(address receiver, uint256 fee, uint256 balance)
internal
virtual
{
uint256 reward;
uint256 extraToken;
uint256 pledge;
if (balance > Ads.budget){
extraToken = balance - Ads.budget;
reward = balance - extraToken;
pledge = reward;
}
else if (balance < Ads.budget) {
extraToken = 0;
reward = balance;
pledge = Ads.budget;
}
else {
reward = balance;
extraToken = 0;
pledge = balance;
}
_transfer(receiver, fee, reward, pledge);
PPeC(PPeCAddress).transfer(Ads.promoter, extraToken);
}
/// Get claimer's claim status.
function claimStatus() public view returns(bool) {
return claimed[address(this)][msg.sender];
}
/// Get the contract [coffer] balance.
function cofferBalance() public view returns(uint256) {
return PPeC(PPeCAddress).balanceOf(address(this));
}
/// Get the promoter's pledged balance.
function pledgedBalance() public view returns(uint256) {
return SmACCor(adCreatorAddress).pledged(Ads.promoter);
}
/// Get important advertisement information.
function getInfo()
public
view
returns(string memory, string memory, uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256, bool, address)
{
return (
Ads.title,
Ads.link,
Ads.reach,
Ads.reward,
Ads.scamReport,
Ads.created,
Ads.expired,
Ads.claimers,
Ads.budget,
PPeC(PPeCAddress).balanceOf(address(this)),
claimed[address(this)][msg.sender],
Ads.promoter
);
}
}
| Report this SmAC as a scam. feedbacks. | function scamReport() public returns (bool reported) {
uint256 claimerBalance = PPeC(PPeCAddress).balanceOf(msg.sender);
bool claimedStatus = claimed[address(this)][msg.sender];
if (claimedStatus == true)
revert Claimed();
if (minClaimerBalance > claimerBalance)
revert NotEnoughTokens(minClaimerBalance, claimerBalance);
if (block.timestamp > Ads.expired)
revert PromotionEnded();
claimed[address(this)][msg.sender] = true;
Ads.scamReport += 1;
emit ScamReport();
return true;
}
| 14,095,642 | [
1,
4820,
333,
9425,
2226,
487,
279,
888,
301,
18,
10762,
87,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
888,
301,
4820,
1435,
1071,
1135,
261,
6430,
14010,
13,
288,
203,
203,
3639,
2254,
5034,
927,
69,
4417,
13937,
273,
453,
11227,
39,
12,
6584,
73,
39,
1887,
2934,
12296,
951,
12,
3576,
18,
15330,
1769,
203,
203,
3639,
1426,
7516,
329,
1482,
273,
7516,
329,
63,
2867,
12,
2211,
13,
6362,
3576,
18,
15330,
15533,
7010,
203,
3639,
309,
261,
14784,
329,
1482,
422,
638,
13,
203,
5411,
15226,
18381,
329,
5621,
203,
203,
3639,
309,
261,
1154,
2009,
69,
4417,
13937,
405,
927,
69,
4417,
13937,
13,
203,
5411,
15226,
2288,
664,
4966,
5157,
12,
1154,
2009,
69,
4417,
13937,
16,
927,
69,
4417,
13937,
1769,
203,
203,
3639,
309,
261,
2629,
18,
5508,
405,
432,
2377,
18,
15820,
13,
203,
5411,
15226,
17552,
8240,
28362,
5621,
203,
203,
3639,
7516,
329,
63,
2867,
12,
2211,
13,
6362,
3576,
18,
15330,
65,
273,
638,
31,
203,
203,
3639,
432,
2377,
18,
1017,
301,
4820,
1011,
404,
31,
203,
203,
3639,
3626,
2850,
301,
4820,
5621,
203,
3639,
327,
638,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0x4d7D5F90554aa9775114c64a332ebeb9652FAb0c/sources/YUTA.sol | exclude from paying fees or having max transaction amount | constructor() ERC20("Yuta", "YUTA") {
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(
0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D
);
excludeFromMaxTransaction(address(_uniswapV2Router), true);
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
excludeFromMaxTransaction(address(uniswapV2Pair), true);
_setAutomatedMarketMakerPair(address(uniswapV2Pair), true);
uint256 _buyMarketingFee = 4;
uint256 _buyLiquidityFee = 1;
uint256 _buyDevFee = 0;
uint256 _sellMarketingFee = 4;
uint256 _sellLiquidityFee = 1;
uint256 _sellDevFee = 0;
uint256 totalSupply = 1_000_000_000 * 1e18;
buyMarketingFee = _buyMarketingFee;
buyLiquidityFee = _buyLiquidityFee;
buyDevFee = _buyDevFee;
buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee;
sellMarketingFee = _sellMarketingFee;
sellLiquidityFee = _sellLiquidityFee;
sellDevFee = _sellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
excludeFromFees(owner(), true);
excludeFromFees(address(this), true);
excludeFromFees(address(0xdead), true);
excludeFromMaxTransaction(owner(), true);
excludeFromMaxTransaction(address(this), true);
excludeFromMaxTransaction(address(0xdead), true);
_mint is an internal function in ERC20.sol that is only called here,
and CANNOT be called ever again
_mint(msg.sender, totalSupply);
| 15,540,320 | [
1,
10157,
628,
8843,
310,
1656,
281,
578,
7999,
943,
2492,
3844,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
3885,
1435,
4232,
39,
3462,
2932,
61,
322,
69,
3113,
315,
61,
1693,
37,
7923,
288,
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,
203,
5411,
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,
203,
3639,
11272,
203,
203,
3639,
4433,
1265,
2747,
3342,
12,
2867,
24899,
318,
291,
91,
438,
58,
22,
8259,
3631,
638,
1769,
203,
3639,
640,
291,
91,
438,
58,
22,
8259,
273,
389,
318,
291,
91,
438,
58,
22,
8259,
31,
203,
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,
10756,
203,
5411,
263,
2640,
4154,
12,
2867,
12,
2211,
3631,
389,
318,
291,
91,
438,
58,
22,
8259,
18,
59,
1584,
44,
10663,
203,
3639,
4433,
1265,
2747,
3342,
12,
2867,
12,
318,
291,
91,
438,
58,
22,
4154,
3631,
638,
1769,
203,
3639,
389,
542,
22932,
690,
3882,
278,
12373,
4154,
12,
2867,
12,
318,
291,
91,
438,
58,
22,
4154,
3631,
638,
1769,
203,
203,
3639,
2254,
5034,
389,
70,
9835,
3882,
21747,
14667,
273,
1059,
31,
203,
3639,
2254,
5034,
389,
70,
9835,
48,
18988,
24237,
14667,
273,
404,
31,
203,
3639,
2254,
5034,
389,
70,
9835,
8870,
2
] |
./partial_match/4/0x50daF484c888BFBccd0E383c6CB943a0A337ee1B/sources/SocialGovernor.sol | add Liquidity or -stake-, requires inputs of the particular mine, the tokens to be staked, the amount to be staked, the reward tier, socialID => date tokens are free to un-stake and token rewards question here..... the requirement for minStakeAmt is only in the SLM contract, which means that a user could get reverted transactions, but perhaps thats the benefit of using parjar interface...transfer minerFees from the house acct to the fees accountnow that both stake tokens have been brought in and rewards have been delivered out - we need to store the new miner in our struct... so depends if they are social or notthis person is social! now we go into the mapping into the specific mine struct and map them to the next number in the socPPL counterthis person is anti social. we are still going to assign them a unique miner number and return it in the same way, but we'll set their sID to 0. | function stake(address _mine, address stAddress, uint sTokens, uint _tier, uint sID, address to) public returns (uint _unLockTime, uint rewards, uint socialNum) {
require(m.stakeToken == stAddress, "This isn't the right token");
require(m.remainingRewards >= _rewards, "Sorry no more rewards left!");
transferFees(_mine, _rewards);
if (msg.sender == parjar) {
socialNum = m.socPPL;
m.socialMiners[m.socPPL++] = SocialMiner(msg.sender, to, unlockTime, _mine, sTokens, sID, true);
socialNum = m.socPPL;
m.socialMiners[m.socPPL++] = SocialMiner(msg.sender, msg.sender, unlockTime, _mine, sTokens, 0, true);
}
}
| 8,666,753 | [
1,
1289,
511,
18988,
24237,
578,
300,
334,
911,
17,
16,
4991,
4540,
434,
326,
6826,
312,
558,
16,
326,
2430,
358,
506,
384,
9477,
16,
326,
3844,
358,
506,
384,
9477,
16,
326,
19890,
17742,
16,
16702,
734,
516,
1509,
2430,
854,
4843,
358,
640,
17,
334,
911,
471,
1147,
283,
6397,
5073,
2674,
838,
2777,
326,
12405,
364,
1131,
510,
911,
31787,
353,
1338,
316,
326,
348,
17063,
6835,
16,
1492,
4696,
716,
279,
729,
3377,
336,
15226,
329,
8938,
16,
1496,
26282,
716,
87,
326,
27641,
7216,
434,
1450,
779,
11930,
1560,
2777,
13866,
1131,
264,
2954,
281,
628,
326,
23867,
20774,
358,
326,
1656,
281,
2236,
3338,
716,
3937,
384,
911,
2430,
1240,
2118,
23670,
9540,
316,
471,
283,
6397,
1240,
2118,
22112,
596,
300,
732,
1608,
358,
1707,
326,
394,
1131,
264,
316,
3134,
1958,
2777,
1427,
10935,
309,
2898,
854,
16702,
578,
486,
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,
384,
911,
12,
2867,
389,
3081,
16,
1758,
384,
1887,
16,
2254,
272,
5157,
16,
2254,
389,
88,
2453,
16,
2254,
272,
734,
16,
1758,
358,
13,
1071,
1135,
261,
11890,
389,
318,
2531,
950,
16,
2254,
283,
6397,
16,
2254,
16702,
2578,
13,
288,
203,
3639,
2583,
12,
81,
18,
334,
911,
1345,
422,
384,
1887,
16,
315,
2503,
5177,
1404,
326,
2145,
1147,
8863,
203,
3639,
2583,
12,
81,
18,
17956,
17631,
14727,
1545,
389,
266,
6397,
16,
315,
28898,
1158,
1898,
283,
6397,
2002,
4442,
1769,
203,
3639,
7412,
2954,
281,
24899,
3081,
16,
389,
266,
6397,
1769,
203,
3639,
309,
261,
3576,
18,
15330,
422,
779,
11930,
13,
288,
203,
5411,
16702,
2578,
273,
312,
18,
87,
504,
52,
6253,
31,
203,
5411,
312,
18,
17582,
2930,
414,
63,
81,
18,
87,
504,
52,
6253,
9904,
65,
273,
29858,
2930,
264,
12,
3576,
18,
15330,
16,
358,
16,
7186,
950,
16,
389,
3081,
16,
272,
5157,
16,
272,
734,
16,
638,
1769,
203,
2398,
203,
5411,
16702,
2578,
273,
312,
18,
87,
504,
52,
6253,
31,
203,
5411,
312,
18,
17582,
2930,
414,
63,
81,
18,
87,
504,
52,
6253,
9904,
65,
273,
29858,
2930,
264,
12,
3576,
18,
15330,
16,
1234,
18,
15330,
16,
7186,
950,
16,
389,
3081,
16,
272,
5157,
16,
374,
16,
638,
1769,
203,
2398,
203,
3639,
289,
203,
565,
289,
203,
377,
203,
377,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.25;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
contract SafeMath {
/**
* @dev Subtracts two numbers, reverts on overflow.
*/
function safeSub(uint256 x, uint256 y) internal pure returns (uint256) {
assert(y <= x);
uint256 z = x - y;
return z;
}
/**
* @dev Adds two numbers, reverts on overflow.
*/
function safeAdd(uint256 x, uint256 y) internal pure returns (uint256) {
uint256 z = x + y;
assert(z >= x);
return z;
}
/**
* @dev Integer division of two numbers, reverts on division by zero.
*/
function safeDiv(uint256 x, uint256 y) internal pure returns (uint256) {
uint256 z = x / y;
return z;
}
/**
* @dev Multiplies two numbers, reverts on overflow.
*/
function safeMul(uint256 x, uint256 y) internal pure returns (uint256) {
if (x == 0) {
return 0;
}
uint256 z = x * y;
assert(z / x == y);
return z;
}
/**
* @dev Returns the integer percentage of the number.
*/
function safePerc(uint256 x, uint256 y) internal pure returns (uint256) {
if (x == 0) {
return 0;
}
uint256 z = x * y;
assert(z / x == y);
z = z / 10000; // percent to hundredths
return z;
}
/**
* @dev Returns the minimum value of two numbers.
*/
function min(uint256 x, uint256 y) internal pure returns (uint256) {
uint256 z = x <= y ? x : y;
return z;
}
/**
* @dev Returns the maximum value of two numbers.
*/
function max(uint256 x, uint256 y) internal pure returns (uint256) {
uint256 z = x >= y ? x : y;
return z;
}
}
/**
* @title DAppDEXI - Interface
*/
interface DAppDEXI {
function updateAgent(address _agent, bool _status) external;
function setAccountType(address user_, uint256 type_) external;
function getAccountType(address user_) external view returns(uint256);
function setFeeType(uint256 type_ , uint256 feeMake_, uint256 feeTake_) external;
function getFeeMake(uint256 type_ ) external view returns(uint256);
function getFeeTake(uint256 type_ ) external view returns(uint256);
function changeFeeAccount(address feeAccount_) external;
function setWhitelistTokens(address token) external;
function setWhitelistTokens(address token, bool active, uint256 timestamp, bytes32 typeERC) external;
function depositToken(address token, uint amount) external;
function tokenFallback(address owner, uint256 amount, bytes data) external returns (bool success);
function withdraw(uint amount) external;
function withdrawToken(address token, uint amount) external;
function balanceOf(address token, address user) external view returns (uint);
function order(address tokenBuy, uint amountBuy, address tokenSell, uint amountSell, uint expires, uint nonce) external;
function trade(address tokenBuy, uint amountBuy, address tokenSell, uint amountSell, uint expires, uint nonce, address user, uint8 v, bytes32 r, bytes32 s, uint amount) external;
function cancelOrder(address tokenBuy, uint amountBuy, address tokenSell, uint amountSell, uint expires, uint nonce, uint8 v, bytes32 r, bytes32 s) external;
function testTrade(address tokenBuy, uint amountBuy, address tokenSell, uint amountSell, uint expires, uint nonce, address user, uint8 v, bytes32 r, bytes32 s, uint amount, address sender) external view returns(bool);
function availableVolume(address tokenBuy, uint amountBuy, address tokenSell, uint amountSell, uint expires, uint nonce, address user, uint8 v, bytes32 r, bytes32 s) external view returns(uint);
function amountFilled(address tokenBuy, uint amountBuy, address tokenSell, uint amountSell, uint expires, uint nonce, address user) external view returns(uint);
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
interface ERC20I {
function balanceOf(address _owner) external view returns (uint256);
function totalSupply() external view returns (uint256);
function transfer(address _to, uint256 _value) external returns (bool success);
function allowance(address _owner, address _spender) external view returns (uint256);
function transferFrom(address _from, address _to, uint256 _value) external returns (bool success);
function approve(address _spender, uint256 _value) external returns (bool success);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title Ownable contract - base contract with an owner
*/
contract Ownable {
address public owner;
address public newOwner;
event OwnershipTransferred(address indexed _from, address indexed _to);
/**
* @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() {
assert(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 {
assert(_newOwner != address(0));
newOwner = _newOwner;
}
/**
* @dev Accept transferOwnership.
*/
function acceptOwnership() public {
if (msg.sender == newOwner) {
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
}
/**
* @title SDADI - Interface
*/
interface SDADI {
function AddToken(address token) external;
function DelToken(address token) external;
}
/**
* @title Standard ERC20 token + balance on date
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20Base is ERC20I, SafeMath {
uint256 totalSupply_;
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) internal allowed;
uint256 public start = 0; // Must be equal to the date of issue tokens
uint256 public period = 30 days; // By default, the dividend accrual period is 30 days
mapping (address => mapping (uint256 => int256)) public ChangeOverPeriod;
address[] public owners;
mapping (address => bool) public ownersIndex;
struct _Prop {
uint propID; // proposal ID in DAO
uint endTime; // end time of voting
}
_Prop[] public ActiveProposals; // contains active proposals
// contains voted Tokens on proposals
mapping (uint => mapping (address => uint)) public voted;
/**
* @dev Total Supply
* @return totalSupply_
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev Tokens balance
* @param _owner holder address
* @return balance amount
*/
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
/**
* @dev Balance of tokens on date
* @param _owner holder address
* @return balance amount
*/
function balanceOf(address _owner, uint _date) public view returns (uint256) {
require(_date >= start);
uint256 N1 = (_date - start) / period + 1;
uint256 N2 = 1;
if (block.timestamp > start) {
N2 = (block.timestamp - start) / period + 1;
}
require(N2 >= N1);
int256 B = int256(balances[_owner]);
while (N2 > N1) {
B = B - ChangeOverPeriod[_owner][N2];
N2--;
}
require(B >= 0);
return uint256(B);
}
/**
* @dev Tranfer tokens to address
* @param _to dest address
* @param _value tokens amount
* @return transfer result
*/
function transfer(address _to, uint256 _value) public returns (bool success) {
require(_to != address(0));
uint lock = 0;
for (uint k = 0; k < ActiveProposals.length; k++) {
if (ActiveProposals[k].endTime > now) {
if (lock < voted[ActiveProposals[k].propID][msg.sender]) {
lock = voted[ActiveProposals[k].propID][msg.sender];
}
}
}
require(safeSub(balances[msg.sender], lock) >= _value);
if (ownersIndex[_to] == false && _value > 0) {
ownersIndex[_to] = true;
owners.push(_to);
}
balances[msg.sender] = safeSub(balances[msg.sender], _value);
balances[_to] = safeAdd(balances[_to], _value);
uint256 N = 1;
if (block.timestamp > start) {
N = (block.timestamp - start) / period + 1;
}
ChangeOverPeriod[msg.sender][N] = ChangeOverPeriod[msg.sender][N] - int256(_value);
ChangeOverPeriod[_to][N] = ChangeOverPeriod[_to][N] + int256(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Token allowance
* @param _owner holder address
* @param _spender spender address
* @return remain amount
*/
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
/**
* @dev Transfer tokens from one address to another
* @param _from source address
* @param _to dest address
* @param _value tokens amount
* @return transfer result
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_to != address(0));
uint lock = 0;
for (uint k = 0; k < ActiveProposals.length; k++) {
if (ActiveProposals[k].endTime > now) {
if (lock < voted[ActiveProposals[k].propID][_from]) {
lock = voted[ActiveProposals[k].propID][_from];
}
}
}
require(safeSub(balances[_from], lock) >= _value);
require(allowed[_from][msg.sender] >= _value);
if (ownersIndex[_to] == false && _value > 0) {
ownersIndex[_to] = true;
owners.push(_to);
}
balances[_from] = safeSub(balances[_from], _value);
balances[_to] = safeAdd(balances[_to], _value);
allowed[_from][msg.sender] = safeSub(allowed[_from][msg.sender], _value);
uint256 N = 1;
if (block.timestamp > start) {
N = (block.timestamp - start) / period + 1;
}
ChangeOverPeriod[_from][N] = ChangeOverPeriod[_from][N] - int256(_value);
ChangeOverPeriod[_to][N] = ChangeOverPeriod[_to][N] + int256(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve transfer
* @param _spender holder address
* @param _value tokens amount
* @return result
*/
function approve(address _spender, uint256 _value) public returns (bool success) {
require((_value == 0) || (allowed[msg.sender][_spender] == 0));
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Trim owners with zero balance
*/
function trim(uint offset, uint limit) external returns (bool) {
uint k = offset;
uint ln = limit;
while (k < ln) {
if (balances[owners[k]] == 0) {
ownersIndex[owners[k]] = false;
owners[k] = owners[owners.length-1];
owners.length = owners.length-1;
ln--;
} else {
k++;
}
}
return true;
}
// current number of shareholders (owners)
function getOwnersCount() external view returns (uint256 count) {
return owners.length;
}
// current period
function getCurrentPeriod() external view returns (uint256 N) {
if (block.timestamp > start) {
return (block.timestamp - start) / period;
} else {
return 0;
}
}
function addProposal(uint _propID, uint _endTime) internal {
ActiveProposals.push(_Prop({
propID: _propID,
endTime: _endTime
}));
}
function delProposal(uint _propID) internal {
uint k = 0;
while (k < ActiveProposals.length){
if (ActiveProposals[k].propID == _propID) {
require(ActiveProposals[k].endTime < now);
ActiveProposals[k] = ActiveProposals[ActiveProposals.length-1];
ActiveProposals.length = ActiveProposals.length-1;
} else {
k++;
}
}
}
function getVoted(uint _propID, address _voter) external view returns (uint) {
return voted[_propID][_voter];
}
}
/**
* @title Dividend Distribution Contract for DAO
*/
contract Dividends is ERC20Base, Ownable {
DAppDEXI public DEX;
address[] public tokens;
mapping (address => uint) public tokensIndex;
mapping (uint => mapping (address => uint)) public dividends;
mapping (address => mapping (address => uint)) public ownersbal;
mapping (uint => mapping (address => mapping (address => bool))) public AlreadyReceived;
uint public multiplier = 100000; // precision to ten thousandth percent (0.001%)
event Payment(address indexed sender, uint amount);
event setDEXContractEvent(address dex);
function AddToken(address token) public {
require(msg.sender == address(DEX));
tokens.push(token);
tokensIndex[token] = tokens.length-1;
}
function DelToken(address token) public {
require(msg.sender == address(DEX));
require(tokens[tokensIndex[token]] != 0);
tokens[tokensIndex[token]] = tokens[tokens.length-1];
tokens.length = tokens.length-1;
}
// Take profit for dividends from DEX contract
function TakeProfit(uint offset, uint limit) external {
require (limit <= tokens.length);
require (offset < limit);
uint N = (block.timestamp - start) / period;
require (N > 0);
for (uint k = offset; k < limit; k++) {
if(dividends[N][tokens[k]] == 0 ) {
uint amount = DEX.balanceOf(tokens[k], address(this));
if (k == 0) {
DEX.withdraw(amount);
dividends[N][tokens[k]] = amount;
} else {
DEX.withdrawToken(tokens[k], amount);
dividends[N][tokens[k]] = amount;
}
}
}
}
function () public payable {
emit Payment(msg.sender, msg.value);
}
// PayDividends to owners
function PayDividends(address token, uint offset, uint limit) external {
//require (address(this).balance > 0);
require (limit <= owners.length);
require (offset < limit);
uint N = (block.timestamp - start) / period; // current - 1
uint date = start + N * period - 1;
require(dividends[N][token] > 0);
uint share = 0;
uint k = 0;
for (k = offset; k < limit; k++) {
if (!AlreadyReceived[N][token][owners[k]]) {
share = safeMul(balanceOf(owners[k], date), multiplier);
share = safeDiv(safeMul(share, 100), totalSupply_); // calc the percentage of the totalSupply_ (from 100%)
share = safePerc(dividends[N][token], share);
share = safeDiv(share, safeDiv(multiplier, 100)); // safeDiv(multiplier, 100) - convert to hundredths
ownersbal[owners[k]][token] = safeAdd(ownersbal[owners[k]][token], share);
AlreadyReceived[N][token][owners[k]] = true;
}
}
}
// PayDividends individuals to msg.sender
function PayDividends(address token) external {
//require (address(this).balance > 0);
uint N = (block.timestamp - start) / period; // current - 1
uint date = start + N * period - 1;
require(dividends[N][token] > 0);
if (!AlreadyReceived[N][token][msg.sender]) {
uint share = safeMul(balanceOf(msg.sender, date), multiplier);
share = safeDiv(safeMul(share, 100), totalSupply_); // calc the percentage of the totalSupply_ (from 100%)
share = safePerc(dividends[N][token], share);
share = safeDiv(share, safeDiv(multiplier, 100)); // safeDiv(multiplier, 100) - convert to hundredths
ownersbal[msg.sender][token] = safeAdd(ownersbal[msg.sender][token], share);
AlreadyReceived[N][token][msg.sender] = true;
}
}
// withdraw dividends
function withdraw(address token, uint _value) external {
require(ownersbal[msg.sender][token] >= _value);
ownersbal[msg.sender][token] = safeSub(ownersbal[msg.sender][token], _value);
if (token == address(0)) {
msg.sender.transfer(_value);
} else {
ERC20I(token).transfer(msg.sender, _value);
}
}
// withdraw dividends to address
function withdraw(address token, uint _value, address _receiver) external {
require(ownersbal[msg.sender][token] >= _value);
ownersbal[msg.sender][token] = safeSub(ownersbal[msg.sender][token], _value);
if (token == address(0)) {
_receiver.transfer(_value);
} else {
ERC20I(token).transfer(_receiver, _value);
}
}
function setMultiplier(uint _value) external onlyOwner {
require(_value > 0);
multiplier = _value;
}
function getMultiplier() external view returns (uint ) {
return multiplier;
}
// link to DEX contract
function setDEXContract(address _contract) external onlyOwner {
DEX = DAppDEXI(_contract);
emit setDEXContractEvent(_contract);
}
}
/**
* @title External interface for DAO
*/
interface CommonI {
function transferOwnership(address _newOwner) external;
function acceptOwnership() external;
function updateAgent(address _agent, bool _state) external;
}
/**
* @title Decentralized Autonomous Organization
*/
contract DAO is Dividends {
//minimum balance for adding proposal - default 10000 tokens
uint minBalance = 1000000000000;
// minimum quorum - number of votes must be more than minimum quorum
uint public minimumQuorum;
// debating period duration
uint public debatingPeriodDuration;
// requisite majority of votes (by the system a simple majority)
uint public requisiteMajority;
struct _Proposal {
// proposal may execute only after voting ended
uint endTimeOfVoting;
// if executed = true
bool executed;
// if passed = true
bool proposalPassed;
// number of votes already voted
uint numberOfVotes;
// in support of votes
uint votesSupport;
// against votes
uint votesAgainst;
// the address where the `amount` will go to if the proposal is accepted
address recipient;
// the amount to transfer to `recipient` if the proposal is accepted.
uint amount;
// keccak256(abi.encodePacked(recipient, amount, transactionByteCode));
bytes32 transactionHash;
// a plain text description of the proposal
string desc;
// a hash of full description data of the proposal (optional)
string fullDescHash;
}
_Proposal[] public Proposals;
event ProposalAdded(uint proposalID, address recipient, uint amount, string description, string fullDescHash);
event Voted(uint proposalID, bool position, address voter, string justification);
event ProposalTallied(uint proposalID, uint votesSupport, uint votesAgainst, uint quorum, bool active);
event ChangeOfRules(uint newMinimumQuorum, uint newdebatingPeriodDuration, uint newRequisiteMajority);
event Payment(address indexed sender, uint amount);
// Modifier that allows only owners of tokens to vote and create new proposals
modifier onlyMembers {
require(balances[msg.sender] > 0);
_;
}
/**
* Change voting rules
*
* Make so that Proposals need to be discussed for at least `_debatingPeriodDuration/60` hours,
* have at least `_minimumQuorum` votes, and have 50% + `_requisiteMajority` votes to be executed
*
* @param _minimumQuorum how many members must vote on a proposal for it to be executed
* @param _debatingPeriodDuration the minimum amount of delay between when a proposal is made and when it can be executed
* @param _requisiteMajority the proposal needs to have 50% plus this number
*/
function changeVotingRules(
uint _minimumQuorum,
uint _debatingPeriodDuration,
uint _requisiteMajority
) onlyOwner public {
minimumQuorum = _minimumQuorum;
debatingPeriodDuration = _debatingPeriodDuration;
requisiteMajority = _requisiteMajority;
emit ChangeOfRules(minimumQuorum, debatingPeriodDuration, requisiteMajority);
}
/**
* Add Proposal
*
* Propose to send `_amount / 1e18` ether to `_recipient` for `_desc`. `_transactionByteCode ? Contains : Does not contain` code.
*
* @param _recipient who to send the ether to
* @param _amount amount of ether to send, in wei
* @param _desc Description of job
* @param _fullDescHash Hash of full description of job
* @param _transactionByteCode bytecode of transaction
*/
function addProposal(address _recipient, uint _amount, string _desc, string _fullDescHash, bytes _transactionByteCode, uint _debatingPeriodDuration) onlyMembers public returns (uint) {
require(balances[msg.sender] > minBalance);
if (_debatingPeriodDuration == 0) {
_debatingPeriodDuration = debatingPeriodDuration;
}
Proposals.push(_Proposal({
endTimeOfVoting: now + _debatingPeriodDuration * 1 minutes,
executed: false,
proposalPassed: false,
numberOfVotes: 0,
votesSupport: 0,
votesAgainst: 0,
recipient: _recipient,
amount: _amount,
transactionHash: keccak256(abi.encodePacked(_recipient, _amount, _transactionByteCode)),
desc: _desc,
fullDescHash: _fullDescHash
}));
// add proposal in ERC20 base contract for block transfer
super.addProposal(Proposals.length-1, Proposals[Proposals.length-1].endTimeOfVoting);
emit ProposalAdded(Proposals.length-1, _recipient, _amount, _desc, _fullDescHash);
return Proposals.length-1;
}
/**
* Check if a proposal code matches
*
* @param _proposalID number of the proposal to query
* @param _recipient who to send the ether to
* @param _amount amount of ether to send
* @param _transactionByteCode bytecode of transaction
*/
function checkProposalCode(uint _proposalID, address _recipient, uint _amount, bytes _transactionByteCode) view public returns (bool) {
require(Proposals[_proposalID].recipient == _recipient);
require(Proposals[_proposalID].amount == _amount);
// compare ByteCode
return Proposals[_proposalID].transactionHash == keccak256(abi.encodePacked(_recipient, _amount, _transactionByteCode));
}
/**
* Log a vote for a proposal
*
* Vote `supportsProposal? in support of : against` proposal #`proposalID`
*
* @param _proposalID number of proposal
* @param _supportsProposal either in favor or against it
* @param _justificationText optional justification text
*/
function vote(uint _proposalID, bool _supportsProposal, string _justificationText) onlyMembers public returns (uint) {
// Get the proposal
_Proposal storage p = Proposals[_proposalID];
require(now <= p.endTimeOfVoting);
// get numbers of votes for msg.sender
uint votes = safeSub(balances[msg.sender], voted[_proposalID][msg.sender]);
require(votes > 0);
voted[_proposalID][msg.sender] = safeAdd(voted[_proposalID][msg.sender], votes);
// Increase the number of votes
p.numberOfVotes = p.numberOfVotes + votes;
if (_supportsProposal) {
p.votesSupport = p.votesSupport + votes;
} else {
p.votesAgainst = p.votesAgainst + votes;
}
emit Voted(_proposalID, _supportsProposal, msg.sender, _justificationText);
return p.numberOfVotes;
}
/**
* Finish vote
*
* Count the votes proposal #`_proposalID` and execute it if approved
*
* @param _proposalID proposal number
* @param _transactionByteCode optional: if the transaction contained a bytecode, you need to send it
*/
function executeProposal(uint _proposalID, bytes _transactionByteCode) public {
// Get the proposal
_Proposal storage p = Proposals[_proposalID];
require(now > p.endTimeOfVoting // If it is past the voting deadline
&& !p.executed // and it has not already been executed
&& p.transactionHash == keccak256(abi.encodePacked(p.recipient, p.amount, _transactionByteCode)) // and the supplied code matches the proposal
&& p.numberOfVotes >= minimumQuorum); // and a minimum quorum has been reached
// then execute result
if (p.votesSupport > requisiteMajority) {
// Proposal passed; execute the transaction
require(p.recipient.call.value(p.amount)(_transactionByteCode));
p.proposalPassed = true;
} else {
// Proposal failed
p.proposalPassed = false;
}
p.executed = true;
// delete proposal from active list
super.delProposal(_proposalID);
// Fire Events
emit ProposalTallied(_proposalID, p.votesSupport, p.votesAgainst, p.numberOfVotes, p.proposalPassed);
}
// function is needed if execution transactionByteCode in Proposal failed
function delActiveProposal(uint _proposalID) public onlyOwner {
// delete proposal from active list
super.delProposal(_proposalID);
}
/**
* @dev Allows the DAO to transfer control of the _contract to a _newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function transferOwnership(address _contract, address _newOwner) public onlyOwner {
CommonI(_contract).transferOwnership(_newOwner);
}
/**
* @dev Accept transferOwnership on a this (DAO) contract
*/
function acceptOwnership(address _contract) public onlyOwner {
CommonI(_contract).acceptOwnership();
}
function updateAgent(address _contract, address _agent, bool _state) public onlyOwner {
CommonI(_contract).updateAgent(_agent, _state);
}
/**
* Set minimum balance for adding proposal
*/
function setMinBalance(uint _minBalance) public onlyOwner {
assert(_minBalance > 0);
minBalance = _minBalance;
}
}
/**
* @title Agent contract - base contract with an agent
*/
contract Agent is Ownable {
address public defAgent;
mapping(address => bool) public Agents;
constructor() public {
Agents[msg.sender] = true;
}
modifier onlyAgent() {
assert(Agents[msg.sender]);
_;
}
function updateAgent(address _agent, bool _status) public onlyOwner {
assert(_agent != address(0));
Agents[_agent] = _status;
}
}
/**
* @title SDAD - ERC20 Token based on ERC20Base, DAO, Dividends smart contracts
*/
contract SDAD is SDADI, DAO {
uint public initialSupply = 10 * 10**6; // 10 million tokens
uint public decimals = 8;
string public name;
string public symbol;
/** Name and symbol were updated. */
event UpdatedTokenInformation(string _name, string _symbol);
/** Period were updated. */
event UpdatedPeriod(uint _period);
constructor(string _name, string _symbol, uint _start, uint _period, address _dexowner) public {
name = _name;
symbol = _symbol;
start = _start;
period = _period;
totalSupply_ = initialSupply*10**decimals;
// creating initial tokens
balances[_dexowner] = totalSupply_;
emit Transfer(0x0, _dexowner, balances[_dexowner]);
ownersIndex[_dexowner] = true;
owners.push(_dexowner);
ChangeOverPeriod[_dexowner][1] = int256(balances[_dexowner]);
// set voting rules
// _minimumQuorum = 50%
// _requisiteMajority = 25%
// _debatingPeriodDuration = 1 day
changeVotingRules(safePerc(totalSupply_, 5000), 1440, safePerc(totalSupply_, 2500));
// add ETH
tokens.push(address(0));
tokensIndex[address(0)] = tokens.length-1;
}
/**
* Owner can update token information here.
*
* It is often useful to conceal the actual token association, until
* the token operations, like central issuance or reissuance have been completed.
*
* This function allows the token owner to rename the token after the operations
* have been completed and then point the audience to use the token contract.
*/
function setTokenInformation(string _name, string _symbol) public onlyOwner {
name = _name;
symbol = _symbol;
emit UpdatedTokenInformation(_name, _symbol);
}
/**
* Owner can change period
*
*/
function setPeriod(uint _period) public onlyOwner {
period = _period;
emit UpdatedPeriod(_period);
}
/**
* set owner to self
*
*/
function setOwnerToSelf() public onlyOwner {
owner = address(this);
emit OwnershipTransferred(msg.sender, address(this));
}
} | * Name and symbol were updated. */* Period were updated. */ creating initial tokens set voting rules _minimumQuorum = 50% _requisiteMajority = 25% _debatingPeriodDuration = 1 day add ETH | constructor(string _name, string _symbol, uint _start, uint _period, address _dexowner) public {
name = _name;
symbol = _symbol;
start = _start;
period = _period;
totalSupply_ = initialSupply*10**decimals;
balances[_dexowner] = totalSupply_;
emit Transfer(0x0, _dexowner, balances[_dexowner]);
ownersIndex[_dexowner] = true;
owners.push(_dexowner);
ChangeOverPeriod[_dexowner][1] = int256(balances[_dexowner]);
changeVotingRules(safePerc(totalSupply_, 5000), 1440, safePerc(totalSupply_, 2500));
tokens.push(address(0));
tokensIndex[address(0)] = tokens.length-1;
}
| 15,818,681 | [
1,
461,
471,
3273,
4591,
3526,
18,
342,
12698,
4591,
3526,
18,
342,
4979,
2172,
2430,
444,
331,
17128,
2931,
389,
15903,
31488,
273,
6437,
9,
389,
4523,
291,
1137,
17581,
560,
273,
6969,
9,
389,
31888,
1776,
5027,
5326,
273,
404,
2548,
527,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
3885,
12,
1080,
389,
529,
16,
533,
389,
7175,
16,
2254,
389,
1937,
16,
2254,
389,
6908,
16,
1758,
389,
561,
8443,
13,
1071,
288,
203,
565,
508,
273,
389,
529,
31,
203,
565,
3273,
273,
389,
7175,
31,
203,
565,
787,
273,
389,
1937,
31,
203,
565,
3879,
273,
389,
6908,
31,
203,
203,
565,
2078,
3088,
1283,
67,
273,
2172,
3088,
1283,
14,
2163,
636,
31734,
31,
203,
203,
565,
324,
26488,
63,
67,
561,
8443,
65,
273,
2078,
3088,
1283,
67,
31,
377,
203,
565,
3626,
12279,
12,
20,
92,
20,
16,
389,
561,
8443,
16,
324,
26488,
63,
67,
561,
8443,
19226,
203,
203,
565,
25937,
1016,
63,
67,
561,
8443,
65,
273,
638,
31,
203,
565,
25937,
18,
6206,
24899,
561,
8443,
1769,
203,
203,
565,
7576,
4851,
5027,
63,
67,
561,
8443,
6362,
21,
65,
273,
509,
5034,
12,
70,
26488,
63,
67,
561,
8443,
19226,
203,
203,
565,
2549,
58,
17128,
4478,
12,
4626,
2173,
71,
12,
4963,
3088,
1283,
67,
16,
20190,
3631,
5045,
7132,
16,
4183,
2173,
71,
12,
4963,
3088,
1283,
67,
16,
6969,
713,
10019,
203,
203,
565,
2430,
18,
6206,
12,
2867,
12,
20,
10019,
203,
565,
2430,
1016,
63,
2867,
12,
20,
25887,
273,
2430,
18,
2469,
17,
21,
31,
203,
225,
289,
7010,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.5.6;
import "./ownership/Ownable.sol";
import "./math/SafeMath.sol";
import "./interface/IGusuelV2.sol";
import "./token/KIP37/KIP37Burnable.sol";
import "./token/KIP17/IKIP17.sol";
contract GuseulKongChick is Ownable, IGuseulV2 {
using SafeMath for uint256;
KIP37Burnable public coupon;
IKIP17 public kongz;
IKIP17 public chickiz;
// token Metadata
string public constant tokenName = "Gusuel KongChick";
string public constant tokenSymbol = "GSL";
uint8 public constant tokenDecimals = 4;
uint256 public constant freeTerm = 43200;
uint256 public constant freeDrop = 100000000;
function name() external pure returns (string memory) {
return tokenName;
}
function symbol() external pure returns (string memory) {
return tokenSymbol;
}
function decimals() external pure returns (uint8) {
return tokenDecimals;
}
// totalSupply & balances
uint256 public tokenTotalSupply = 0;
uint256 public round = 1;
struct UserInfo {
uint8 oddEven;
uint256 initialBalance;
uint256 canEarn;
uint256 lastRound;
uint256 freeBlock;
}
mapping(address => UserInfo) public _userInfo;
//round => user => uint256, bool
mapping(uint256 => mapping(address => bool)) private _betBool;
mapping(uint256 => mapping(address => uint256)) private _betQuan;
// odd = 1, even = 2
mapping(uint256 => uint8) public _roundResult;
function totalSupply() external view returns (uint256) {
return tokenTotalSupply;
}
function balanceOf(address user) external view returns (uint256 balance) {
return balances(user);
}
function balances(address user) public view returns (uint256 balance) {
UserInfo memory _uInfo = _userInfo[user];
if (_roundResult[_uInfo.lastRound] == _uInfo.oddEven) {
return _uInfo.canEarn.add(_uInfo.initialBalance);
}
return _uInfo.initialBalance;
}
constructor(
KIP37Burnable _coupon,
IKIP17 _kongz,
IKIP17 _chickiz
) public {
canTransfer[msg.sender] = true;
coupon = _coupon;
kongz = _kongz;
chickiz = _chickiz;
}
// only able to transfer when canTransfer is true
mapping(address => bool) public canTransfer;
function addCanTransfer(address adr) external onlyOwner {
canTransfer[adr] = true;
}
function _transfer(
address from,
address to,
uint256 amount
) internal {
require(from != address(0), "KIP7: transfer from the zero address");
require(to != address(0), "KIP7: transfer to the zero address");
emit Transfer(from, to, amount);
}
function transfer(address to, uint256 amount)
external
returns (bool success)
{
require(canTransfer[msg.sender] == true, "not Allowed");
_transfer(msg.sender, to, amount);
return true;
}
function transferFrom(
address from,
address to,
uint256 amount
) external returns (bool success) {
require(canTransfer[msg.sender] == true, "not Allowed");
_transfer(from, to, amount);
return true;
}
//airdrop
function airdrop(address[] memory adr, uint256 quant) public onlyOwner {
uint256 len = adr.length;
for (uint256 i = 0; i < len; i++) {
UserInfo storage _thisInfo = _userInfo[adr[i]];
_thisInfo.initialBalance = _thisInfo.initialBalance.add(quant);
emit Transfer(msg.sender, adr[i], quant);
}
}
//game
function freeGsl() public {
UserInfo memory _uInfo = _userInfo[msg.sender];
uint256 _uBalance = _uInfo.initialBalance;
uint256 _possibleBlock = _uInfo.freeBlock.add(freeTerm);
uint256 _kongzBalance = kongz.balanceOf(msg.sender);
uint256 _chickizBalance = chickiz.balanceOf(msg.sender);
require(_kongzBalance.add(_chickizBalance) > 0);
require(_possibleBlock <= block.number);
UserInfo storage _thisInfo = _userInfo[msg.sender];
_thisInfo.freeBlock = block.number;
_thisInfo.initialBalance = _uBalance.add(freeDrop);
emit Transfer(msg.sender, msg.sender, freeDrop);
}
function raffle(uint8 __result) public onlyOwner {
_roundResult[round] = __result;
round = round.add(1);
}
function bet(uint8 _oddEven, uint256 _howMuch) public {
require(_betBool[round][msg.sender] != true);
UserInfo storage _thisInfo = _userInfo[msg.sender];
uint256 nowQuant = balances(msg.sender);
_betBool[round][msg.sender] = true;
_betQuan[round][msg.sender] = _howMuch;
_thisInfo.oddEven = _oddEven;
_thisInfo.initialBalance = nowQuant.sub(_howMuch);
_thisInfo.canEarn = _howMuch.mul(2);
_thisInfo.lastRound = round;
emit Transfer(msg.sender, msg.sender, 0);
}
function betWithCoupon(uint8 _oddEven, uint256 _howMuch) public {
require(_betBool[round][msg.sender] != true);
coupon.burn(msg.sender, 0, 1);
UserInfo storage _thisInfo = _userInfo[msg.sender];
uint256 nowQuant = balances(msg.sender);
_betBool[round][msg.sender] = true;
_betQuan[round][msg.sender] = _howMuch;
_thisInfo.oddEven = _oddEven;
_thisInfo.initialBalance = nowQuant.sub(_howMuch);
_thisInfo.canEarn = _howMuch.mul(3);
_thisInfo.lastRound = round;
emit Transfer(msg.sender, msg.sender, 0);
}
function refresh() public {
emit Transfer(msg.sender, msg.sender, 0);
}
// view
function betOrNot(address adr) public view returns (bool) {
return _betBool[round][adr];
}
function thisRoundBet(address adr) public view returns (uint256) {
return _betQuan[round][adr];
}
function lastRoundEarn(address adr) public view returns (uint256) {
UserInfo memory _uInfo = _userInfo[adr];
if (
_uInfo.lastRound == round.sub(1) &&
_roundResult[_uInfo.lastRound] == _uInfo.oddEven
) {
return _uInfo.canEarn;
}
return 0;
}
function kongchickPoint(address adr) public view returns (uint256) {
return kongz.balanceOf(adr).mul(7).add(chickiz.balanceOf(adr));
}
//burn
function burnAll(address[] memory adr) public onlyOwner {
uint256 len = adr.length;
for (uint256 i = 0; i < len; i++) {
UserInfo storage _thisInfo = _userInfo[adr[i]];
_thisInfo.initialBalance = 0;
emit Transfer(adr[i], adr[i], 0);
}
tokenTotalSupply = 0;
round = round.add(1);
}
}
| round => user => uint256, bool | mapping(uint256 => mapping(address => bool)) private _betBool;
| 14,041,932 | [
1,
2260,
516,
729,
516,
2254,
5034,
16,
1426,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
2874,
12,
11890,
5034,
516,
2874,
12,
2867,
516,
1426,
3719,
3238,
389,
70,
278,
7464,
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
] |
./full_match/1/0x82a7b5842085f434c6584A8c44b6A1C15c25a512/sources/contracts/LiquidityManager.sol | Update processed count */ | processedIndices += 1;
| 9,659,048 | [
1,
1891,
5204,
1056,
342,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
5411,
5204,
8776,
1011,
404,
31,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/4/0xB942536a4255a04622C16dB974f54002DE78Da7a/sources/Inflator.sol | * @notice Inflates position exactly by `value` (one borrow-supply) cycle @dev This internal method doesnt checks risk and allowed borrow @param value Amount to inflate/ Encoding EVM script with 2 operations - borrow, supply | function inflateOnceExact(uint256 value) internal {
bytes memory borrowCalldata = abi.encodeWithSelector(ctoken.borrow.selector, value);
bytes memory supplyCalldata = abi.encodeWithSelector(ctoken.mint.selector, value);
bytes memory evmscript = abi.encodePacked(
uint32(borrowCalldata.length),
uint32(supplyCalldata.length),
supplyCalldata
);
agent.forward(evmscript);
}
| 8,607,068 | [
1,
27040,
815,
1754,
8950,
635,
1375,
1132,
68,
261,
476,
29759,
17,
2859,
1283,
13,
8589,
225,
1220,
2713,
707,
31272,
4271,
18404,
471,
2935,
29759,
225,
460,
16811,
358,
26809,
19,
13400,
512,
7397,
2728,
598,
576,
5295,
300,
29759,
16,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
26809,
12212,
14332,
12,
11890,
5034,
460,
13,
2713,
288,
203,
3639,
1731,
3778,
29759,
1477,
892,
273,
24126,
18,
3015,
1190,
4320,
12,
299,
969,
18,
70,
15318,
18,
9663,
16,
460,
1769,
203,
3639,
1731,
3778,
14467,
1477,
892,
273,
24126,
18,
3015,
1190,
4320,
12,
299,
969,
18,
81,
474,
18,
9663,
16,
460,
1769,
203,
3639,
1731,
3778,
2113,
959,
9118,
273,
24126,
18,
3015,
4420,
329,
12,
203,
5411,
2254,
1578,
12,
70,
15318,
1477,
892,
18,
2469,
3631,
203,
5411,
2254,
1578,
12,
2859,
1283,
1477,
892,
18,
2469,
3631,
203,
5411,
14467,
1477,
892,
203,
3639,
11272,
203,
3639,
4040,
18,
11565,
12,
14965,
959,
9118,
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
] |
./full_match/5/0xd3C803fc4f113BEac108A3406c09C32dB8671fbc/sources/contracts/GovernanceContract.sol | CrowdProject[] memory allProjects = new CrowdProject[](crowdProjectIds.length); | function getProjects() public view returns (ProjectMetaData[] memory) {
ProjectMetaData[] memory allMetaData;
for(uint32 i = 0; i < crowdProjectIds.length; i++) {
CrowdProject storage foundProject = crowdProjects[i];
if(foundProject.projectId != 0) {
ProjectMetaData memory metaData = ProjectMetaData(
foundProject.projectId,
foundProject.target,
foundProject.title,
foundProject.description);
allMetaData[i] = metaData;
}
}
return allMetaData;
}
| 1,920,047 | [
1,
39,
492,
72,
4109,
8526,
3778,
777,
15298,
273,
394,
385,
492,
72,
4109,
8526,
12,
71,
492,
72,
4109,
2673,
18,
2469,
1769,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
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,
4202,
445,
11080,
87,
1435,
1071,
1476,
1135,
261,
4109,
6998,
8526,
3778,
13,
288,
203,
3639,
5420,
6998,
8526,
3778,
777,
6998,
31,
203,
3639,
364,
12,
11890,
1578,
277,
273,
374,
31,
277,
411,
276,
492,
72,
4109,
2673,
18,
2469,
31,
277,
27245,
288,
203,
5411,
385,
492,
72,
4109,
2502,
1392,
4109,
273,
276,
492,
72,
15298,
63,
77,
15533,
203,
5411,
309,
12,
7015,
4109,
18,
4406,
548,
480,
374,
13,
288,
203,
7734,
5420,
6998,
3778,
11651,
273,
5420,
6998,
12,
7010,
13491,
1392,
4109,
18,
4406,
548,
16,
203,
13491,
1392,
4109,
18,
3299,
16,
203,
13491,
1392,
4109,
18,
2649,
16,
203,
13491,
1392,
4109,
18,
3384,
1769,
203,
1171,
203,
7734,
777,
6998,
63,
77,
65,
273,
11651,
31,
7010,
5411,
289,
203,
3639,
289,
203,
203,
3639,
327,
777,
6998,
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
] |
pragma solidity 0.5.7;
import "./../interfaces/ifoladt.sol";
import "./../helpers/ownable.sol";
/**
* @title fixed ordered bidirectional linked list concrete implementation of ifoladt
* @dev all fobll operation O(1) [note max iterations count eq capacity]
* @dev note all indexations start from 1
* inheritdoc
*/
contract FOBLL is IFOLADT, Ownable {
/**
* @dev initialize fobll with max size param
* @param capacity max size of fobll
*/
constructor(uint32 capacity) public {
__capacity = capacity;
}
/// inheritdoc
function size() external view returns(uint32) {
return __size;
}
/// inheritdoc
function capacity() external view returns(uint32) {
return __capacity;
}
/// inheritdoc
function empty() public view returns(bool) {
return __head == address(0) && __tail == address(0) && __size == 0;
}
/// inheritdoc
function push(address key, uint256 value) external owner {
// in case of invalid address specified
require(key != address(0), "Invalid push key specified");
// before start placement remove node from fobll
// replace node everytime isntead of update existed value
__remove(key);
// in case of empty fobll
// place single node into fobll
// than break from place method
// as placement was done already
if (empty()) {
__between(key, value, address(0), address(0), true);
return;
}
// start common place flow
__place(key, value);
}
/// inheritdoc
function index(address key) external view returns(uint32) {
// in case of invalid address specified
require(key != address(0), "Invalid index key specified");
uint32 idx = 1; // index start from first node
// iterate over all fobll nodes from head to tail
address it = __head;
address end = __nodes[__tail].next;
while (it != end) {
// in case we pass finish break
if (idx > __capacity) {
break;
}
Node memory node = __nodes[it];
if (node.self != key) {
// update fobll iterator
it = node.next;
// update iteration break index
++idx;
// skip while we not find right node
continue;
}
// in case we found right node
return idx;
}
return 0;
}
/// inheritdoc
function at(uint32 idx) public view returns(address) {
// in case of invalid index specified
require(idx != 0 && idx <= __capacity, "Invalid index specified");
uint32 lidx = 1; // index start from first node
// iterate over all fobll nodes from head to tail
address it = __head;
address end = __nodes[__tail].next;
while (it != end) {
// in case we pass finish break
if (lidx > idx) {
break;
}
Node memory node = __nodes[it];
if (idx != lidx) {
// update fobll iterator
it = node.next;
// update iteration break index
++lidx;
// skip while we not find right node
continue;
}
// in case we found right node
return node.self;
}
return address(0);
}
/// inheritdoc
function remove(uint32 idx) public owner {
// use remove by key and at methods
__remove(at(idx));
}
/// inheritdoc
function slice(uint32 start, uint32 finish) external view returns(address[] memory) {
// in case of invalid indexes specified
require(start != 0 && finish != 0 && start <= finish && finish <= __capacity, "Invalid slice indexes specified");
address[] memory result = new address[](finish - start + 1);
uint32 idx = 1; // index start from first node
// iterate over all fobll nodes from head to tail
address it = __head;
address end = __nodes[__tail].next;
while (it != end) {
// in case we pass finish break
if (idx > finish) {
break;
}
Node memory node = __nodes[it];
// in case we found right node
if (start <= idx && idx <= finish) {
result[idx - start] = node.self;
}
// update fobll iterator
it = node.next;
// update iteration break index
++idx;
}
return result;
}
/**
* @dev remove element from fobll by key, if elemnt already exists
* @dev update size constraints
* @param key element identifier
*/
function __remove(address key) private {
Node memory node = __nodes[key];
// in case node not exists
if (node.self == address(0)) {
return;
}
// in case removed node was head node
// declare next node as new head node
if (node.self == __head) {
__head = node.next;
}
// in case removed node was tail node
// declare prev node as new tail node
if (__tail == node.self) {
__tail = node.prev;
}
// in case removded prev node exists
// change old prev node next ptr to node next ptr
if (node.prev != address(0)) {
__nodes[node.prev].next = node.next;
}
// in case removded next node exists
// change old next node prev ptr to node prev ptr
if (node.next != address(0)) {
__nodes[node.next].prev = node.prev;
}
// update fobll size
--__size;
// clear node data
delete __nodes[key];
}
/**
* @dev place node into the fobll by order, correctly processed single item fobll and multi items fobll
* @param key address of new node
* @param value value of new node
*/
function __place(address key, uint256 value) private {
uint32 idx = 1; // index start from first node
// iterate over all fobll nodes from head to tail
address it = __head;
address end = __nodes[__tail].next;
do {
Node memory node = __nodes[it];
if (node.value >= value) {
// update fobll iterator
it = node.next;
// update iteration break index
++idx;
// skip between action
// while we not find right node
continue;
}
// in case fobll is already full
// and new node value is lower than min existed
// break from place method
if (idx > __capacity) {
return;
}
// add new node to the fobll before current node
__between(key, value, node.prev, node.self, false);
// in case placement done in middle of fobll
// and fobll size growth over capacity
// remove __tail element
if (__size > __capacity) {
__remove(__tail);
}
// break from place method
// as placement was done
return;
} while (it != end);
// in case of fobll lowest new node value
// append new node to fobll tail node
// add new node to the end of fobll
__between(key, value, __tail, address(0), true);
}
/**
* @dev create new node with address and value between prev address and next address
* @param key address of new node
* @param value value of new node
* @param prev ptr to prev node
* @param next prt to next node
* @param constraint flag that consider size constraint
*/
function __between(address key, uint256 value, address prev, address next, bool constraint) private {
// in case fobll is already full
// break from between method
if (constraint && __size >= __capacity) {
return;
}
// add new node to the fobll before next node and prev node
__nodes[key] = Node({
value: value,
self: key,
prev: prev,
next: next
});
// in case prev node is tail node
// declare new node as new tail node
if (prev == __tail) {
__tail = key;
}
// in case next node is head node
// declare new node as new head node
if (next == __head) {
__head = key;
}
// in case prev node exists
// change old prev node next ptr to new node
if (prev != address(0)) {
__nodes[prev].next = key;
}
// in case next node exists
// change old next node prev ptr to new node
if (next != address(0)) {
__nodes[next].prev = key;
}
// update fobll size
++__size;
}
/// @title size of fobll
uint32 private __size;
/// @title capacity of fobll
uint32 private __capacity;
/// @title inner node struct of fobll
struct Node {
/// @title node self value
uint256 value;
/// @title node self address
address self;
/// @title node next address
address next;
/// @title node prev address
address prev;
}
/// @title nodes mapping of fobll
mapping(address => Node) private __nodes;
/// @title head ptr of fobll
address private __head;
/// @title tail ptr of fobll
address private __tail;
}
| inheritdoc in case of invalid address specified iterate over all fobll nodes from head to tail in case we pass finish break update fobll iterator update iteration break index skip while we not find right node | function index(address key) external view returns(uint32) {
require(key != address(0), "Invalid index key specified");
address it = __head;
address end = __nodes[__tail].next;
while (it != end) {
if (idx > __capacity) {
break;
}
Node memory node = __nodes[it];
if (node.self != key) {
it = node.next;
++idx;
continue;
}
}
return 0;
}
| 5,441,787 | [
1,
10093,
316,
648,
434,
2057,
1758,
1269,
7401,
1879,
777,
284,
947,
2906,
2199,
628,
910,
358,
5798,
316,
648,
732,
1342,
4076,
898,
1089,
284,
947,
2906,
2775,
1089,
6532,
898,
770,
2488,
1323,
732,
486,
1104,
2145,
756,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
770,
12,
2867,
498,
13,
3903,
1476,
1135,
12,
11890,
1578,
13,
288,
203,
3639,
2583,
12,
856,
480,
1758,
12,
20,
3631,
315,
1941,
770,
498,
1269,
8863,
203,
203,
3639,
1758,
518,
273,
1001,
1978,
31,
203,
3639,
1758,
679,
273,
1001,
4690,
63,
972,
13101,
8009,
4285,
31,
203,
3639,
1323,
261,
305,
480,
679,
13,
288,
203,
5411,
309,
261,
3465,
405,
1001,
16017,
13,
288,
203,
7734,
898,
31,
203,
5411,
289,
203,
203,
5411,
2029,
3778,
756,
273,
1001,
4690,
63,
305,
15533,
203,
5411,
309,
261,
2159,
18,
2890,
480,
498,
13,
288,
203,
7734,
518,
273,
756,
18,
4285,
31,
203,
7734,
965,
3465,
31,
203,
7734,
1324,
31,
203,
5411,
289,
203,
203,
3639,
289,
203,
3639,
327,
374,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0xEd177746E5C5b7a321237dC900841491E10ACb25/sources/YANG.sol | uint256 DeveloperShare = _buyDevTax.add(_sellDevTax); | function swapBack(uint256 tAmount) private lockThatSwap {
uint256 totalShares = _totalBuyFee.add(_totalSellFee);
uint256 liquidityShare = _buyLPTax.add(_sellLPTax);
uint256 MarketingShare = _buyMarketTax.add(_sellMarketTax);
uint256 tokenForLp = tAmount.mul(liquidityShare).div(totalShares).div(2);
uint256 tokenForSwap = tAmount.sub(tokenForLp);
uint256 initialBalance = address(this).balance;
swapTokensToEth(tokenForSwap);
uint256 recievedBalance = address(this).balance.sub(initialBalance);
uint256 totalETHFee = totalShares.sub(liquidityShare.div(2));
uint256 amountETHLiquidity = recievedBalance.mul(liquidityShare).div(totalETHFee).div(2);
uint256 amountETHMarketing = recievedBalance.mul(MarketingShare).div(totalETHFee);
uint256 amountETHDeveloper = recievedBalance.sub(amountETHLiquidity).sub(amountETHMarketing);
if(amountETHMarketing > 0) {
payable(feeWallet).transfer(amountETHMarketing);
}
if(amountETHDeveloper > 0) {
payable(botFeeWallet).transfer(amountETHDeveloper);
}
if(amountETHLiquidity > 0 && tokenForLp > 0) {
addLiquidity(tokenForLp, amountETHLiquidity);
}
}
| 9,294,886 | [
1,
11890,
5034,
14526,
9535,
273,
389,
70,
9835,
8870,
7731,
18,
1289,
24899,
87,
1165,
8870,
7731,
1769,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
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,
7720,
2711,
12,
11890,
5034,
268,
6275,
13,
3238,
2176,
18163,
12521,
288,
203,
3639,
2254,
5034,
2078,
24051,
273,
389,
4963,
38,
9835,
14667,
18,
1289,
24899,
4963,
55,
1165,
14667,
1769,
203,
203,
3639,
2254,
5034,
4501,
372,
24237,
9535,
273,
389,
70,
9835,
48,
1856,
651,
18,
1289,
24899,
87,
1165,
48,
1856,
651,
1769,
203,
3639,
2254,
5034,
6622,
21747,
9535,
273,
389,
70,
9835,
3882,
278,
7731,
18,
1289,
24899,
87,
1165,
3882,
278,
7731,
1769,
203,
540,
203,
3639,
2254,
5034,
1147,
1290,
48,
84,
273,
268,
6275,
18,
16411,
12,
549,
372,
24237,
9535,
2934,
2892,
12,
4963,
24051,
2934,
2892,
12,
22,
1769,
203,
3639,
2254,
5034,
1147,
1290,
12521,
273,
268,
6275,
18,
1717,
12,
2316,
1290,
48,
84,
1769,
203,
203,
3639,
2254,
5034,
2172,
13937,
273,
225,
1758,
12,
2211,
2934,
12296,
31,
203,
3639,
7720,
5157,
774,
41,
451,
12,
2316,
1290,
12521,
1769,
203,
3639,
2254,
5034,
1950,
1385,
2155,
13937,
273,
225,
1758,
12,
2211,
2934,
12296,
18,
1717,
12,
6769,
13937,
1769,
203,
203,
3639,
2254,
5034,
2078,
1584,
44,
14667,
273,
2078,
24051,
18,
1717,
12,
549,
372,
24237,
9535,
18,
2892,
12,
22,
10019,
203,
203,
3639,
2254,
5034,
3844,
1584,
44,
48,
18988,
24237,
273,
1950,
1385,
2155,
13937,
18,
16411,
12,
549,
372,
24237,
9535,
2934,
2892,
12,
4963,
1584,
44,
14667,
2934,
2892,
12,
22,
1769,
203,
3639,
2254,
5034,
3844,
1584,
44,
3882,
21747,
273,
1950,
1385,
2155,
13937,
18,
16411,
2
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {ERC721} from "@solidstate/contracts/token/ERC721/ERC721.sol";
import {ERC721BaseStorage} from "@solidstate/contracts/token/ERC721/base/ERC721BaseStorage.sol";
import {OwnableInternal} from "@solidstate/contracts/access/OwnableInternal.sol";
import {VRFConsumerBase} from "@chainlink/contracts/src/v0.8/VRFConsumerBase.sol";
import {ChonkyGenomeLib} from "./lib/ChonkyGenomeLib.sol";
import {ChonkyMetadata} from "./ChonkyMetadata.sol";
import {ChonkyNFTStorage} from "./ChonkyNFTStorage.sol";
import {IChonkyNFT} from "./interface/IChonkyNFT.sol";
contract ChonkyNFT is IChonkyNFT, ERC721, VRFConsumerBase, OwnableInternal {
using ERC721BaseStorage for ERC721BaseStorage.Layout;
uint256 internal constant MAX_ELEMENTS = 7777;
// Price per unit if buying < AMOUNT_DISCOUNT_ONE
uint256 internal constant PRICE = 70 * 10**15;
// Price per unit if buying >= AMOUNT_DISCOUNT_ONE
uint256 internal constant PRICE_DISCOUNT_ONE = 65 * 10**15;
// Price per unit if buying MAX_AMOUNT
uint256 internal constant PRICE_DISCOUNT_MAX = 60 * 10**15;
uint256 internal constant AMOUNT_DISCOUNT_ONE = 10;
uint256 internal constant MAX_AMOUNT = 20;
uint256 internal constant RESERVED_AMOUNT = 16;
uint256 internal constant BITS_PER_GENOME = 58;
string internal constant CID =
"QmdafmnRuwqdnYGpVstF6raAqW64AD4i4maDAyvbeVDTGe";
// Chainlink VRF
bytes32 private immutable VRF_KEY_HASH;
uint256 private immutable VRF_FEE;
event CreateChonky(uint256 indexed id);
event RevealInitiated(bytes32 indexed requestId);
event Reveal(
uint256 indexed startId,
uint256 indexed endId,
uint256 indexed offset
);
constructor(
address _vrfCoordinator,
address _link,
bytes32 _vrfKeyHash,
uint256 _vrfFee
) VRFConsumerBase(_vrfCoordinator, _link) {
VRF_KEY_HASH = _vrfKeyHash;
VRF_FEE = _vrfFee;
}
function mintReserved(uint256 amount) external onlyOwner {
// Mint reserved chonky
for (uint256 i = 0; i < amount; i++) {
_mintChonky(msg.sender);
}
}
function setStartTimestamp(uint256 timestamp) external onlyOwner {
ChonkyNFTStorage.layout().startTimestamp = timestamp;
}
function reveal() external onlyOwner returns (bytes32 requestId) {
requestId = requestRandomness(VRF_KEY_HASH, VRF_FEE);
emit RevealInitiated(requestId);
}
function fulfillRandomness(bytes32, uint256 randomness) internal override {
ChonkyNFTStorage.Layout storage l = ChonkyNFTStorage.layout();
uint256 startId = _getRevealStartId();
require(startId < MAX_ELEMENTS, "Reveal already completed");
require(l.currentId >= startId, "No new mint to reveal");
uint256 offset = (randomness % (MAX_ELEMENTS - RESERVED_AMOUNT));
_reveal(l, startId, offset);
}
function _reveal(
ChonkyNFTStorage.Layout storage l,
uint256 startId,
uint256 baseOffset
) internal {
// If first reveal, we dont need to check for range collisions
if (l.revealRanges.length == 0) {
l.revealRanges.push(
ChonkyNFTStorage.RevealRange(startId, l.currentId, baseOffset)
);
emit Reveal(startId, l.currentId, baseOffset);
return;
}
uint256 offset = _checkStartRangeCollision(l, startId, baseOffset);
uint256 endId = _checkEndRangeCollision(
l,
startId,
offset,
l.currentId
);
l.revealRanges.push(
ChonkyNFTStorage.RevealRange(startId, endId, offset)
);
emit Reveal(startId, endId, offset);
if (endId != l.currentId) {
// If there was a collision, we calculate the next range
_reveal(l, endId + 1, baseOffset);
}
}
function _checkStartRangeCollision(
ChonkyNFTStorage.Layout storage l,
uint256 _startId,
uint256 _initialOffset
) internal returns (uint256 offset) {
offset = _initialOffset;
uint256 newRangeStartId = _applyOffset(_startId, _initialOffset);
for (uint256 i = 0; i < l.revealRanges.length; i++) {
ChonkyNFTStorage.RevealRange memory range = l.revealRanges[i];
uint256 rangeStart = _applyOffset(range.startId, range.offset);
uint256 rangeEnd = _applyOffset(range.endId, range.offset);
if (rangeStart > rangeEnd) {
if (newRangeStartId <= rangeEnd) {
offset += (rangeEnd - newRangeStartId) + 1;
return _checkStartRangeCollision(l, _startId, offset);
} else if (
newRangeStartId >= rangeStart &&
newRangeStartId <= MAX_ELEMENTS
) {
offset +=
(rangeEnd - RESERVED_AMOUNT) +
(MAX_ELEMENTS - newRangeStartId) +
1;
return _checkStartRangeCollision(l, _startId, offset);
}
} else {
if (
newRangeStartId >= rangeStart && newRangeStartId <= rangeEnd
) {
offset += (rangeEnd - newRangeStartId) + 1;
return _checkStartRangeCollision(l, _startId, offset);
}
}
}
return _initialOffset;
}
function _checkEndRangeCollision(
ChonkyNFTStorage.Layout storage l,
uint256 _startId,
uint256 _offset,
uint256 _initialEndId
) internal view returns (uint256 endId) {
uint256 startIdWithOffset = _applyOffset(_startId, _offset);
uint256 endIdWithOffset = _applyOffset(_initialEndId, _offset);
uint256 collisionDistance;
for (uint256 i = 0; i < l.revealRanges.length; i++) {
ChonkyNFTStorage.RevealRange memory range = l.revealRanges[i];
uint256 rangeStart = _applyOffset(range.startId, range.offset);
uint256 distance;
if (endIdWithOffset < startIdWithOffset) {
if (
rangeStart > startIdWithOffset && rangeStart <= MAX_ELEMENTS
) {
distance =
(endIdWithOffset - RESERVED_AMOUNT) +
(MAX_ELEMENTS - rangeStart) +
1;
} else if (rangeStart < endIdWithOffset) {
distance = (endIdWithOffset - rangeStart) + 1;
}
} else {
if (
rangeStart > startIdWithOffset &&
rangeStart <= endIdWithOffset
) {
distance = (endIdWithOffset - rangeStart) + 1;
}
}
if (distance > 0 && distance > collisionDistance) {
collisionDistance = distance;
}
}
if (collisionDistance == 0) return _initialEndId;
return _initialEndId - collisionDistance;
}
function _applyOffset(uint256 _tokenId, uint256 _offset)
internal
pure
returns (uint256)
{
return
((_tokenId + _offset) % (MAX_ELEMENTS - RESERVED_AMOUNT)) +
RESERVED_AMOUNT;
}
function _getRevealStartId() internal view returns (uint256) {
ChonkyNFTStorage.Layout storage l = ChonkyNFTStorage.layout();
uint256 rangesAmount = l.revealRanges.length;
if (rangesAmount == 0) return RESERVED_AMOUNT;
return l.revealRanges[rangesAmount - 1].endId + 1;
}
function mint() external payable {
ChonkyNFTStorage.Layout storage l = ChonkyNFTStorage.layout();
require(
l.startTimestamp > 0 && block.timestamp > l.startTimestamp,
"Minting not started"
);
require(l.currentId < MAX_ELEMENTS, "Sale ended");
require(msg.value <= MAX_AMOUNT * PRICE_DISCOUNT_MAX, "> Max amount");
uint256 count;
if (msg.value >= MAX_AMOUNT * PRICE_DISCOUNT_MAX) {
count = MAX_AMOUNT;
} else if (msg.value >= PRICE_DISCOUNT_ONE * AMOUNT_DISCOUNT_ONE) {
count = msg.value / PRICE_DISCOUNT_ONE;
} else {
count = msg.value / PRICE;
}
require(l.currentId + count <= MAX_ELEMENTS, "Max limit");
for (uint256 i = 0; i < count; i++) {
_mintChonky(msg.sender);
}
}
function _mintChonky(address _to) private {
ChonkyNFTStorage.Layout storage l = ChonkyNFTStorage.layout();
uint256 id = l.currentId;
_safeMint(_to, id);
l.currentId += 1;
emit CreateChonky(id);
}
function withdraw(address[] memory _addresses, uint256[] memory _amounts)
public
onlyOwner
{
for (uint256 i = 0; i < _addresses.length; i++) {
_withdraw(_addresses[i], _amounts[i]);
}
}
function parseGenome(uint256 _genome)
external
pure
returns (uint256[12] memory result)
{
return ChonkyGenomeLib.parseGenome(_genome);
}
function formatGenome(uint256[12] memory _attributes)
external
pure
returns (uint256 genome)
{
return ChonkyGenomeLib.formatGenome(_attributes);
}
function getGenome(uint256 _id) external view returns (uint256) {
return _getGenome(_id);
}
function _getGenome(uint256 _id) internal view returns (uint256) {
ChonkyNFTStorage.Layout storage l = ChonkyNFTStorage.layout();
uint256 startBit = BITS_PER_GENOME * _id;
uint256 genomeIndex = startBit / 256;
uint256 genome = l.genomes[genomeIndex] >> (startBit % 256);
if ((startBit % 256) + BITS_PER_GENOME <= 256) {
uint256 mask = 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff >>
(256 - BITS_PER_GENOME);
genome &= mask;
} else {
uint256 remainingBits = 256 - (startBit % 256);
uint256 missingBits = BITS_PER_GENOME - remainingBits;
uint256 genomeNext = (l.genomes[genomeIndex + 1] <<
(256 - missingBits)) >> (256 - missingBits - remainingBits);
genome += genomeNext;
}
return genome;
}
function addPackedGenomes(uint256[] memory _genomes) external onlyOwner {
ChonkyNFTStorage.Layout storage l = ChonkyNFTStorage.layout();
for (uint256 i = 0; i < _genomes.length; i++) {
l.genomes.push(_genomes[i]);
}
}
function setPackedGenomes(uint256[] memory _ids, uint256[] memory _genomes)
external
onlyOwner
{
require(_ids.length == _genomes.length, "Invalid arrays length");
ChonkyNFTStorage.Layout storage l = ChonkyNFTStorage.layout();
for (uint256 i = 0; i < _genomes.length; i++) {
l.genomes[_ids[i]] = _genomes[i];
}
}
function _getGenomeId(uint256 _tokenId) internal view returns (uint256) {
ChonkyNFTStorage.Layout storage l = ChonkyNFTStorage.layout();
// Honoraries
if (_tokenId < RESERVED_AMOUNT) return _tokenId;
for (uint256 i = 0; i < l.revealRanges.length; i++) {
if (_tokenId <= l.revealRanges[i].endId) {
return _applyOffset(_tokenId, l.revealRanges[i].offset);
}
}
// 10000 = Unrevealed
return 10000;
}
function tokenURI(uint256 _tokenId)
public
view
override
returns (string memory)
{
require(
ERC721BaseStorage.layout().exists(_tokenId),
"ERC721Metadata: URI query for nonexistent token"
);
ChonkyNFTStorage.Layout storage l = ChonkyNFTStorage.layout();
uint256 genomeId = _getGenomeId(_tokenId);
return
ChonkyMetadata(l.chonkyMetadata).buildTokenURI(
_tokenId,
genomeId,
genomeId == 10000 ? 0 : _getGenome(genomeId),
CID,
l.chonkyAttributes,
l.chonkySet
);
}
function _withdraw(address _address, uint256 _amount) private {
(bool success, ) = _address.call{value: _amount}("");
require(success, "Transfer failed.");
}
function getChonkyAttributesAddress() external view returns (address) {
return ChonkyNFTStorage.layout().chonkyAttributes;
}
function getChonkyMetadataAddress() external view returns (address) {
return ChonkyNFTStorage.layout().chonkyMetadata;
}
function getChonkySetAddress() external view returns (address) {
return ChonkyNFTStorage.layout().chonkySet;
}
function getCID() external pure returns (string memory) {
return CID;
}
function getStartTimestamp() external view returns (uint256) {
return ChonkyNFTStorage.layout().startTimestamp;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import { ERC721Base, ERC721BaseInternal } from './base/ERC721Base.sol';
import { ERC721Enumerable } from './enumerable/ERC721Enumerable.sol';
import { ERC721Metadata } from './metadata/ERC721Metadata.sol';
import { ERC165 } from '../../introspection/ERC165.sol';
/**
* @notice SolidState ERC721 implementation, including recommended extensions
*/
abstract contract ERC721 is
ERC721Base,
ERC721Enumerable,
ERC721Metadata,
ERC165
{
/**
* @notice ERC721 hook: revert if value is included in external approve function call
* @inheritdoc ERC721BaseInternal
*/
function _handleApproveMessageValue(
address operator,
uint256 tokenId,
uint256 value
) internal virtual override {
require(value == 0, 'ERC721: payable approve calls not supported');
super._handleApproveMessageValue(operator, tokenId, value);
}
/**
* @notice ERC721 hook: revert if value is included in external transfer function call
* @inheritdoc ERC721BaseInternal
*/
function _handleTransferMessageValue(
address from,
address to,
uint256 tokenId,
uint256 value
) internal virtual override {
require(value == 0, 'ERC721: payable transfer calls not supported');
super._handleTransferMessageValue(from, to, tokenId, value);
}
/**
* @inheritdoc ERC721BaseInternal
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override(ERC721BaseInternal, ERC721Metadata) {
super._beforeTokenTransfer(from, to, tokenId);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import { EnumerableMap } from '../../../utils/EnumerableMap.sol';
import { EnumerableSet } from '../../../utils/EnumerableSet.sol';
library ERC721BaseStorage {
using EnumerableSet for EnumerableSet.UintSet;
using EnumerableMap for EnumerableMap.UintToAddressMap;
bytes32 internal constant STORAGE_SLOT =
keccak256('solidstate.contracts.storage.ERC721Base');
struct Layout {
EnumerableMap.UintToAddressMap tokenOwners;
mapping(address => EnumerableSet.UintSet) holderTokens;
mapping(uint256 => address) tokenApprovals;
mapping(address => mapping(address => bool)) operatorApprovals;
}
function layout() internal pure returns (Layout storage l) {
bytes32 slot = STORAGE_SLOT;
assembly {
l.slot := slot
}
}
function exists(Layout storage l, uint256 tokenId)
internal
view
returns (bool)
{
return l.tokenOwners.contains(tokenId);
}
function totalSupply(Layout storage l) internal view returns (uint256) {
return l.tokenOwners.length();
}
function tokenOfOwnerByIndex(
Layout storage l,
address owner,
uint256 index
) internal view returns (uint256) {
return l.holderTokens[owner].at(index);
}
function tokenByIndex(Layout storage l, uint256 index)
internal
view
returns (uint256)
{
(uint256 tokenId, ) = l.tokenOwners.at(index);
return tokenId;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import { OwnableStorage } from './OwnableStorage.sol';
abstract contract OwnableInternal {
using OwnableStorage for OwnableStorage.Layout;
modifier onlyOwner() {
require(
msg.sender == OwnableStorage.layout().owner,
'Ownable: sender must be owner'
);
_;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./interfaces/LinkTokenInterface.sol";
import "./VRFRequestIDBase.sol";
/** ****************************************************************************
* @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);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
library ChonkyGenomeLib {
function parseGenome(uint256 _genome)
internal
pure
returns (uint256[12] memory result)
{
assembly {
mstore(result, sub(_genome, shl(5, shr(5, _genome))))
mstore(
add(result, 0x20),
sub(shr(5, _genome), shl(3, shr(8, _genome)))
)
mstore(
add(result, 0x40),
sub(shr(8, _genome), shl(4, shr(12, _genome)))
)
mstore(
add(result, 0x60),
sub(shr(12, _genome), shl(5, shr(17, _genome)))
)
mstore(
add(result, 0x80),
sub(shr(17, _genome), shl(4, shr(21, _genome)))
)
mstore(
add(result, 0xA0),
sub(shr(21, _genome), shl(4, shr(25, _genome)))
)
mstore(
add(result, 0xC0),
sub(shr(25, _genome), shl(7, shr(32, _genome)))
)
mstore(
add(result, 0xE0),
sub(shr(32, _genome), shl(6, shr(38, _genome)))
)
mstore(
add(result, 0x100),
sub(shr(38, _genome), shl(6, shr(44, _genome)))
)
mstore(
add(result, 0x120),
sub(shr(44, _genome), shl(7, shr(51, _genome)))
)
mstore(
add(result, 0x140),
sub(shr(51, _genome), shl(3, shr(54, _genome)))
)
mstore(add(result, 0x160), shr(54, _genome))
}
}
function formatGenome(uint256[12] memory _attributes)
internal
pure
returns (uint256 genome)
{
genome =
(_attributes[0]) +
(_attributes[1] << 5) +
(_attributes[2] << 8) +
(_attributes[3] << 12) +
(_attributes[4] << 17) +
(_attributes[5] << 21) +
(_attributes[6] << 25) +
(_attributes[7] << 32) +
(_attributes[8] << 38) +
(_attributes[9] << 44) +
(_attributes[10] << 51) +
(_attributes[11] << 54);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {UintUtils} from "@solidstate/contracts/utils/UintUtils.sol";
import {Base64} from "base64-sol/base64.sol";
import {ChonkyGenomeLib} from "./lib/ChonkyGenomeLib.sol";
import {ChonkyAttributes} from "./ChonkyAttributes.sol";
import {ChonkySet} from "./ChonkySet.sol";
import {IChonkyMetadata} from "./interface/IChonkyMetadata.sol";
import {IChonkySet} from "./interface/IChonkySet.sol";
contract ChonkyMetadata is IChonkyMetadata {
using UintUtils for uint256;
function buildTokenURI(
uint256 id,
uint256 genomeId,
uint256 genome,
string memory CID,
address chonkyAttributes,
address chonkySet
) public pure returns (string memory) {
string
memory description = "A collection of 7777 mischievous Chonky's ready to wreak havoc on the ETH blockchain.";
string memory attributes = _buildAttributes(
genome,
chonkyAttributes,
chonkySet
);
return
string(
abi.encodePacked(
"data:application/json;base64,",
Base64.encode(
bytes(
abi.encodePacked(
"{",
'"image":"ipfs://',
CID,
"/",
_buildPaddedID(genomeId),
'.png",',
'"description":"',
description,
'",',
'"name":"Chonky',
"'s #",
_buildPaddedID(id),
'",',
attributes,
"}"
)
)
)
)
);
}
function _buildPaddedID(uint256 id) internal pure returns (string memory) {
if (id == 0) return "0000";
if (id < 10) return string(abi.encodePacked("000", id.toString()));
if (id < 100) return string(abi.encodePacked("00", id.toString()));
if (id < 1000) return string(abi.encodePacked("0", id.toString()));
return id.toString();
}
////
function _getBGBase(uint256 id) internal pure returns (string memory) {
if (id == 1) return "Aqua";
if (id == 2) return "Black";
if (id == 3) return "Brown";
if (id == 4) return "Dark Purple";
if (id == 5) return "Dark Red";
if (id == 6) return "Gold";
if (id == 7) return "Green";
if (id == 8) return "Green Apple";
if (id == 9) return "Grey";
if (id == 10) return "Ice Blue";
if (id == 11) return "Kaki";
if (id == 12) return "Orange";
if (id == 13) return "Pink";
if (id == 14) return "Purple";
if (id == 15) return "Rainbow";
if (id == 16) return "Red";
if (id == 17) return "Sky Blue";
if (id == 18) return "Yellow";
return "";
}
function _getBGRare(uint256 id) internal pure returns (string memory) {
if (id == 1) return "HamHam";
if (id == 2) return "Japan";
if (id == 3) return "Skulls";
if (id == 4) return "Stars";
return "";
}
function _getWings(uint256 id) internal pure returns (string memory) {
if (id == 1) return "Angel";
if (id == 2) return "Bat";
if (id == 3) return "Bee";
if (id == 4) return "Crystal";
if (id == 5) return "Devil";
if (id == 6) return "Dragon";
if (id == 7) return "Fairy";
if (id == 8) return "Plant";
if (id == 9) return "Robot";
return "";
}
function _getSkin(uint256 id) internal pure returns (string memory) {
if (id == 1) return "Almond";
if (id == 2) return "Aqua";
if (id == 3) return "Blue";
if (id == 4) return "Brown";
if (id == 5) return "Cream";
if (id == 6) return "Dark";
if (id == 7) return "Dark Blue";
if (id == 8) return "Gold";
if (id == 9) return "Green";
if (id == 10) return "Grey";
if (id == 11) return "Ice";
if (id == 12) return "Indigo";
if (id == 13) return "Light Brown";
if (id == 14) return "Light Purple";
if (id == 15) return "Neon Blue";
if (id == 16) return "Orange";
if (id == 17) return "Pink";
if (id == 18) return "Purple";
if (id == 19) return "Rose White";
if (id == 20) return "Salmon";
if (id == 21) return "Skye Blue";
if (id == 22) return "Special Red";
if (id == 23) return "White";
if (id == 24) return "Yellow";
return "";
}
function _getPattern(uint256 id) internal pure returns (string memory) {
if (id == 1) return "3 Dots";
if (id == 2) return "3 Triangles";
if (id == 3) return "Corner";
if (id == 4) return "Dalmatian";
if (id == 5) return "Half";
if (id == 6) return "Tiger Stripes";
if (id == 7) return "Triangle";
if (id == 8) return "White Reversed V";
if (id == 9) return "Zombie";
return "";
}
function _getPaint(uint256 id) internal pure returns (string memory) {
if (id == 1) return "Beard";
if (id == 2) return "Board";
if (id == 3) return "Earrings";
if (id == 4) return "Face Tattoo";
if (id == 5) return "Happy Cheeks";
if (id == 6) return "Pink Star";
if (id == 7) return "Purple Star";
if (id == 8) return "Scar";
return "";
}
function _getBody(uint256 id) internal pure returns (string memory) {
if (id == 1) return "Retro Shirt";
if (id == 2) return "Angel Wings";
if (id == 3) return "Aqua Monster";
if (id == 4) return "Astronaut";
if (id == 5) return "Bag";
if (id == 6) return "Baron Samedi";
if (id == 7) return "Bee";
if (id == 8) return "Black Samurai";
if (id == 9) return "Black Wizard";
if (id == 10) return "Blue Football";
if (id == 11) return "Blue Parka";
if (id == 12) return "Blue Kimono";
if (id == 13) return "Blue Hoodie";
if (id == 14) return "Blue Wizard";
if (id == 15) return "Jester";
if (id == 16) return "Bubble Tea";
if (id == 17) return "Captain";
if (id == 18) return "Caveman";
if (id == 19) return "Chef";
if (id == 20) return "Chinese Shirt";
if (id == 21) return "Cloth Monster";
if (id == 22) return "Color Shirt";
if (id == 23) return "Cowboy Shirt";
if (id == 24) return "Cyber Assassin";
if (id == 25) return "Devil Wings";
if (id == 26) return "Scuba";
if (id == 27) return "Doreamon";
if (id == 28) return "Dracula";
if (id == 29) return "Gold Chain";
if (id == 30) return "Green Cyber";
if (id == 31) return "Green Parka";
if (id == 32) return "Green Kimono";
if (id == 33) return "Green Hoodie";
if (id == 34) return "Hamsterdam Shirt";
if (id == 35) return "Hazard";
if (id == 36) return "Hiding Hamster";
if (id == 37) return "Pink Punk Girl";
if (id == 38) return "Japanese Worker";
if (id == 39) return "King";
if (id == 40) return "Leather Jacket";
if (id == 41) return "Leaves";
if (id == 42) return "Lobster";
if (id == 43) return "Luffy";
if (id == 44) return "Magenta Cyber";
if (id == 45) return "Sailor";
if (id == 46) return "Mario Pipe";
if (id == 47) return "Mommy";
if (id == 48) return "Ninja";
if (id == 49) return "Old Grandma";
if (id == 50) return "Orange Jumpsuit";
if (id == 51) return "Chili";
if (id == 52) return "Chili Fire";
if (id == 53) return "Pharaoh";
if (id == 54) return "Pink Football";
if (id == 55) return "Pink Ruff";
if (id == 56) return "Pink Jumpsuit";
if (id == 57) return "Pink Kimono";
if (id == 58) return "Pink Polo";
if (id == 59) return "Pirate";
if (id == 60) return "Plague Doctor";
if (id == 61) return "Poncho";
if (id == 62) return "Purple Cyber";
if (id == 63) return "Purple Polo";
if (id == 64) return "Mystery Hoodie";
if (id == 65) return "Rainbow Snake";
if (id == 66) return "Red Ruff";
if (id == 67) return "Red Punk Girl";
if (id == 68) return "Red Samurai";
if (id == 69) return "Referee";
if (id == 70) return "Robotbod";
if (id == 71) return "Robot Cyber";
if (id == 72) return "Rocker";
if (id == 73) return "Roman Legionary";
if (id == 74) return "Safari";
if (id == 75) return "Scout";
if (id == 76) return "Sherlock";
if (id == 77) return "Shirt";
if (id == 78) return "Snow Coat";
if (id == 79) return "Sparta";
if (id == 80) return "Steampunk";
if (id == 81) return "Suit";
if (id == 82) return "Tie";
if (id == 83) return "Tire";
if (id == 84) return "Toga";
if (id == 85) return "Tron";
if (id == 86) return "Valkyrie";
if (id == 87) return "Viking";
if (id == 88) return "Wereham";
if (id == 89) return "White Cloak";
if (id == 90) return "Yellow Jumpsuit";
if (id == 91) return "Zombie";
return "";
}
function _getMouth(uint256 id) internal pure returns (string memory) {
if (id == 1) return "Black Gas Mask Ninja";
if (id == 2) return "Black Ninja Mask";
if (id == 3) return "Shocked";
if (id == 4) return "Creepy";
if (id == 5) return "=D";
if (id == 6) return "Drawing";
if (id == 7) return "Duck";
if (id == 8) return "Elegant Moustache";
if (id == 9) return "Fire";
if (id == 10) return "Gold Teeth";
if (id == 11) return "Grey Futuristic Gas Mask";
if (id == 12) return "Happy Open";
if (id == 13) return "Goatee";
if (id == 14) return "Honey";
if (id == 15) return "Jack-O-Lantern";
if (id == 16) return "Lipstick";
if (id == 17) return "Little Moustache";
if (id == 18) return "Luffy Smile";
if (id == 19) return "Sanitary Mask";
if (id == 20) return "Robot Mask";
if (id == 21) return "Mega Happy";
if (id == 22) return "Mega Tongue Out";
if (id == 23) return "Meh";
if (id == 24) return "Mexican Moustache";
if (id == 25) return "Monster";
if (id == 26) return "Moustache";
if (id == 27) return "Drunk";
if (id == 28) return "Fake Moustache";
if (id == 29) return "Full";
if (id == 30) return "Piece";
if (id == 31) return "Stretch";
if (id == 32) return "Ninja";
if (id == 33) return "Normal";
if (id == 34) return "Ohhhh";
if (id == 35) return "Chili";
if (id == 36) return "Purple Futuristic Gas Mask";
if (id == 37) return "Red Gas Mask Ninja";
if (id == 38) return "Red Ninja Mask";
if (id == 39) return "Robot Mouth";
if (id == 40) return "Scream";
if (id == 41) return "Cigarette";
if (id == 42) return "Smoking Pipe";
if (id == 43) return "Square";
if (id == 44) return "Steampunk";
if (id == 45) return "Stitch";
if (id == 46) return "Super Sad";
if (id == 47) return "Thick Moustache";
if (id == 48) return "Tongue";
if (id == 49) return "Tongue Out";
if (id == 50) return "Triangle";
if (id == 51) return "Vampire";
if (id == 52) return "Wave";
if (id == 53) return "What";
if (id == 54) return "YKWIM";
return "";
}
function _getEyes(uint256 id) internal pure returns (string memory) {
if (id == 1) return "^_^";
if (id == 2) return ">_<";
if (id == 3) return "=_=";
if (id == 4) return "3D";
if (id == 5) return "Angry";
if (id == 6) return "Button";
if (id == 7) return "Confused";
if (id == 8) return "Crazy";
if (id == 9) return "Cute";
if (id == 10) return "Cyber Glasses";
if (id == 11) return "Cyclops";
if (id == 12) return "Depressed";
if (id == 13) return "Determined";
if (id == 14) return "Diving Mask";
if (id == 15) return "Drawing";
if (id == 16) return "Morty";
if (id == 17) return "Eyepatch";
if (id == 18) return "Fake Moustache";
if (id == 19) return "Flower Glasses";
if (id == 20) return "Frozen";
if (id == 21) return "Furious";
if (id == 22) return "Gengar";
if (id == 23) return "Glasses Depressed";
if (id == 24) return "Goku";
if (id == 25) return "Green Underwear";
if (id == 26) return "Hippie";
if (id == 27) return "Kawaii";
if (id == 28) return "Line Glasses";
if (id == 29) return "Looking Up";
if (id == 30) return "Looking Up Happy";
if (id == 31) return "Mini Sunglasses";
if (id == 32) return "Monocle";
if (id == 33) return "Monster";
if (id == 34) return "Ninja";
if (id == 35) return "Normal";
if (id == 36) return "Not Impressed";
if (id == 37) return "o_o";
if (id == 38) return "Orange Underwear";
if (id == 39) return "Pink Star Sunglasses";
if (id == 40) return "Pissed";
if (id == 41) return "Pixel Glasses";
if (id == 42) return "Plague Doctor Mask";
if (id == 43) return "Proud";
if (id == 44) return "Raccoon";
if (id == 45) return "Red Dot";
if (id == 46) return "Red Star Sunglasses";
if (id == 47) return "Robot Eyes";
if (id == 48) return "Scared Eyes";
if (id == 49) return "Snorkel";
if (id == 50) return "Serious Japan";
if (id == 51) return "Seriously";
if (id == 52) return "Star";
if (id == 53) return "Steampunk Glasses";
if (id == 54) return "Sunglasses";
if (id == 55) return "Sunglasses Triangle";
if (id == 56) return "Surprised";
if (id == 57) return "Thick Eyebrows";
if (id == 58) return "Troubled";
if (id == 59) return "UniBrow";
if (id == 60) return "Weird";
if (id == 61) return "X_X";
return "";
}
function _getLostKing(uint256 _id) internal pure returns (string memory) {
if (_id == 1) return "The Glitch King";
if (_id == 2) return "The Gummy King";
if (_id == 3) return "King Diamond";
if (_id == 4) return "The King of Gold";
if (_id == 5) return "King Unicorn";
if (_id == 6) return "The Last King";
if (_id == 7) return "The Monkey King";
return "";
}
function _getHonorary(uint256 id) internal pure returns (string memory) {
if (id == 1) return "Crunchies";
if (id == 2) return "Chuckle";
if (id == 3) return "ChainLinkGod";
if (id == 4) return "Crypt0n1c";
if (id == 5) return "Bigdham";
if (id == 6) return "Cyclopeape";
if (id == 7) return "Elmo";
if (id == 8) return "Caustik";
if (id == 9) return "Churby";
if (id == 10) return "Chonko";
if (id == 11) return "Hamham";
if (id == 12) return "Icebergy";
if (id == 13) return "IronHam";
if (id == 14) return "RatWell";
if (id == 15) return "VangogHam";
if (id == 16) return "Boneham";
return "";
}
function _getHat(uint256 id) internal pure returns (string memory) {
if (id == 1) return "Retro";
if (id == 2) return "Aqua Monster";
if (id == 3) return "Astronaut";
if (id == 4) return "Baby Hamster";
if (id == 5) return "Baron Samedi";
if (id == 6) return "Bear Skin";
if (id == 7) return "Bee";
if (id == 8) return "Beanie";
if (id == 9) return "Beret";
if (id == 10) return "Biker Helmet";
if (id == 11) return "Black Afro";
if (id == 12) return "Black Hair JB";
if (id == 13) return "Black Kabuki Mask";
if (id == 14) return "Black Kabuto";
if (id == 15) return "Black Magician";
if (id == 16) return "Black Toupee";
if (id == 17) return "Bolts";
if (id == 18) return "Jester";
if (id == 19) return "Brain";
if (id == 20) return "Brown Hair JB";
if (id == 21) return "Candle";
if (id == 22) return "Captain";
if (id == 23) return "Cheese";
if (id == 24) return "Chef";
if (id == 25) return "Cloth Monster";
if (id == 26) return "Cone";
if (id == 27) return "Cowboy";
if (id == 28) return "Crown";
if (id == 29) return "Devil Horns";
if (id == 30) return "Dracula";
if (id == 31) return "Duck";
if (id == 32) return "Elvis";
if (id == 33) return "Fish";
if (id == 34) return "Fan";
if (id == 35) return "Fire";
if (id == 36) return "Fluffy Beanie";
if (id == 37) return "Pigskin";
if (id == 38) return "Futuristic Crown";
if (id == 39) return "Golden Horns";
if (id == 40) return "Green Fire";
if (id == 41) return "Green Knot";
if (id == 42) return "Green Punk";
if (id == 43) return "Green Visor";
if (id == 44) return "Halo";
if (id == 45) return "Headband";
if (id == 46) return "Ice";
if (id == 47) return "Injury";
if (id == 48) return "Kabuto";
if (id == 49) return "Leaf";
if (id == 50) return "Lion Head";
if (id == 51) return "Long Hair Front";
if (id == 52) return "Magician";
if (id == 53) return "Mario Flower";
if (id == 54) return "Mini Cap";
if (id == 55) return "Ninja Band";
if (id == 56) return "Mushroom";
if (id == 57) return "Ninja";
if (id == 58) return "Noodle Cup";
if (id == 59) return "Octopus";
if (id == 60) return "Old Lady";
if (id == 61) return "Pancakes";
if (id == 62) return "Paper Hat";
if (id == 63) return "Pharaoh";
if (id == 64) return "Pink Exploding Hair";
if (id == 65) return "Pink Hair Girl";
if (id == 66) return "Pink Mini Cap";
if (id == 67) return "Pink Punk";
if (id == 68) return "Pink Visor";
if (id == 69) return "Pirate";
if (id == 70) return "Plague Doctor";
if (id == 71) return "Plant";
if (id == 72) return "Punk Helmet";
if (id == 73) return "Purple Mini Cap";
if (id == 74) return "Purple Top Hat";
if (id == 75) return "Rainbow Afro";
if (id == 76) return "Rainbow Ice Cream";
if (id == 77) return "Red Black Hair Girl";
if (id == 78) return "Red Knot";
if (id == 79) return "Red Punk";
if (id == 80) return "Red Top Hat";
if (id == 81) return "Robot Head";
if (id == 82) return "Roman Legionary";
if (id == 83) return "Safari";
if (id == 84) return "Sherlock";
if (id == 85) return "Sombrero";
if (id == 86) return "Sparta";
if (id == 87) return "Steampunk";
if (id == 88) return "Straw";
if (id == 89) return "Straw Hat";
if (id == 90) return "Teapot";
if (id == 91) return "Tin Hat";
if (id == 92) return "Toupee";
if (id == 93) return "Valkyrie";
if (id == 94) return "Viking";
if (id == 95) return "White Kabuki Mask";
if (id == 96) return "Yellow Exploding Hair";
return "";
}
////
function _buildAttributes(
uint256 genome,
address chonkyAttributes,
address chonkySet
) internal pure returns (string memory result) {
uint256[12] memory attributes = ChonkyGenomeLib.parseGenome(genome);
bytes memory buffer = abi.encodePacked(
'"attributes":[',
'{"trait_type":"Background",',
'"value":"',
_getBGBase(attributes[0]),
'"}'
);
if (attributes[1] > 0) {
buffer = abi.encodePacked(
buffer,
', {"trait_type":"Rare Background",',
'"value":"',
_getBGRare(attributes[1]),
'"}'
);
}
if (attributes[2] > 0) {
buffer = abi.encodePacked(
buffer,
',{"trait_type":"Wings",',
'"value":"',
_getWings(attributes[2]),
'"}'
);
}
if (attributes[3] > 0) {
buffer = abi.encodePacked(
buffer,
',{"trait_type":"Skin",',
'"value":"',
_getSkin(attributes[3]),
'"}'
);
}
if (attributes[4] > 0) {
buffer = abi.encodePacked(
buffer,
',{"trait_type":"Pattern",',
'"value":"',
_getPattern(attributes[4]),
'"}'
);
}
if (attributes[5] > 0) {
buffer = abi.encodePacked(
buffer,
',{"trait_type":"Paint",',
'"value":"',
_getPaint(attributes[5]),
'"}'
);
}
if (attributes[6] > 0) {
buffer = abi.encodePacked(
buffer,
',{"trait_type":"Body",',
'"value":"',
_getBody(attributes[6]),
'"}'
);
}
if (attributes[7] > 0) {
buffer = abi.encodePacked(
buffer,
',{"trait_type":"Mouth",',
'"value":"',
_getMouth(attributes[7]),
'"}'
);
}
if (attributes[8] > 0) {
buffer = abi.encodePacked(
buffer,
',{"trait_type":"Eyes",',
'"value":"',
_getEyes(attributes[8]),
'"}'
);
}
if (attributes[9] > 0) {
buffer = abi.encodePacked(
buffer,
',{"trait_type":"Hat",',
'"value":"',
_getHat(attributes[9]),
'"}'
);
}
if (attributes[10] > 0) {
buffer = abi.encodePacked(
buffer,
',{"trait_type":"Lost King",',
'"value":"',
_getLostKing(attributes[10]),
'"}'
);
}
if (attributes[11] > 0) {
buffer = abi.encodePacked(
buffer,
',{"trait_type":"Honorary",',
'"value":"',
_getHonorary(attributes[11]),
'"}'
);
}
uint256 setId = IChonkySet(chonkySet).getSetId(genome);
if (setId > 0) {
buffer = abi.encodePacked(
buffer,
',{"trait_type":"Full Set",',
'"value":"',
IChonkySet(chonkySet).getSetFromId(setId),
'"}'
);
}
uint256[4] memory attributeValues = ChonkyAttributes(chonkyAttributes)
.getAttributeValues(attributes, setId);
buffer = abi.encodePacked(
buffer,
',{"trait_type":"Brain",',
'"value":',
attributeValues[0].toString(),
"}"
);
buffer = abi.encodePacked(
buffer,
',{"trait_type":"Cute",',
'"value":',
attributeValues[1].toString(),
"}"
);
buffer = abi.encodePacked(
buffer,
',{"trait_type":"Power",',
'"value":',
attributeValues[2].toString(),
"}"
);
buffer = abi.encodePacked(
buffer,
',{"trait_type":"Wicked",',
'"value":',
attributeValues[3].toString(),
"}"
);
return string(abi.encodePacked(buffer, "]"));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {EnumerableSet} from "@solidstate/contracts/utils/EnumerableSet.sol";
library ChonkyNFTStorage {
bytes32 internal constant STORAGE_SLOT =
keccak256("chonky.contracts.storage.ChonkyNFT");
struct RevealRange {
uint256 startId;
uint256 endId;
uint256 offset; // Offset to apply for this interval
}
struct Layout {
address implementation;
uint256 currentId;
uint256[] genomes;
// Offset IDs to randomize distribution when revealing
uint256 _deprecated_offset;
// Address of chonkyAttributes contract
address chonkyAttributes;
// Address of chonkyMetadata contract
address chonkyMetadata;
// Address of chonkySet contract
address chonkySet;
// Timestamp at which minting starts
uint256 startTimestamp;
// Reveal ranges
RevealRange[] revealRanges;
}
function layout() internal pure returns (Layout storage l) {
bytes32 slot = STORAGE_SLOT;
assembly {
l.slot := slot
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {IERC721} from "@solidstate/contracts/token/ERC721/IERC721.sol";
import {IERC721Enumerable} from "@solidstate/contracts/token/ERC721/enumerable/IERC721Enumerable.sol";
interface IChonkyNFT is IERC721, IERC721Enumerable {
function mint() external payable;
function parseGenome(uint256 _genome)
external
pure
returns (uint256[12] memory result);
function formatGenome(uint256[12] memory _attributes)
external
pure
returns (uint256 genome);
function getGenome(uint256 _id) external view returns (uint256);
function getChonkyAttributesAddress() external view returns (address);
function getChonkyMetadataAddress() external view returns (address);
function getChonkySetAddress() external view returns (address);
function getCID() external pure returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import { AddressUtils } from '../../../utils/AddressUtils.sol';
import { EnumerableMap } from '../../../utils/EnumerableMap.sol';
import { EnumerableSet } from '../../../utils/EnumerableSet.sol';
import { IERC721 } from '../IERC721.sol';
import { IERC721Receiver } from '../IERC721Receiver.sol';
import { ERC721BaseStorage } from './ERC721BaseStorage.sol';
import { ERC721BaseInternal } from './ERC721BaseInternal.sol';
/**
* @notice Base ERC721 implementation, excluding optional extensions
*/
abstract contract ERC721Base is IERC721, ERC721BaseInternal {
using AddressUtils for address;
using EnumerableMap for EnumerableMap.UintToAddressMap;
using EnumerableSet for EnumerableSet.UintSet;
/**
* @inheritdoc IERC721
*/
function balanceOf(address account) public view override returns (uint256) {
return _balanceOf(account);
}
/**
* @inheritdoc IERC721
*/
function ownerOf(uint256 tokenId) public view override returns (address) {
return _ownerOf(tokenId);
}
/**
* @inheritdoc IERC721
*/
function getApproved(uint256 tokenId)
public
view
override
returns (address)
{
return _getApproved(tokenId);
}
/**
* @inheritdoc IERC721
*/
function isApprovedForAll(address account, address operator)
public
view
override
returns (bool)
{
return _isApprovedForAll(account, operator);
}
/**
* @inheritdoc IERC721
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public payable override {
_handleTransferMessageValue(from, to, tokenId, msg.value);
require(
_isApprovedOrOwner(msg.sender, tokenId),
'ERC721: transfer caller is not owner or approved'
);
_transfer(from, to, tokenId);
}
/**
* @inheritdoc IERC721
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public payable override {
safeTransferFrom(from, to, tokenId, '');
}
/**
* @inheritdoc IERC721
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory data
) public payable override {
_handleTransferMessageValue(from, to, tokenId, msg.value);
require(
_isApprovedOrOwner(msg.sender, tokenId),
'ERC721: transfer caller is not owner or approved'
);
_safeTransfer(from, to, tokenId, data);
}
/**
* @inheritdoc IERC721
*/
function approve(address operator, uint256 tokenId)
public
payable
override
{
_handleApproveMessageValue(operator, tokenId, msg.value);
address owner = ownerOf(tokenId);
require(operator != owner, 'ERC721: approval to current owner');
require(
msg.sender == owner || isApprovedForAll(owner, msg.sender),
'ERC721: approve caller is not owner nor approved for all'
);
_approve(operator, tokenId);
}
/**
* @inheritdoc IERC721
*/
function setApprovalForAll(address operator, bool status) public override {
require(operator != msg.sender, 'ERC721: approve to caller');
ERC721BaseStorage.layout().operatorApprovals[msg.sender][
operator
] = status;
emit ApprovalForAll(msg.sender, operator, status);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import { EnumerableMap } from '../../../utils/EnumerableMap.sol';
import { EnumerableSet } from '../../../utils/EnumerableSet.sol';
import { ERC721BaseStorage } from '../base/ERC721BaseStorage.sol';
import { IERC721Enumerable } from './IERC721Enumerable.sol';
import { ERC721EnumerableInternal } from './ERC721EnumerableInternal.sol';
abstract contract ERC721Enumerable is
IERC721Enumerable,
ERC721EnumerableInternal
{
using EnumerableMap for EnumerableMap.UintToAddressMap;
using EnumerableSet for EnumerableSet.UintSet;
/**
* @inheritdoc IERC721Enumerable
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply();
}
/**
* @inheritdoc IERC721Enumerable
*/
function tokenOfOwnerByIndex(address owner, uint256 index)
public
view
override
returns (uint256)
{
return _tokenOfOwnerByIndex(owner, index);
}
/**
* @inheritdoc IERC721Enumerable
*/
function tokenByIndex(uint256 index)
public
view
override
returns (uint256)
{
return _tokenByIndex(index);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import { UintUtils } from '../../../utils/UintUtils.sol';
import { ERC721BaseInternal, ERC721BaseStorage } from '../base/ERC721Base.sol';
import { ERC721MetadataStorage } from './ERC721MetadataStorage.sol';
import { ERC721MetadataInternal } from './ERC721MetadataInternal.sol';
import { IERC721Metadata } from './IERC721Metadata.sol';
/**
* @notice ERC721 metadata extensions
*/
abstract contract ERC721Metadata is IERC721Metadata, ERC721MetadataInternal {
using ERC721BaseStorage for ERC721BaseStorage.Layout;
using UintUtils for uint256;
/**
* @notice inheritdoc IERC721Metadata
*/
function name() public view virtual override returns (string memory) {
return ERC721MetadataStorage.layout().name;
}
/**
* @notice inheritdoc IERC721Metadata
*/
function symbol() public view virtual override returns (string memory) {
return ERC721MetadataStorage.layout().symbol;
}
/**
* @notice inheritdoc IERC721Metadata
*/
function tokenURI(uint256 tokenId)
public
view
virtual
override
returns (string memory)
{
require(
ERC721BaseStorage.layout().exists(tokenId),
'ERC721Metadata: URI query for nonexistent token'
);
ERC721MetadataStorage.Layout storage l = ERC721MetadataStorage.layout();
string memory tokenIdURI = l.tokenURIs[tokenId];
string memory baseURI = l.baseURI;
if (bytes(baseURI).length == 0) {
return tokenIdURI;
} else if (bytes(tokenIdURI).length > 0) {
return string(abi.encodePacked(baseURI, tokenIdURI));
} else {
return string(abi.encodePacked(baseURI, tokenId.toString()));
}
}
/**
* @inheritdoc ERC721MetadataInternal
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import { IERC165 } from './IERC165.sol';
import { ERC165Storage } from './ERC165Storage.sol';
/**
* @title ERC165 implementation
*/
abstract contract ERC165 is IERC165 {
using ERC165Storage for ERC165Storage.Layout;
/**
* @inheritdoc IERC165
*/
function supportsInterface(bytes4 interfaceId)
public
view
override
returns (bool)
{
return ERC165Storage.layout().isSupportedInterface(interfaceId);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
library AddressUtils {
function toString(address account) internal pure returns (string memory) {
bytes32 value = bytes32(uint256(uint160(account)));
bytes memory alphabet = '0123456789abcdef';
bytes memory chars = new bytes(42);
chars[0] = '0';
chars[1] = 'x';
for (uint256 i = 0; i < 20; i++) {
chars[2 + i * 2] = alphabet[uint8(value[i + 12] >> 4)];
chars[3 + i * 2] = alphabet[uint8(value[i + 12] & 0x0f)];
}
return string(chars);
}
function isContract(address account) internal view returns (bool) {
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
function sendValue(address payable account, uint256 amount) internal {
(bool success, ) = account.call{ value: amount }('');
require(success, 'AddressUtils: failed to send value');
}
function functionCall(address target, bytes memory data)
internal
returns (bytes memory)
{
return
functionCall(target, data, 'AddressUtils: failed low-level call');
}
function functionCall(
address target,
bytes memory data,
string memory error
) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, error);
}
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return
functionCallWithValue(
target,
data,
value,
'AddressUtils: failed low-level call with value'
);
}
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory error
) internal returns (bytes memory) {
require(
address(this).balance >= value,
'AddressUtils: insufficient balance for call'
);
return _functionCallWithValue(target, data, value, error);
}
function _functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory error
) private returns (bytes memory) {
require(
isContract(target),
'AddressUtils: function call to non-contract'
);
(bool success, bytes memory returnData) = target.call{ value: value }(
data
);
if (success) {
return returnData;
} else if (returnData.length > 0) {
assembly {
let returnData_size := mload(returnData)
revert(add(32, returnData), returnData_size)
}
} else {
revert(error);
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title Map implementation with enumeration functions
* @dev derived from https://github.com/OpenZeppelin/openzeppelin-contracts (MIT license)
*/
library EnumerableMap {
struct MapEntry {
bytes32 _key;
bytes32 _value;
}
struct Map {
MapEntry[] _entries;
// 1-indexed to allow 0 to signify nonexistence
mapping(bytes32 => uint256) _indexes;
}
struct AddressToAddressMap {
Map _inner;
}
struct UintToAddressMap {
Map _inner;
}
function at(AddressToAddressMap storage map, uint256 index)
internal
view
returns (address, address)
{
(bytes32 key, bytes32 value) = _at(map._inner, index);
address addressKey;
assembly {
addressKey := mload(add(key, 20))
}
return (addressKey, address(uint160(uint256(value))));
}
function at(UintToAddressMap storage map, uint256 index)
internal
view
returns (uint256, address)
{
(bytes32 key, bytes32 value) = _at(map._inner, index);
return (uint256(key), address(uint160(uint256(value))));
}
function contains(AddressToAddressMap storage map, address key)
internal
view
returns (bool)
{
return _contains(map._inner, bytes32(uint256(uint160(key))));
}
function contains(UintToAddressMap storage map, uint256 key)
internal
view
returns (bool)
{
return _contains(map._inner, bytes32(key));
}
function length(AddressToAddressMap storage map)
internal
view
returns (uint256)
{
return _length(map._inner);
}
function length(UintToAddressMap storage map)
internal
view
returns (uint256)
{
return _length(map._inner);
}
function get(AddressToAddressMap storage map, address key)
internal
view
returns (address)
{
return
address(
uint160(
uint256(_get(map._inner, bytes32(uint256(uint160(key)))))
)
);
}
function get(UintToAddressMap storage map, uint256 key)
internal
view
returns (address)
{
return address(uint160(uint256(_get(map._inner, bytes32(key)))));
}
function set(
AddressToAddressMap storage map,
address key,
address value
) internal returns (bool) {
return
_set(
map._inner,
bytes32(uint256(uint160(key))),
bytes32(uint256(uint160(value)))
);
}
function set(
UintToAddressMap storage map,
uint256 key,
address value
) internal returns (bool) {
return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value))));
}
function remove(AddressToAddressMap storage map, address key)
internal
returns (bool)
{
return _remove(map._inner, bytes32(uint256(uint160(key))));
}
function remove(UintToAddressMap storage map, uint256 key)
internal
returns (bool)
{
return _remove(map._inner, bytes32(key));
}
function _at(Map storage map, uint256 index)
private
view
returns (bytes32, bytes32)
{
require(
map._entries.length > index,
'EnumerableMap: index out of bounds'
);
MapEntry storage entry = map._entries[index];
return (entry._key, entry._value);
}
function _contains(Map storage map, bytes32 key)
private
view
returns (bool)
{
return map._indexes[key] != 0;
}
function _length(Map storage map) private view returns (uint256) {
return map._entries.length;
}
function _get(Map storage map, bytes32 key) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, 'EnumerableMap: nonexistent key');
return map._entries[keyIndex - 1]._value;
}
function _set(
Map storage map,
bytes32 key,
bytes32 value
) private returns (bool) {
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) {
map._entries.push(MapEntry({ _key: key, _value: value }));
map._indexes[key] = map._entries.length;
return true;
} else {
map._entries[keyIndex - 1]._value = value;
return false;
}
}
function _remove(Map storage map, bytes32 key) private returns (bool) {
uint256 keyIndex = map._indexes[key];
if (keyIndex != 0) {
uint256 index = keyIndex - 1;
MapEntry storage last = map._entries[map._entries.length - 1];
// move last entry to now-vacant index
map._entries[index] = last;
map._indexes[last._key] = index + 1;
// clear last index
map._entries.pop();
delete map._indexes[key];
return true;
} else {
return false;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title Set implementation with enumeration functions
* @dev derived from https://github.com/OpenZeppelin/openzeppelin-contracts (MIT license)
*/
library EnumerableSet {
struct Set {
bytes32[] _values;
// 1-indexed to allow 0 to signify nonexistence
mapping(bytes32 => uint256) _indexes;
}
struct Bytes32Set {
Set _inner;
}
struct AddressSet {
Set _inner;
}
struct UintSet {
Set _inner;
}
function at(Bytes32Set storage set, uint256 index)
internal
view
returns (bytes32)
{
return _at(set._inner, index);
}
function at(AddressSet storage set, uint256 index)
internal
view
returns (address)
{
return address(uint160(uint256(_at(set._inner, index))));
}
function at(UintSet storage set, uint256 index)
internal
view
returns (uint256)
{
return uint256(_at(set._inner, index));
}
function contains(Bytes32Set storage set, bytes32 value)
internal
view
returns (bool)
{
return _contains(set._inner, value);
}
function contains(AddressSet storage set, address value)
internal
view
returns (bool)
{
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
function contains(UintSet storage set, uint256 value)
internal
view
returns (bool)
{
return _contains(set._inner, bytes32(value));
}
function indexOf(Bytes32Set storage set, bytes32 value)
internal
view
returns (uint256)
{
return _indexOf(set._inner, value);
}
function indexOf(AddressSet storage set, address value)
internal
view
returns (uint256)
{
return _indexOf(set._inner, bytes32(uint256(uint160(value))));
}
function indexOf(UintSet storage set, uint256 value)
internal
view
returns (uint256)
{
return _indexOf(set._inner, bytes32(value));
}
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
function add(Bytes32Set storage set, bytes32 value)
internal
returns (bool)
{
return _add(set._inner, value);
}
function add(AddressSet storage set, address value)
internal
returns (bool)
{
return _add(set._inner, bytes32(uint256(uint160(value))));
}
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
function remove(Bytes32Set storage set, bytes32 value)
internal
returns (bool)
{
return _remove(set._inner, value);
}
function remove(AddressSet storage set, address value)
internal
returns (bool)
{
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
function remove(UintSet storage set, uint256 value)
internal
returns (bool)
{
return _remove(set._inner, bytes32(value));
}
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];
}
function _contains(Set storage set, bytes32 value)
private
view
returns (bool)
{
return set._indexes[value] != 0;
}
function _indexOf(Set storage set, bytes32 value)
private
view
returns (uint256)
{
unchecked {
return set._indexes[value] - 1;
}
}
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
function _remove(Set storage set, bytes32 value) private returns (bool) {
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) {
uint256 index = valueIndex - 1;
bytes32 last = set._values[set._values.length - 1];
// move last value to now-vacant index
set._values[index] = last;
set._indexes[last] = index + 1;
// clear last index
set._values.pop();
delete set._indexes[value];
return true;
} else {
return false;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import { IERC165 } from '../../introspection/IERC165.sol';
import { IERC721Internal } from './IERC721Internal.sol';
/**
* @notice ERC721 interface
* @dev see https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721 is IERC721Internal, IERC165 {
/**
* @notice query the balance of given address
* @return balance quantity of tokens held
*/
function balanceOf(address account) external view returns (uint256 balance);
/**
* @notice query the owner of given token
* @param tokenId token to query
* @return owner token owner
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @notice transfer token between given addresses, checking for ERC721Receiver implementation if applicable
* @param from sender of token
* @param to receiver of token
* @param tokenId token id
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external payable;
/**
* @notice transfer token between given addresses, checking for ERC721Receiver implementation if applicable
* @param from sender of token
* @param to receiver of token
* @param tokenId token id
* @param data data payload
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external payable;
/**
* @notice transfer token between given addresses, without checking for ERC721Receiver implementation if applicable
* @param from sender of token
* @param to receiver of token
* @param tokenId token id
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external payable;
/**
* @notice grant approval to given account to spend token
* @param operator address to be approved
* @param tokenId token to approve
*/
function approve(address operator, uint256 tokenId) external payable;
/**
* @notice get approval status for given token
* @param tokenId token to query
* @return operator address approved to spend token
*/
function getApproved(uint256 tokenId)
external
view
returns (address operator);
/**
* @notice grant approval to or revoke approval from given account to spend all tokens held by sender
* @param operator address to be approved
* @param status approval status
*/
function setApprovalForAll(address operator, bool status) external;
/**
* @notice query approval status of given operator with respect to given address
* @param account address to query for approval granted
* @param operator address to query for approval received
* @return status whether operator is approved to spend tokens held by account
*/
function isApprovedForAll(address account, address operator)
external
view
returns (bool status);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IERC721Receiver {
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import { AddressUtils } from '../../../utils/AddressUtils.sol';
import { EnumerableMap } from '../../../utils/EnumerableMap.sol';
import { EnumerableSet } from '../../../utils/EnumerableSet.sol';
import { IERC721Internal } from '../IERC721Internal.sol';
import { IERC721Receiver } from '../IERC721Receiver.sol';
import { ERC721BaseStorage } from './ERC721BaseStorage.sol';
/**
* @notice Base ERC721 internal functions
*/
abstract contract ERC721BaseInternal is IERC721Internal {
using ERC721BaseStorage for ERC721BaseStorage.Layout;
using AddressUtils for address;
using EnumerableMap for EnumerableMap.UintToAddressMap;
using EnumerableSet for EnumerableSet.UintSet;
function _balanceOf(address account) internal view returns (uint256) {
require(
account != address(0),
'ERC721: balance query for the zero address'
);
return ERC721BaseStorage.layout().holderTokens[account].length();
}
function _ownerOf(uint256 tokenId) internal view returns (address) {
address owner = ERC721BaseStorage.layout().tokenOwners.get(tokenId);
require(owner != address(0), 'ERC721: invalid owner');
return owner;
}
function _getApproved(uint256 tokenId) internal view returns (address) {
ERC721BaseStorage.Layout storage l = ERC721BaseStorage.layout();
require(
l.exists(tokenId),
'ERC721: approved query for nonexistent token'
);
return l.tokenApprovals[tokenId];
}
function _isApprovedForAll(address account, address operator)
internal
view
returns (bool)
{
return ERC721BaseStorage.layout().operatorApprovals[account][operator];
}
function _isApprovedOrOwner(address spender, uint256 tokenId)
internal
view
returns (bool)
{
require(
ERC721BaseStorage.layout().exists(tokenId),
'ERC721: query for nonexistent token'
);
address owner = _ownerOf(tokenId);
return (spender == owner ||
_getApproved(tokenId) == spender ||
_isApprovedForAll(owner, spender));
}
function _mint(address to, uint256 tokenId) internal {
require(to != address(0), 'ERC721: mint to the zero address');
ERC721BaseStorage.Layout storage l = ERC721BaseStorage.layout();
require(!l.exists(tokenId), 'ERC721: token already minted');
_beforeTokenTransfer(address(0), to, tokenId);
l.holderTokens[to].add(tokenId);
l.tokenOwners.set(tokenId, to);
emit Transfer(address(0), to, tokenId);
}
function _safeMint(address to, uint256 tokenId) internal {
_safeMint(to, tokenId, '');
}
function _safeMint(
address to,
uint256 tokenId,
bytes memory data
) internal {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, data),
'ERC721: transfer to non ERC721Receiver implementer'
);
}
function _burn(uint256 tokenId) internal {
address owner = _ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
_approve(address(0), tokenId);
ERC721BaseStorage.Layout storage l = ERC721BaseStorage.layout();
l.holderTokens[owner].remove(tokenId);
l.tokenOwners.remove(tokenId);
emit Transfer(owner, address(0), tokenId);
}
function _transfer(
address from,
address to,
uint256 tokenId
) internal {
require(
_ownerOf(tokenId) == from,
'ERC721: transfer of token that is not own'
);
require(to != address(0), 'ERC721: transfer to the zero address');
_beforeTokenTransfer(from, to, tokenId);
_approve(address(0), tokenId);
ERC721BaseStorage.Layout storage l = ERC721BaseStorage.layout();
l.holderTokens[from].remove(tokenId);
l.holderTokens[to].add(tokenId);
l.tokenOwners.set(tokenId, to);
emit Transfer(from, to, tokenId);
}
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory data
) internal {
_transfer(from, to, tokenId);
require(
_checkOnERC721Received(from, to, tokenId, data),
'ERC721: transfer to non ERC721Receiver implementer'
);
}
function _approve(address operator, uint256 tokenId) internal {
ERC721BaseStorage.layout().tokenApprovals[tokenId] = operator;
emit Approval(_ownerOf(tokenId), operator, tokenId);
}
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory data
) internal returns (bool) {
if (!to.isContract()) {
return true;
}
bytes memory returnData = to.functionCall(
abi.encodeWithSelector(
IERC721Receiver(to).onERC721Received.selector,
msg.sender,
from,
tokenId,
data
),
'ERC721: transfer to non ERC721Receiver implementer'
);
bytes4 returnValue = abi.decode(returnData, (bytes4));
return returnValue == type(IERC721Receiver).interfaceId;
}
/**
* @notice ERC721 hook, called before externally called approvals for processing of included message value
* @param operator beneficiary of approval
* @param tokenId id of transferred token
* @param value message value
*/
function _handleApproveMessageValue(
address operator,
uint256 tokenId,
uint256 value
) internal virtual {}
/**
* @notice ERC721 hook, called before externally called transfers for processing of included message value
* @param from sender of token
* @param to receiver of token
* @param tokenId id of transferred token
* @param value message value
*/
function _handleTransferMessageValue(
address from,
address to,
uint256 tokenId,
uint256 value
) internal virtual {}
/**
* @notice ERC721 hook, called before all transfers including mint and burn
* @dev function should be overridden and new implementation must call super
* @param from sender of token
* @param to receiver of token
* @param tokenId id of transferred token
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title ERC165 interface registration interface
* @dev see https://eips.ethereum.org/EIPS/eip-165
*/
interface IERC165 {
/**
* @notice query whether contract has registered support for given interface
* @param interfaceId interface id
* @return bool whether interface is supported
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @notice Partial ERC721 interface needed by internal functions
*/
interface IERC721Internal {
event Transfer(
address indexed from,
address indexed to,
uint256 indexed tokenId
);
event Approval(
address indexed owner,
address indexed operator,
uint256 indexed tokenId
);
event ApprovalForAll(
address indexed owner,
address indexed operator,
bool approved
);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IERC721Enumerable {
/**
* @notice get total token supply
* @return total supply
*/
function totalSupply() external view returns (uint256);
/**
* @notice get token of given owner at given internal storage index
* @param owner token holder to query
* @param index position in owner's token list to query
* @return tokenId id of retrieved token
*/
function tokenOfOwnerByIndex(address owner, uint256 index)
external
view
returns (uint256 tokenId);
/**
* @notice get token at given internal storage index
* @param index position in global token list to query
* @return tokenId id of retrieved token
*/
function tokenByIndex(uint256 index)
external
view
returns (uint256 tokenId);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import { ERC721BaseStorage } from '../base/ERC721BaseStorage.sol';
abstract contract ERC721EnumerableInternal {
using ERC721BaseStorage for ERC721BaseStorage.Layout;
/**
* @notice TODO
*/
function _totalSupply() internal view returns (uint256) {
return ERC721BaseStorage.layout().totalSupply();
}
/**
* @notice TODO
*/
function _tokenOfOwnerByIndex(address owner, uint256 index)
internal
view
returns (uint256)
{
return ERC721BaseStorage.layout().tokenOfOwnerByIndex(owner, index);
}
/**
* @notice TODO
*/
function _tokenByIndex(uint256 index) internal view returns (uint256) {
return ERC721BaseStorage.layout().tokenByIndex(index);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
library UintUtils {
function toString(uint256 value) internal pure returns (string memory) {
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);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
library ERC721MetadataStorage {
bytes32 internal constant STORAGE_SLOT =
keccak256('solidstate.contracts.storage.ERC721Metadata');
struct Layout {
string name;
string symbol;
string baseURI;
mapping(uint256 => string) tokenURIs;
}
function layout() internal pure returns (Layout storage l) {
bytes32 slot = STORAGE_SLOT;
assembly {
l.slot := slot
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import { ERC721BaseInternal } from '../base/ERC721Base.sol';
import { ERC721MetadataStorage } from './ERC721MetadataStorage.sol';
/**
* @notice ERC721Metadata internal functions
*/
abstract contract ERC721MetadataInternal is ERC721BaseInternal {
/**
* @notice ERC721 hook: clear per-token URI data on burn
* @inheritdoc ERC721BaseInternal
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (to == address(0)) {
delete ERC721MetadataStorage.layout().tokenURIs[tokenId];
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title ERC721Metadata interface
*/
interface IERC721Metadata {
/**
* @notice get token name
* @return token name
*/
function name() external view returns (string memory);
/**
* @notice get token symbol
* @return token symbol
*/
function symbol() external view returns (string memory);
/**
* @notice get generated URI for given token
* @return token URI
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
library ERC165Storage {
struct Layout {
mapping(bytes4 => bool) supportedInterfaces;
}
bytes32 internal constant STORAGE_SLOT =
keccak256('solidstate.contracts.storage.ERC165');
function layout() internal pure returns (Layout storage l) {
bytes32 slot = STORAGE_SLOT;
assembly {
l.slot := slot
}
}
function isSupportedInterface(Layout storage l, bytes4 interfaceId)
internal
view
returns (bool)
{
return l.supportedInterfaces[interfaceId];
}
function setSupportedInterface(
Layout storage l,
bytes4 interfaceId,
bool status
) internal {
require(interfaceId != 0xffffffff, 'ERC165: invalid interface id');
l.supportedInterfaces[interfaceId] = status;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
library OwnableStorage {
struct Layout {
address owner;
}
bytes32 internal constant STORAGE_SLOT =
keccak256('solidstate.contracts.storage.Ownable');
function layout() internal pure returns (Layout storage l) {
bytes32 slot = STORAGE_SLOT;
assembly {
l.slot := slot
}
}
function setOwner(Layout storage l, address owner) internal {
l.owner = owner;
}
}
// SPDX-License-Identifier: MIT
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);
}
// SPDX-License-Identifier: MIT
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));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0;
/// @title Base64
/// @author Brecht Devos - <[email protected]>
/// @notice Provides functions for encoding/decoding base64
library Base64 {
string internal constant TABLE_ENCODE = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
bytes internal constant TABLE_DECODE = hex"0000000000000000000000000000000000000000000000000000000000000000"
hex"00000000000000000000003e0000003f3435363738393a3b3c3d000000000000"
hex"00000102030405060708090a0b0c0d0e0f101112131415161718190000000000"
hex"001a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132330000000000";
function encode(bytes memory data) internal pure returns (string memory) {
if (data.length == 0) return '';
// load the table into memory
string memory table = TABLE_ENCODE;
// multiply by 4/3 rounded up
uint256 encodedLen = 4 * ((data.length + 2) / 3);
// add some extra buffer at the end required for the writing
string memory result = new string(encodedLen + 32);
assembly {
// set the actual output length
mstore(result, encodedLen)
// prepare the lookup table
let tablePtr := add(table, 1)
// input ptr
let dataPtr := data
let endPtr := add(dataPtr, mload(data))
// result ptr, jump over length
let resultPtr := add(result, 32)
// run over the input, 3 bytes at a time
for {} lt(dataPtr, endPtr) {}
{
// read 3 bytes
dataPtr := add(dataPtr, 3)
let input := mload(dataPtr)
// write 4 characters
mstore8(resultPtr, mload(add(tablePtr, and(shr(18, input), 0x3F))))
resultPtr := add(resultPtr, 1)
mstore8(resultPtr, mload(add(tablePtr, and(shr(12, input), 0x3F))))
resultPtr := add(resultPtr, 1)
mstore8(resultPtr, mload(add(tablePtr, and(shr( 6, input), 0x3F))))
resultPtr := add(resultPtr, 1)
mstore8(resultPtr, mload(add(tablePtr, and( input, 0x3F))))
resultPtr := add(resultPtr, 1)
}
// padding with '='
switch mod(mload(data), 3)
case 1 { mstore(sub(resultPtr, 2), shl(240, 0x3d3d)) }
case 2 { mstore(sub(resultPtr, 1), shl(248, 0x3d)) }
}
return result;
}
function decode(string memory _data) internal pure returns (bytes memory) {
bytes memory data = bytes(_data);
if (data.length == 0) return new bytes(0);
require(data.length % 4 == 0, "invalid base64 decoder input");
// load the table into memory
bytes memory table = TABLE_DECODE;
// every 4 characters represent 3 bytes
uint256 decodedLen = (data.length / 4) * 3;
// add some extra buffer at the end required for the writing
bytes memory result = new bytes(decodedLen + 32);
assembly {
// padding with '='
let lastBytes := mload(add(data, mload(data)))
if eq(and(lastBytes, 0xFF), 0x3d) {
decodedLen := sub(decodedLen, 1)
if eq(and(lastBytes, 0xFFFF), 0x3d3d) {
decodedLen := sub(decodedLen, 1)
}
}
// set the actual output length
mstore(result, decodedLen)
// prepare the lookup table
let tablePtr := add(table, 1)
// input ptr
let dataPtr := data
let endPtr := add(dataPtr, mload(data))
// result ptr, jump over length
let resultPtr := add(result, 32)
// run over the input, 4 characters at a time
for {} lt(dataPtr, endPtr) {}
{
// read 4 characters
dataPtr := add(dataPtr, 4)
let input := mload(dataPtr)
// write 3 bytes
let output := add(
add(
shl(18, and(mload(add(tablePtr, and(shr(24, input), 0xFF))), 0xFF)),
shl(12, and(mload(add(tablePtr, and(shr(16, input), 0xFF))), 0xFF))),
add(
shl( 6, and(mload(add(tablePtr, and(shr( 8, input), 0xFF))), 0xFF)),
and(mload(add(tablePtr, and( input , 0xFF))), 0xFF)
)
)
mstore(resultPtr, shl(232, output))
resultPtr := add(resultPtr, 3)
}
}
return result;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {IChonkyAttributes} from "./interface/IChonkyAttributes.sol";
contract ChonkyAttributes is IChonkyAttributes {
function _getBodyAttribute(uint256 _id)
internal
pure
returns (IChonkyAttributes.AttributeType, uint256)
{
if (_id == 0) return (IChonkyAttributes.AttributeType.NONE, 0);
if (_id == 1) return (IChonkyAttributes.AttributeType.CUTE, 7);
if (_id == 2) return (IChonkyAttributes.AttributeType.CUTE, 6);
if (_id == 3) return (IChonkyAttributes.AttributeType.WICKED, 8);
if (_id == 4) return (IChonkyAttributes.AttributeType.BRAIN, 9);
if (_id == 5) return (IChonkyAttributes.AttributeType.POWER, 3);
if (_id == 6) return (IChonkyAttributes.AttributeType.WICKED, 10);
if (_id == 7) return (IChonkyAttributes.AttributeType.CUTE, 9);
if (_id == 8) return (IChonkyAttributes.AttributeType.POWER, 10);
if (_id == 9) return (IChonkyAttributes.AttributeType.WICKED, 2);
if (_id == 10) return (IChonkyAttributes.AttributeType.POWER, 2);
if (_id == 11) return (IChonkyAttributes.AttributeType.CUTE, 6);
if (_id == 12) return (IChonkyAttributes.AttributeType.CUTE, 4);
if (_id == 13) return (IChonkyAttributes.AttributeType.POWER, 1);
if (_id == 14) return (IChonkyAttributes.AttributeType.BRAIN, 2);
if (_id == 15) return (IChonkyAttributes.AttributeType.BRAIN, 6);
if (_id == 16) return (IChonkyAttributes.AttributeType.CUTE, 5);
if (_id == 17) return (IChonkyAttributes.AttributeType.POWER, 3);
if (_id == 18) return (IChonkyAttributes.AttributeType.POWER, 2);
if (_id == 19) return (IChonkyAttributes.AttributeType.BRAIN, 1);
if (_id == 20) return (IChonkyAttributes.AttributeType.CUTE, 2);
if (_id == 21) return (IChonkyAttributes.AttributeType.WICKED, 3);
if (_id == 22) return (IChonkyAttributes.AttributeType.WICKED, 4);
if (_id == 23) return (IChonkyAttributes.AttributeType.POWER, 5);
if (_id == 24) return (IChonkyAttributes.AttributeType.POWER, 8);
if (_id == 25) return (IChonkyAttributes.AttributeType.WICKED, 6);
if (_id == 26) return (IChonkyAttributes.AttributeType.POWER, 8);
if (_id == 27) return (IChonkyAttributes.AttributeType.CUTE, 1);
if (_id == 28) return (IChonkyAttributes.AttributeType.WICKED, 8);
if (_id == 29) return (IChonkyAttributes.AttributeType.POWER, 2);
if (_id == 30) return (IChonkyAttributes.AttributeType.BRAIN, 8);
if (_id == 31) return (IChonkyAttributes.AttributeType.POWER, 6);
if (_id == 32) return (IChonkyAttributes.AttributeType.CUTE, 4);
if (_id == 33) return (IChonkyAttributes.AttributeType.POWER, 1);
if (_id == 34) return (IChonkyAttributes.AttributeType.POWER, 2);
if (_id == 35) return (IChonkyAttributes.AttributeType.WICKED, 5);
if (_id == 36) return (IChonkyAttributes.AttributeType.CUTE, 7);
if (_id == 37) return (IChonkyAttributes.AttributeType.CUTE, 5);
if (_id == 38) return (IChonkyAttributes.AttributeType.POWER, 5);
if (_id == 39) return (IChonkyAttributes.AttributeType.POWER, 10);
if (_id == 40) return (IChonkyAttributes.AttributeType.POWER, 4);
if (_id == 41) return (IChonkyAttributes.AttributeType.WICKED, 7);
if (_id == 42) return (IChonkyAttributes.AttributeType.WICKED, 8);
if (_id == 43) return (IChonkyAttributes.AttributeType.POWER, 9);
if (_id == 44) return (IChonkyAttributes.AttributeType.BRAIN, 8);
if (_id == 45) return (IChonkyAttributes.AttributeType.CUTE, 1);
if (_id == 46) return (IChonkyAttributes.AttributeType.WICKED, 8);
if (_id == 47) return (IChonkyAttributes.AttributeType.CUTE, 6);
if (_id == 48) return (IChonkyAttributes.AttributeType.POWER, 7);
if (_id == 49) return (IChonkyAttributes.AttributeType.CUTE, 1);
if (_id == 50) return (IChonkyAttributes.AttributeType.POWER, 1);
if (_id == 51) return (IChonkyAttributes.AttributeType.POWER, 6);
if (_id == 52) return (IChonkyAttributes.AttributeType.WICKED, 7);
if (_id == 53) return (IChonkyAttributes.AttributeType.POWER, 9);
if (_id == 54) return (IChonkyAttributes.AttributeType.POWER, 3);
if (_id == 55) return (IChonkyAttributes.AttributeType.CUTE, 2);
if (_id == 56) return (IChonkyAttributes.AttributeType.POWER, 2);
if (_id == 57) return (IChonkyAttributes.AttributeType.CUTE, 3);
if (_id == 58) return (IChonkyAttributes.AttributeType.BRAIN, 1);
if (_id == 59) return (IChonkyAttributes.AttributeType.POWER, 8);
if (_id == 60) return (IChonkyAttributes.AttributeType.WICKED, 9);
if (_id == 61) return (IChonkyAttributes.AttributeType.POWER, 5);
if (_id == 62) return (IChonkyAttributes.AttributeType.BRAIN, 8);
if (_id == 63) return (IChonkyAttributes.AttributeType.BRAIN, 2);
if (_id == 64) return (IChonkyAttributes.AttributeType.BRAIN, 3);
if (_id == 65) return (IChonkyAttributes.AttributeType.CUTE, 10);
if (_id == 66) return (IChonkyAttributes.AttributeType.CUTE, 1);
if (_id == 67) return (IChonkyAttributes.AttributeType.CUTE, 3);
if (_id == 68) return (IChonkyAttributes.AttributeType.BRAIN, 8);
if (_id == 69) return (IChonkyAttributes.AttributeType.POWER, 1);
if (_id == 70) return (IChonkyAttributes.AttributeType.BRAIN, 10);
if (_id == 71) return (IChonkyAttributes.AttributeType.BRAIN, 7);
if (_id == 72) return (IChonkyAttributes.AttributeType.POWER, 6);
if (_id == 73) return (IChonkyAttributes.AttributeType.POWER, 7);
if (_id == 74) return (IChonkyAttributes.AttributeType.POWER, 7);
if (_id == 75) return (IChonkyAttributes.AttributeType.POWER, 5);
if (_id == 76) return (IChonkyAttributes.AttributeType.BRAIN, 9);
if (_id == 77) return (IChonkyAttributes.AttributeType.BRAIN, 1);
if (_id == 78) return (IChonkyAttributes.AttributeType.CUTE, 2);
if (_id == 79) return (IChonkyAttributes.AttributeType.POWER, 9);
if (_id == 80) return (IChonkyAttributes.AttributeType.BRAIN, 9);
if (_id == 81) return (IChonkyAttributes.AttributeType.POWER, 2);
if (_id == 82) return (IChonkyAttributes.AttributeType.BRAIN, 3);
if (_id == 83) return (IChonkyAttributes.AttributeType.CUTE, 8);
if (_id == 84) return (IChonkyAttributes.AttributeType.CUTE, 7);
if (_id == 85) return (IChonkyAttributes.AttributeType.BRAIN, 7);
if (_id == 86) return (IChonkyAttributes.AttributeType.POWER, 9);
if (_id == 87) return (IChonkyAttributes.AttributeType.POWER, 4);
if (_id == 88) return (IChonkyAttributes.AttributeType.WICKED, 5);
if (_id == 89) return (IChonkyAttributes.AttributeType.BRAIN, 4);
if (_id == 90) return (IChonkyAttributes.AttributeType.POWER, 1);
if (_id == 91) return (IChonkyAttributes.AttributeType.WICKED, 8);
return (IChonkyAttributes.AttributeType.NONE, 0);
}
function _getEyesAttribute(uint256 _id)
internal
pure
returns (IChonkyAttributes.AttributeType, uint256)
{
if (_id == 0) return (IChonkyAttributes.AttributeType.NONE, 0);
if (_id == 1) return (IChonkyAttributes.AttributeType.CUTE, 2);
if (_id == 2) return (IChonkyAttributes.AttributeType.CUTE, 1);
if (_id == 3) return (IChonkyAttributes.AttributeType.NONE, 0);
if (_id == 4) return (IChonkyAttributes.AttributeType.POWER, 6);
if (_id == 5) return (IChonkyAttributes.AttributeType.POWER, 5);
if (_id == 6) return (IChonkyAttributes.AttributeType.WICKED, 7);
if (_id == 7) return (IChonkyAttributes.AttributeType.NONE, 0);
if (_id == 8) return (IChonkyAttributes.AttributeType.WICKED, 2);
if (_id == 9) return (IChonkyAttributes.AttributeType.CUTE, 7);
if (_id == 10) return (IChonkyAttributes.AttributeType.BRAIN, 8);
if (_id == 11) return (IChonkyAttributes.AttributeType.WICKED, 10);
if (_id == 12) return (IChonkyAttributes.AttributeType.NONE, 0);
if (_id == 13) return (IChonkyAttributes.AttributeType.NONE, 0);
if (_id == 14) return (IChonkyAttributes.AttributeType.CUTE, 8);
if (_id == 15) return (IChonkyAttributes.AttributeType.NONE, 0);
if (_id == 16) return (IChonkyAttributes.AttributeType.NONE, 0);
if (_id == 17) return (IChonkyAttributes.AttributeType.WICKED, 8);
if (_id == 18) return (IChonkyAttributes.AttributeType.BRAIN, 6);
if (_id == 19) return (IChonkyAttributes.AttributeType.CUTE, 5);
if (_id == 20) return (IChonkyAttributes.AttributeType.NONE, 0);
if (_id == 21) return (IChonkyAttributes.AttributeType.NONE, 0);
if (_id == 22) return (IChonkyAttributes.AttributeType.WICKED, 4);
if (_id == 23) return (IChonkyAttributes.AttributeType.BRAIN, 3);
if (_id == 24) return (IChonkyAttributes.AttributeType.POWER, 3);
if (_id == 25) return (IChonkyAttributes.AttributeType.POWER, 6);
if (_id == 26) return (IChonkyAttributes.AttributeType.CUTE, 7);
if (_id == 27) return (IChonkyAttributes.AttributeType.CUTE, 6);
if (_id == 28) return (IChonkyAttributes.AttributeType.NONE, 0);
if (_id == 29) return (IChonkyAttributes.AttributeType.BRAIN, 1);
if (_id == 30) return (IChonkyAttributes.AttributeType.CUTE, 4);
if (_id == 31) return (IChonkyAttributes.AttributeType.POWER, 3);
if (_id == 32) return (IChonkyAttributes.AttributeType.BRAIN, 8);
if (_id == 33) return (IChonkyAttributes.AttributeType.WICKED, 6);
if (_id == 34) return (IChonkyAttributes.AttributeType.POWER, 9);
if (_id == 35) return (IChonkyAttributes.AttributeType.NONE, 0);
if (_id == 36) return (IChonkyAttributes.AttributeType.NONE, 0);
if (_id == 37) return (IChonkyAttributes.AttributeType.WICKED, 2);
if (_id == 38) return (IChonkyAttributes.AttributeType.POWER, 5);
if (_id == 39) return (IChonkyAttributes.AttributeType.CUTE, 5);
if (_id == 40) return (IChonkyAttributes.AttributeType.NONE, 0);
if (_id == 41) return (IChonkyAttributes.AttributeType.BRAIN, 7);
if (_id == 42) return (IChonkyAttributes.AttributeType.WICKED, 10);
if (_id == 43) return (IChonkyAttributes.AttributeType.NONE, 0);
if (_id == 44) return (IChonkyAttributes.AttributeType.NONE, 0);
if (_id == 45) return (IChonkyAttributes.AttributeType.WICKED, 9);
if (_id == 46) return (IChonkyAttributes.AttributeType.CUTE, 4);
if (_id == 47) return (IChonkyAttributes.AttributeType.BRAIN, 8);
if (_id == 48) return (IChonkyAttributes.AttributeType.NONE, 0);
if (_id == 49) return (IChonkyAttributes.AttributeType.CUTE, 6);
if (_id == 50) return (IChonkyAttributes.AttributeType.POWER, 5);
if (_id == 51) return (IChonkyAttributes.AttributeType.NONE, 0);
if (_id == 52) return (IChonkyAttributes.AttributeType.BRAIN, 4);
if (_id == 53) return (IChonkyAttributes.AttributeType.BRAIN, 9);
if (_id == 54) return (IChonkyAttributes.AttributeType.POWER, 4);
if (_id == 55) return (IChonkyAttributes.AttributeType.CUTE, 2);
if (_id == 56) return (IChonkyAttributes.AttributeType.NONE, 0);
if (_id == 57) return (IChonkyAttributes.AttributeType.POWER, 3);
if (_id == 58) return (IChonkyAttributes.AttributeType.NONE, 0);
if (_id == 59) return (IChonkyAttributes.AttributeType.NONE, 0);
if (_id == 60) return (IChonkyAttributes.AttributeType.WICKED, 1);
if (_id == 61) return (IChonkyAttributes.AttributeType.WICKED, 3);
return (IChonkyAttributes.AttributeType.NONE, 0);
}
function _getMouthAttribute(uint256 _id)
internal
pure
returns (IChonkyAttributes.AttributeType, uint256)
{
if (_id == 0) return (IChonkyAttributes.AttributeType.NONE, 0);
if (_id == 1) return (IChonkyAttributes.AttributeType.POWER, 7);
if (_id == 2) return (IChonkyAttributes.AttributeType.WICKED, 6);
if (_id == 3) return (IChonkyAttributes.AttributeType.NONE, 0);
if (_id == 4) return (IChonkyAttributes.AttributeType.WICKED, 4);
if (_id == 5) return (IChonkyAttributes.AttributeType.NONE, 0);
if (_id == 6) return (IChonkyAttributes.AttributeType.NONE, 0);
if (_id == 7) return (IChonkyAttributes.AttributeType.CUTE, 8);
if (_id == 8) return (IChonkyAttributes.AttributeType.BRAIN, 5);
if (_id == 9) return (IChonkyAttributes.AttributeType.WICKED, 8);
if (_id == 10) return (IChonkyAttributes.AttributeType.POWER, 4);
if (_id == 11) return (IChonkyAttributes.AttributeType.BRAIN, 8);
if (_id == 12) return (IChonkyAttributes.AttributeType.NONE, 0);
if (_id == 13) return (IChonkyAttributes.AttributeType.POWER, 8);
if (_id == 14) return (IChonkyAttributes.AttributeType.CUTE, 5);
if (_id == 15) return (IChonkyAttributes.AttributeType.WICKED, 5);
if (_id == 16) return (IChonkyAttributes.AttributeType.CUTE, 3);
if (_id == 17) return (IChonkyAttributes.AttributeType.BRAIN, 1);
if (_id == 18) return (IChonkyAttributes.AttributeType.POWER, 6);
if (_id == 19) return (IChonkyAttributes.AttributeType.NONE, 0);
if (_id == 20) return (IChonkyAttributes.AttributeType.BRAIN, 9);
if (_id == 21) return (IChonkyAttributes.AttributeType.CUTE, 3);
if (_id == 22) return (IChonkyAttributes.AttributeType.CUTE, 4);
if (_id == 23) return (IChonkyAttributes.AttributeType.NONE, 0);
if (_id == 24) return (IChonkyAttributes.AttributeType.POWER, 5);
if (_id == 25) return (IChonkyAttributes.AttributeType.WICKED, 4);
if (_id == 26) return (IChonkyAttributes.AttributeType.BRAIN, 6);
if (_id == 27) return (IChonkyAttributes.AttributeType.BRAIN, 3);
if (_id == 28) return (IChonkyAttributes.AttributeType.BRAIN, 4);
if (_id == 29) return (IChonkyAttributes.AttributeType.NONE, 0);
if (_id == 30) return (IChonkyAttributes.AttributeType.POWER, 6);
if (_id == 31) return (IChonkyAttributes.AttributeType.NONE, 0);
if (_id == 32) return (IChonkyAttributes.AttributeType.POWER, 9);
if (_id == 33) return (IChonkyAttributes.AttributeType.NONE, 0);
if (_id == 34) return (IChonkyAttributes.AttributeType.NONE, 0);
if (_id == 35) return (IChonkyAttributes.AttributeType.WICKED, 3);
if (_id == 36) return (IChonkyAttributes.AttributeType.BRAIN, 8);
if (_id == 37) return (IChonkyAttributes.AttributeType.POWER, 9);
if (_id == 38) return (IChonkyAttributes.AttributeType.WICKED, 7);
if (_id == 39) return (IChonkyAttributes.AttributeType.BRAIN, 6);
if (_id == 40) return (IChonkyAttributes.AttributeType.CUTE, 4);
if (_id == 41) return (IChonkyAttributes.AttributeType.POWER, 4);
if (_id == 42) return (IChonkyAttributes.AttributeType.BRAIN, 5);
if (_id == 43) return (IChonkyAttributes.AttributeType.CUTE, 3);
if (_id == 44) return (IChonkyAttributes.AttributeType.BRAIN, 9);
if (_id == 45) return (IChonkyAttributes.AttributeType.WICKED, 8);
if (_id == 46) return (IChonkyAttributes.AttributeType.CUTE, 2);
if (_id == 47) return (IChonkyAttributes.AttributeType.BRAIN, 2);
if (_id == 48) return (IChonkyAttributes.AttributeType.CUTE, 1);
if (_id == 49) return (IChonkyAttributes.AttributeType.CUTE, 1);
if (_id == 50) return (IChonkyAttributes.AttributeType.WICKED, 1);
if (_id == 51) return (IChonkyAttributes.AttributeType.WICKED, 5);
if (_id == 52) return (IChonkyAttributes.AttributeType.NONE, 0);
if (_id == 53) return (IChonkyAttributes.AttributeType.NONE, 0);
if (_id == 54) return (IChonkyAttributes.AttributeType.NONE, 0);
return (IChonkyAttributes.AttributeType.NONE, 0);
}
function _getHatAttribute(uint256 _id)
internal
pure
returns (IChonkyAttributes.AttributeType, uint256)
{
if (_id == 0) return (IChonkyAttributes.AttributeType.NONE, 0);
if (_id == 1) return (IChonkyAttributes.AttributeType.CUTE, 8);
if (_id == 2) return (IChonkyAttributes.AttributeType.WICKED, 8);
if (_id == 3) return (IChonkyAttributes.AttributeType.BRAIN, 9);
if (_id == 4) return (IChonkyAttributes.AttributeType.CUTE, 4);
if (_id == 5) return (IChonkyAttributes.AttributeType.WICKED, 9);
if (_id == 6) return (IChonkyAttributes.AttributeType.WICKED, 3);
if (_id == 7) return (IChonkyAttributes.AttributeType.CUTE, 7);
if (_id == 8) return (IChonkyAttributes.AttributeType.POWER, 2);
if (_id == 9) return (IChonkyAttributes.AttributeType.CUTE, 1);
if (_id == 10) return (IChonkyAttributes.AttributeType.POWER, 4);
if (_id == 11) return (IChonkyAttributes.AttributeType.POWER, 6);
if (_id == 12) return (IChonkyAttributes.AttributeType.POWER, 2);
if (_id == 13) return (IChonkyAttributes.AttributeType.WICKED, 10);
if (_id == 14) return (IChonkyAttributes.AttributeType.POWER, 10);
if (_id == 15) return (IChonkyAttributes.AttributeType.WICKED, 3);
if (_id == 16) return (IChonkyAttributes.AttributeType.BRAIN, 2);
if (_id == 17) return (IChonkyAttributes.AttributeType.WICKED, 6);
if (_id == 18) return (IChonkyAttributes.AttributeType.WICKED, 5);
if (_id == 19) return (IChonkyAttributes.AttributeType.BRAIN, 9);
if (_id == 20) return (IChonkyAttributes.AttributeType.POWER, 2);
if (_id == 21) return (IChonkyAttributes.AttributeType.WICKED, 3);
if (_id == 22) return (IChonkyAttributes.AttributeType.POWER, 6);
if (_id == 23) return (IChonkyAttributes.AttributeType.WICKED, 4);
if (_id == 24) return (IChonkyAttributes.AttributeType.BRAIN, 2);
if (_id == 25) return (IChonkyAttributes.AttributeType.WICKED, 7);
if (_id == 26) return (IChonkyAttributes.AttributeType.WICKED, 4);
if (_id == 27) return (IChonkyAttributes.AttributeType.POWER, 5);
if (_id == 28) return (IChonkyAttributes.AttributeType.POWER, 10);
if (_id == 29) return (IChonkyAttributes.AttributeType.WICKED, 6);
if (_id == 30) return (IChonkyAttributes.AttributeType.WICKED, 6);
if (_id == 31) return (IChonkyAttributes.AttributeType.CUTE, 6);
if (_id == 32) return (IChonkyAttributes.AttributeType.POWER, 1);
if (_id == 33) return (IChonkyAttributes.AttributeType.CUTE, 9);
if (_id == 34) return (IChonkyAttributes.AttributeType.BRAIN, 7);
if (_id == 35) return (IChonkyAttributes.AttributeType.WICKED, 5);
if (_id == 36) return (IChonkyAttributes.AttributeType.CUTE, 3);
if (_id == 37) return (IChonkyAttributes.AttributeType.POWER, 3);
if (_id == 38) return (IChonkyAttributes.AttributeType.BRAIN, 5);
if (_id == 39) return (IChonkyAttributes.AttributeType.WICKED, 5);
if (_id == 40) return (IChonkyAttributes.AttributeType.WICKED, 8);
if (_id == 41) return (IChonkyAttributes.AttributeType.CUTE, 1);
if (_id == 42) return (IChonkyAttributes.AttributeType.WICKED, 4);
if (_id == 43) return (IChonkyAttributes.AttributeType.BRAIN, 7);
if (_id == 44) return (IChonkyAttributes.AttributeType.CUTE, 9);
if (_id == 45) return (IChonkyAttributes.AttributeType.BRAIN, 4);
if (_id == 46) return (IChonkyAttributes.AttributeType.POWER, 6);
if (_id == 47) return (IChonkyAttributes.AttributeType.BRAIN, 5);
if (_id == 48) return (IChonkyAttributes.AttributeType.POWER, 9);
if (_id == 49) return (IChonkyAttributes.AttributeType.CUTE, 3);
if (_id == 50) return (IChonkyAttributes.AttributeType.CUTE, 4);
if (_id == 51) return (IChonkyAttributes.AttributeType.WICKED, 1);
if (_id == 52) return (IChonkyAttributes.AttributeType.BRAIN, 3);
if (_id == 53) return (IChonkyAttributes.AttributeType.WICKED, 8);
if (_id == 54) return (IChonkyAttributes.AttributeType.CUTE, 2);
if (_id == 55) return (IChonkyAttributes.AttributeType.POWER, 4);
if (_id == 56) return (IChonkyAttributes.AttributeType.WICKED, 3);
if (_id == 57) return (IChonkyAttributes.AttributeType.POWER, 8);
if (_id == 58) return (IChonkyAttributes.AttributeType.CUTE, 8);
if (_id == 59) return (IChonkyAttributes.AttributeType.CUTE, 7);
if (_id == 60) return (IChonkyAttributes.AttributeType.POWER, 2);
if (_id == 61) return (IChonkyAttributes.AttributeType.CUTE, 4);
if (_id == 62) return (IChonkyAttributes.AttributeType.BRAIN, 1);
if (_id == 63) return (IChonkyAttributes.AttributeType.POWER, 8);
if (_id == 64) return (IChonkyAttributes.AttributeType.CUTE, 2);
if (_id == 65) return (IChonkyAttributes.AttributeType.CUTE, 4);
if (_id == 66) return (IChonkyAttributes.AttributeType.CUTE, 3);
if (_id == 67) return (IChonkyAttributes.AttributeType.WICKED, 3);
if (_id == 68) return (IChonkyAttributes.AttributeType.BRAIN, 6);
if (_id == 69) return (IChonkyAttributes.AttributeType.POWER, 8);
if (_id == 70) return (IChonkyAttributes.AttributeType.WICKED, 8);
if (_id == 71) return (IChonkyAttributes.AttributeType.WICKED, 2);
if (_id == 72) return (IChonkyAttributes.AttributeType.POWER, 3);
if (_id == 73) return (IChonkyAttributes.AttributeType.CUTE, 1);
if (_id == 74) return (IChonkyAttributes.AttributeType.BRAIN, 2);
if (_id == 75) return (IChonkyAttributes.AttributeType.CUTE, 10);
if (_id == 76) return (IChonkyAttributes.AttributeType.CUTE, 9);
if (_id == 77) return (IChonkyAttributes.AttributeType.CUTE, 1);
if (_id == 78) return (IChonkyAttributes.AttributeType.CUTE, 2);
if (_id == 79) return (IChonkyAttributes.AttributeType.WICKED, 3);
if (_id == 80) return (IChonkyAttributes.AttributeType.BRAIN, 3);
if (_id == 81) return (IChonkyAttributes.AttributeType.BRAIN, 10);
if (_id == 82) return (IChonkyAttributes.AttributeType.POWER, 9);
if (_id == 83) return (IChonkyAttributes.AttributeType.POWER, 8);
if (_id == 84) return (IChonkyAttributes.AttributeType.BRAIN, 8);
if (_id == 85) return (IChonkyAttributes.AttributeType.POWER, 6);
if (_id == 86) return (IChonkyAttributes.AttributeType.POWER, 7);
if (_id == 87) return (IChonkyAttributes.AttributeType.BRAIN, 9);
if (_id == 88) return (IChonkyAttributes.AttributeType.CUTE, 6);
if (_id == 89) return (IChonkyAttributes.AttributeType.POWER, 7);
if (_id == 90) return (IChonkyAttributes.AttributeType.CUTE, 4);
if (_id == 91) return (IChonkyAttributes.AttributeType.BRAIN, 3);
if (_id == 92) return (IChonkyAttributes.AttributeType.BRAIN, 2);
if (_id == 93) return (IChonkyAttributes.AttributeType.POWER, 9);
if (_id == 94) return (IChonkyAttributes.AttributeType.POWER, 4);
if (_id == 95) return (IChonkyAttributes.AttributeType.CUTE, 10);
if (_id == 96) return (IChonkyAttributes.AttributeType.POWER, 2);
return (IChonkyAttributes.AttributeType.NONE, 0);
}
function _getWingsAttribute(uint256 _id)
internal
pure
returns (IChonkyAttributes.AttributeType, uint256)
{
if (_id == 0) return (IChonkyAttributes.AttributeType.NONE, 0);
if (_id == 1) return (IChonkyAttributes.AttributeType.CUTE, 6);
if (_id == 2) return (IChonkyAttributes.AttributeType.WICKED, 8);
if (_id == 3) return (IChonkyAttributes.AttributeType.CUTE, 4);
if (_id == 4) return (IChonkyAttributes.AttributeType.POWER, 9);
if (_id == 5) return (IChonkyAttributes.AttributeType.WICKED, 4);
if (_id == 6) return (IChonkyAttributes.AttributeType.POWER, 4);
if (_id == 7) return (IChonkyAttributes.AttributeType.CUTE, 7);
if (_id == 8) return (IChonkyAttributes.AttributeType.BRAIN, 5);
if (_id == 9) return (IChonkyAttributes.AttributeType.BRAIN, 9);
return (IChonkyAttributes.AttributeType.NONE, 0);
}
function _getSetAttribute(uint256 _id)
internal
pure
returns (IChonkyAttributes.AttributeType, uint256)
{
if (_id == 0) return (IChonkyAttributes.AttributeType.NONE, 0);
if (_id == 1) return (IChonkyAttributes.AttributeType.POWER, 1);
if (_id == 2) return (IChonkyAttributes.AttributeType.CUTE, 3);
if (_id == 3) return (IChonkyAttributes.AttributeType.BRAIN, 5);
if (_id == 4) return (IChonkyAttributes.AttributeType.WICKED, 5);
if (_id == 5) return (IChonkyAttributes.AttributeType.CUTE, 5);
if (_id == 6) return (IChonkyAttributes.AttributeType.POWER, 5);
if (_id == 7) return (IChonkyAttributes.AttributeType.POWER, 3);
if (_id == 8) return (IChonkyAttributes.AttributeType.CUTE, 2);
if (_id == 9) return (IChonkyAttributes.AttributeType.BRAIN, 2);
if (_id == 10) return (IChonkyAttributes.AttributeType.POWER, 1);
if (_id == 11) return (IChonkyAttributes.AttributeType.BRAIN, 1);
if (_id == 12) return (IChonkyAttributes.AttributeType.WICKED, 5);
if (_id == 13) return (IChonkyAttributes.AttributeType.WICKED, 2);
if (_id == 14) return (IChonkyAttributes.AttributeType.POWER, 2);
if (_id == 15) return (IChonkyAttributes.AttributeType.BRAIN, 2);
if (_id == 16) return (IChonkyAttributes.AttributeType.BRAIN, 5);
if (_id == 17) return (IChonkyAttributes.AttributeType.BRAIN, 3);
if (_id == 18) return (IChonkyAttributes.AttributeType.BRAIN, 5);
if (_id == 19) return (IChonkyAttributes.AttributeType.WICKED, 1);
if (_id == 20) return (IChonkyAttributes.AttributeType.WICKED, 3);
if (_id == 21) return (IChonkyAttributes.AttributeType.CUTE, 5);
if (_id == 22) return (IChonkyAttributes.AttributeType.CUTE, 1);
if (_id == 23) return (IChonkyAttributes.AttributeType.WICKED, 3);
if (_id == 24) return (IChonkyAttributes.AttributeType.POWER, 2);
if (_id == 25) return (IChonkyAttributes.AttributeType.POWER, 2);
if (_id == 26) return (IChonkyAttributes.AttributeType.POWER, 1);
if (_id == 27) return (IChonkyAttributes.AttributeType.WICKED, 2);
if (_id == 28) return (IChonkyAttributes.AttributeType.CUTE, 2);
if (_id == 29) return (IChonkyAttributes.AttributeType.CUTE, 3);
if (_id == 30) return (IChonkyAttributes.AttributeType.POWER, 5);
if (_id == 31) return (IChonkyAttributes.AttributeType.WICKED, 3);
if (_id == 32) return (IChonkyAttributes.AttributeType.POWER, 2);
if (_id == 33) return (IChonkyAttributes.AttributeType.BRAIN, 5);
if (_id == 34) return (IChonkyAttributes.AttributeType.WICKED, 3);
if (_id == 35) return (IChonkyAttributes.AttributeType.CUTE, 1);
if (_id == 36) return (IChonkyAttributes.AttributeType.POWER, 1);
if (_id == 37) return (IChonkyAttributes.AttributeType.POWER, 5);
if (_id == 38) return (IChonkyAttributes.AttributeType.POWER, 5);
if (_id == 39) return (IChonkyAttributes.AttributeType.WICKED, 5);
if (_id == 40) return (IChonkyAttributes.AttributeType.CUTE, 5);
if (_id == 41) return (IChonkyAttributes.AttributeType.POWER, 3);
if (_id == 42) return (IChonkyAttributes.AttributeType.CUTE, 3);
if (_id == 43) return (IChonkyAttributes.AttributeType.POWER, 3);
if (_id == 44) return (IChonkyAttributes.AttributeType.POWER, 3);
if (_id == 45) return (IChonkyAttributes.AttributeType.BRAIN, 5);
if (_id == 46) return (IChonkyAttributes.AttributeType.CUTE, 3);
if (_id == 47) return (IChonkyAttributes.AttributeType.POWER, 5);
if (_id == 48) return (IChonkyAttributes.AttributeType.POWER, 2);
if (_id == 49) return (IChonkyAttributes.AttributeType.BRAIN, 5);
if (_id == 50) return (IChonkyAttributes.AttributeType.CUTE, 3);
if (_id == 51) return (IChonkyAttributes.AttributeType.CUTE, 1);
if (_id == 52) return (IChonkyAttributes.AttributeType.POWER, 3);
if (_id == 53) return (IChonkyAttributes.AttributeType.CUTE, 1);
if (_id == 54) return (IChonkyAttributes.AttributeType.BRAIN, 3);
if (_id == 55) return (IChonkyAttributes.AttributeType.POWER, 3);
if (_id == 56) return (IChonkyAttributes.AttributeType.POWER, 2);
if (_id == 57) return (IChonkyAttributes.AttributeType.WICKED, 3);
if (_id == 58) return (IChonkyAttributes.AttributeType.CUTE, 0);
return (IChonkyAttributes.AttributeType.NONE, 0);
}
function _addAttributeValue(
uint256[4] memory _array,
uint256 _value,
IChonkyAttributes.AttributeType _valueType
) internal pure returns (uint256[4] memory) {
if (_valueType != IChonkyAttributes.AttributeType.NONE) {
_array[uint256(_valueType) - 1] += _value;
}
return _array;
}
function getAttributeValues(uint256[12] memory _attributes, uint256 _setId)
public
pure
returns (uint256[4] memory result)
{
uint256 value;
IChonkyAttributes.AttributeType valueType;
(valueType, value) = _getWingsAttribute(_attributes[2]);
result = _addAttributeValue(result, value, valueType);
(valueType, value) = _getBodyAttribute(_attributes[6]);
result = _addAttributeValue(result, value, valueType);
(valueType, value) = _getMouthAttribute(_attributes[7]);
result = _addAttributeValue(result, value, valueType);
(valueType, value) = _getEyesAttribute(_attributes[8]);
result = _addAttributeValue(result, value, valueType);
(valueType, value) = _getHatAttribute(_attributes[9]);
result = _addAttributeValue(result, value, valueType);
(valueType, value) = _getSetAttribute(_setId);
result = _addAttributeValue(result, value, valueType);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {IChonkySet} from "./interface/IChonkySet.sol";
contract ChonkySet is IChonkySet {
function getSetId(uint256 _genome) external pure returns (uint256) {
return _getSetId(_genome);
}
function getSetFromGenome(uint256 _genome)
external
pure
returns (string memory)
{
return _getSetFromId(_getSetId(_genome));
}
function getSetFromId(uint256 _setId)
external
pure
returns (string memory)
{
return _getSetFromId(_setId);
}
function _getSetId(uint256 _genome) internal pure returns (uint256) {
if (_genome == 0x025e716c06d02c) return 1;
if (_genome == 0x02c8cca802518f) return 2;
if (_genome == 0x38e108027089) return 3;
if (_genome == 0x51ad0c0d7065) return 4;
if (_genome == 0x704e0ea50332) return 5;
if (_genome == 0xec821004d052) return 6;
if (_genome == 0x0398a060045048) return 7;
if (_genome == 0x05836b2008d04c) return 8;
if (_genome == 0x016daf22043029) return 9;
if (_genome == 0x635b242d4063) return 10;
if (_genome == 0x018ac826022089) return 11;
if (_genome == 0x035edd5c064089) return 12;
if (_genome == 0x0190002a000049) return 13;
if (_genome == 0x01bcda2e0e8083) return 14;
if (_genome == 0x028e4d4608d068) return 15;
if (_genome == 0x0402a45842e02c) return 16;
if (_genome == 0x04f16530657022) return 17;
if (_genome == 0x013bd48e40f02e) return 18;
if (_genome == 0xf15712212084) return 19;
if (_genome == 0x01de0966016582) return 20;
if (_genome == 0x03b39e3407208f) return 21;
if (_genome == 0x0228cc3608304a) return 22;
if (_genome == 0x01eb7338017065) return 23;
if (_genome == 0x055e587a084032) return 24;
if (_genome == 0x04a81aa20e3029) return 25;
if (_genome == 0x8dca3a044022) return 26;
if (_genome == 0x01504f2c07006c) return 27;
if (_genome == 0x02d6224c10304a) return 28;
if (_genome == 0x012d101e0b2084) return 29;
if (_genome == 0x01c7954e028086) return 30;
if (_genome == 0x251906042067) return 31;
if (_genome == 0x059e125704d065) return 32;
if (_genome == 0x0510008c000049) return 33;
if (_genome == 0x038974520c408b) return 34;
if (_genome == 0x0326df280cd086) return 35;
if (_genome == 0x03ca296204d050) return 36;
if (_genome == 0x03ff216a058092) return 37;
if (_genome == 0x04545a76104062) return 38;
if (_genome == 0x046a8078041067) return 39;
if (_genome == 0x04b6d18200508f) return 40;
if (_genome == 0x030ca68808d042) return 41;
if (_genome == 0x168502c5802f) return 42;
if (_genome == 0x052e28920ea089) return 43;
if (_genome == 0x05380894022085) return 44;
if (_genome == 0x054cea9808d023) return 45;
if (_genome == 0x02ea56160eb08a) return 46;
if (_genome == 0x0560009e02a082) return 47;
if (_genome == 0x023f63680b0090) return 48;
if (_genome == 0x057d6ca0044983) return 49;
if (_genome == 0x01fc6ba6aa502d) return 50;
if (_genome == 0x031b320a00104b) return 51;
if (_genome == 0x05bd27480ea089) return 52;
if (_genome == 0x40db5e110028) return 53;
if (_genome == 0x02b157aa0eb021) return 54;
if (_genome == 0x05dae8aca25192) return 55;
if (_genome == 0x05e568ae048023) return 56;
if (_genome == 0x011875b6129067) return 57;
return 0;
}
function _getSetFromId(uint256 _id) internal pure returns (string memory) {
if (_id == 1) return "American Football";
if (_id == 2) return "Angel";
if (_id == 3) return "Astronaut";
if (_id == 4) return "Baron Samedi";
if (_id == 5) return "Bee";
if (_id == 6) return "Black Kabuto";
if (_id == 7) return "Blue Ninja";
if (_id == 8) return "Bubble Tea";
if (_id == 9) return "Captain";
if (_id == 10) return "Caveman";
if (_id == 11) return "Chef";
if (_id == 12) return "Chonky Plant";
if (_id == 13) return "Cloth Monster";
if (_id == 14) return "Cowboy";
if (_id == 15) return "Crazy Scientist";
if (_id == 16) return "Cyber Hacker";
if (_id == 17) return "Cyberpunk";
if (_id == 18) return "Cyborg";
if (_id == 19) return "Dark Magician";
if (_id == 20) return "Devil";
if (_id == 21) return "Diver";
if (_id == 22) return "Doraemon";
if (_id == 23) return "Dracula";
if (_id == 24) return "Ese Sombrero";
if (_id == 25) return "Gentleman";
if (_id == 26) return "Golden Tooth";
if (_id == 27) return "Jack-O-Lantern";
if (_id == 28) return "Japanese Drummer";
if (_id == 29) return "Jester";
if (_id == 30) return "King";
if (_id == 31) return "Lake Monster";
if (_id == 32) return "Luffy";
if (_id == 33) return "Mr Roboto";
if (_id == 34) return "Mushroom Guy";
if (_id == 35) return "New Year Outfit";
if (_id == 36) return "Old Lady";
if (_id == 37) return "Pharaoh";
if (_id == 38) return "Pirate";
if (_id == 39) return "Plague Doctor";
if (_id == 40) return "Rainbow Love";
if (_id == 41) return "Red Samurai";
if (_id == 42) return "Retro";
if (_id == 43) return "Roman";
if (_id == 44) return "Safari Hunter";
if (_id == 45) return "Sherlock";
if (_id == 46) return "Snow Dude";
if (_id == 47) return "Sparta";
if (_id == 48) return "Spicy Man";
if (_id == 49) return "Steampunk";
if (_id == 50) return "Swimmer";
if (_id == 51) return "Tanuki";
if (_id == 52) return "Tin Man";
if (_id == 53) return "Tired Dad";
if (_id == 54) return "Tron Boy";
if (_id == 55) return "Valkyrie";
if (_id == 56) return "Viking";
if (_id == 57) return "Zombie";
return "";
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IChonkyMetadata {
function buildTokenURI(
uint256 id,
uint256 genomeId,
uint256 genome,
string memory CID,
address chonkySet,
address chonkyAttributes
) external pure returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IChonkySet {
function getSetId(uint256 _genome) external pure returns (uint256);
function getSetFromGenome(uint256 _genome)
external
pure
returns (string memory);
function getSetFromId(uint256 _setId) external pure returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IChonkyAttributes {
enum AttributeType {
NONE,
BRAIN,
CUTE,
POWER,
WICKED
}
function getAttributeValues(uint256[12] memory _attributes, uint256 _setId)
external
pure
returns (uint256[4] memory result);
} | * @inheritdoc IERC721/ | function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public payable override {
safeTransferFrom(from, to, tokenId, '');
}
| 73,654 | [
1,
36,
10093,
467,
654,
39,
27,
5340,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
4183,
5912,
1265,
12,
203,
3639,
1758,
628,
16,
203,
3639,
1758,
358,
16,
203,
3639,
2254,
5034,
1147,
548,
203,
565,
262,
1071,
8843,
429,
3849,
288,
203,
3639,
4183,
5912,
1265,
12,
2080,
16,
358,
16,
1147,
548,
16,
23489,
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
] |
/**
*Submitted for verification at Etherscan.io on 2021-05-15
*/
// File: contracts/zeppelin/SafeMath.sol
pragma solidity 0.4.24;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @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 Multiplies two unsigned integers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
}
// File: contracts/AuVImplementation.sol
pragma solidity 0.4.24;
pragma experimental "v0.5.0";
/**
* @title AuVImplementation
* @dev this contract is a Pausable ERC20 token with Burn and Mint
* controlled by a central SupplyController. By implementing AuVImplementation
* this contract also includes external methods for setting
* a new implementation contract for the Proxy.
* NOTE: The storage defined here will actually be held in the Proxy
* contract and all calls to this contract should be made through
* the proxy, including admin actions done as owner or supplyController.
* Any call to transfer against this contract should fail
* with insufficient funds since no tokens will be issued there.
*/
contract AuVImplementation {
/**
* MATH
*/
using SafeMath for uint256;
/**
* DATA
*/
// INITIALIZATION DATA
bool private initialized = false;
// ERC20 BASIC DATA
mapping(address => uint256) internal balances;
uint256 internal totalSupply_;
string public constant name = "VIIIDA Gold"; // solium-disable-line
string public constant symbol = "AuV"; // solium-disable-line uppercase
uint8 public constant decimals = 18; // solium-disable-line uppercase
// ERC20 DATA
mapping(address => mapping(address => uint256)) internal allowed;
// OWNER DATA
address public owner;
address public proposedOwner;
// PAUSABILITY DATA
bool public paused = false;
// ASSET PROTECTION DATA
address public assetProtectionRole;
mapping(address => bool) internal frozen;
// SUPPLY CONTROL DATA
address public supplyController;
// DELEGATED TRANSFER DATA
address public betaDelegateWhitelister;
mapping(address => bool) internal betaDelegateWhitelist;
mapping(address => uint256) internal nextSeqs;
// EIP191 header for EIP712 prefix
string constant internal EIP191_HEADER = "\x19\x01";
// Hash of the EIP712 Domain Separator Schema
bytes32 constant internal EIP712_DOMAIN_SEPARATOR_SCHEMA_HASH = keccak256(
"EIP712Domain(string name,address verifyingContract)"
);
bytes32 constant internal EIP712_DELEGATED_TRANSFER_SCHEMA_HASH = keccak256(
"BetaDelegatedTransfer(address to,uint256 value,uint256 serviceFee,uint256 seq,uint256 deadline)"
);
// Hash of the EIP712 Domain Separator data
// solhint-disable-next-line var-name-mixedcase
bytes32 public EIP712_DOMAIN_HASH;
// FEE CONTROLLER DATA
// fee decimals is only set for informational purposes.
// 1 feeRate = .000001 oz of gold
uint8 public constant feeDecimals = 6;
// feeRate is measured in 100th of a basis point (parts per 1,000,000)
// ex: a fee rate of 200 = 0.02% of an oz of gold
uint256 public constant feeParts = 1000000;
uint256 public feeRate;
address public feeController;
address public feeRecipient;
/**
* EVENTS
*/
// ERC20 BASIC EVENTS
event Transfer(address indexed from, address indexed to, uint256 value);
// ERC20 EVENTS
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
// OWNABLE EVENTS
event OwnershipTransferProposed(
address indexed currentOwner,
address indexed proposedOwner
);
event OwnershipTransferDisregarded(
address indexed oldProposedOwner
);
event OwnershipTransferred(
address indexed oldOwner,
address indexed newOwner
);
// PAUSABLE EVENTS
event Pause();
event Unpause();
// ASSET PROTECTION EVENTS
event AddressFrozen(address indexed addr);
event AddressUnfrozen(address indexed addr);
event FrozenAddressWiped(address indexed addr);
event AssetProtectionRoleSet (
address indexed oldAssetProtectionRole,
address indexed newAssetProtectionRole
);
// SUPPLY CONTROL EVENTS
event SupplyIncreased(address indexed to, uint256 value);
event SupplyDecreased(address indexed from, uint256 value);
event SupplyControllerSet(
address indexed oldSupplyController,
address indexed newSupplyController
);
// DELEGATED TRANSFER EVENTS
event BetaDelegatedTransfer(
address indexed from, address indexed to, uint256 value, uint256 seq, uint256 serviceFee
);
event BetaDelegateWhitelisterSet(
address indexed oldWhitelister,
address indexed newWhitelister
);
event BetaDelegateWhitelisted(address indexed newDelegate);
event BetaDelegateUnwhitelisted(address indexed oldDelegate);
// FEE CONTROLLER EVENTS
event FeeCollected(address indexed from, address indexed to, uint256 value);
event FeeRateSet(
uint256 indexed oldFeeRate,
uint256 indexed newFeeRate
);
event FeeControllerSet(
address indexed oldFeeController,
address indexed newFeeController
);
event FeeRecipientSet(
address indexed oldFeeRecipient,
address indexed newFeeRecipient
);
/**
* FUNCTIONALITY
*/
// INITIALIZATION FUNCTIONALITY
/**
* @dev sets 0 initial tokens, the owner, the supplyController,
* the fee controller and fee recipient.
* this serves as the constructor for the proxy but compiles to the
* memory model of the Implementation contract.
*/
function initialize() public {
require(!initialized, "already initialized");
owner = msg.sender;
proposedOwner = address(0);
assetProtectionRole = address(0);
totalSupply_ = 0;
supplyController = msg.sender;
feeRate = 0;
feeController = msg.sender;
feeRecipient = msg.sender;
initializeDomainSeparator();
initialized = true;
}
/**
* The constructor is used here to ensure that the implementation
* contract is initialized. An uncontrolled implementation
* contract might lead to misleading state
* for users who accidentally interact with it.
*/
constructor() public {
initialize();
pause();
}
/**
* @dev To be called when upgrading the contract using upgradeAndCall to add delegated transfers
*/
function initializeDomainSeparator() public {
// hash the name context with the contract address
EIP712_DOMAIN_HASH = keccak256(abi.encodePacked(// solium-disable-line
EIP712_DOMAIN_SEPARATOR_SCHEMA_HASH,
keccak256(bytes(name)),
bytes32(address(this))
));
}
// ERC20 BASIC FUNCTIONALITY
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev Transfer token to a specified address from msg.sender
* Transfer additionally sends the fee to the fee controller
* Note: the use of Safemath ensures that _value is nonnegative.
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public whenNotPaused returns (bool) {
require(_to != address(0), "cannot transfer to address zero");
require(!frozen[_to] && !frozen[msg.sender], "address frozen");
require(_value <= balances[msg.sender], "insufficient funds");
_transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _addr The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _addr) public view returns (uint256) {
return balances[_addr];
}
// ERC20 FUNCTIONALITY
/**
* @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
whenNotPaused
returns (bool)
{
require(_to != address(0), "cannot transfer to address zero");
require(!frozen[_to] && !frozen[_from] && !frozen[msg.sender], "address frozen");
require(_value <= balances[_from], "insufficient funds");
require(_value <= allowed[_from][msg.sender], "insufficient allowance");
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 whenNotPaused returns (bool) {
require(!frozen[_spender] && !frozen[msg.sender], "address frozen");
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];
}
function _transfer(address _from, address _to, uint256 _value) internal returns (uint256) {
uint256 _fee = getFeeFor(_value);
uint256 _principle = _value.sub(_fee);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_principle);
emit Transfer(_from, _to, _principle);
emit Transfer(_from, feeRecipient, _fee);
if (_fee > 0) {
balances[feeRecipient] = balances[feeRecipient].add(_fee);
emit FeeCollected(_from, feeRecipient, _fee);
}
return _principle;
}
// OWNER FUNCTIONALITY
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner, "onlyOwner");
_;
}
/**
* @dev Allows the current owner to begin transferring control of the contract to a proposedOwner
* @param _proposedOwner The address to transfer ownership to.
*/
function proposeOwner(address _proposedOwner) public onlyOwner {
require(_proposedOwner != address(0), "cannot transfer ownership to address zero");
require(msg.sender != _proposedOwner, "caller already is owner");
proposedOwner = _proposedOwner;
emit OwnershipTransferProposed(owner, proposedOwner);
}
/**
* @dev Allows the current owner or proposed owner to cancel transferring control of the contract to a proposedOwner
*/
function disregardProposeOwner() public {
require(msg.sender == proposedOwner || msg.sender == owner, "only proposedOwner or owner");
require(proposedOwner != address(0), "can only disregard a proposed owner that was previously set");
address _oldProposedOwner = proposedOwner;
proposedOwner = address(0);
emit OwnershipTransferDisregarded(_oldProposedOwner);
}
/**
* @dev Allows the proposed owner to complete transferring control of the contract to the proposedOwner.
*/
function claimOwnership() public {
require(msg.sender == proposedOwner, "onlyProposedOwner");
address _oldOwner = owner;
owner = proposedOwner;
proposedOwner = address(0);
emit OwnershipTransferred(_oldOwner, owner);
}
/**
* @dev Reclaim all AuV at the contract address.
* This sends the AuV tokens that this contract add holding to the owner.
* Note: this is not affected by freeze constraints.
*/
function reclaimAuV() external onlyOwner {
uint256 _balance = balances[this];
balances[this] = 0;
balances[owner] = balances[owner].add(_balance);
emit Transfer(this, owner, _balance);
}
// PAUSABILITY FUNCTIONALITY
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused, "whenNotPaused");
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() public onlyOwner {
require(!paused, "already paused");
paused = true;
emit Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() public onlyOwner {
require(paused, "already unpaused");
paused = false;
emit Unpause();
}
// ASSET PROTECTION FUNCTIONALITY
/**
* @dev Sets a new asset protection role address.
* @param _newAssetProtectionRole The new address allowed to freeze/unfreeze addresses and seize their tokens.
*/
function setAssetProtectionRole(address _newAssetProtectionRole) public {
require(msg.sender == assetProtectionRole || msg.sender == owner, "only assetProtectionRole or Owner");
emit AssetProtectionRoleSet(assetProtectionRole, _newAssetProtectionRole);
assetProtectionRole = _newAssetProtectionRole;
}
modifier onlyAssetProtectionRole() {
require(msg.sender == assetProtectionRole, "onlyAssetProtectionRole");
_;
}
/**
* @dev Freezes an address balance from being transferred.
* @param _addr The new address to freeze.
*/
function freeze(address _addr) public onlyAssetProtectionRole {
require(!frozen[_addr], "address already frozen");
frozen[_addr] = true;
emit AddressFrozen(_addr);
}
/**
* @dev Unfreezes an address balance allowing transfer.
* @param _addr The new address to unfreeze.
*/
function unfreeze(address _addr) public onlyAssetProtectionRole {
require(frozen[_addr], "address already unfrozen");
frozen[_addr] = false;
emit AddressUnfrozen(_addr);
}
/**
* @dev Wipes the balance of a frozen address, burning the tokens
* and setting the approval to zero.
* @param _addr The new frozen address to wipe.
*/
function wipeFrozenAddress(address _addr) public onlyAssetProtectionRole {
require(frozen[_addr], "address is not frozen");
uint256 _balance = balances[_addr];
balances[_addr] = 0;
totalSupply_ = totalSupply_.sub(_balance);
emit FrozenAddressWiped(_addr);
emit SupplyDecreased(_addr, _balance);
emit Transfer(_addr, address(0), _balance);
}
/**
* @dev Gets whether the address is currently frozen.
* @param _addr The address to check if frozen.
* @return A bool representing whether the given address is frozen.
*/
function isFrozen(address _addr) public view returns (bool) {
return frozen[_addr];
}
// SUPPLY CONTROL FUNCTIONALITY
/**
* @dev Sets a new supply controller address.
* @param _newSupplyController The address allowed to burn/mint tokens to control supply.
*/
function setSupplyController(address _newSupplyController) public {
require(msg.sender == supplyController || msg.sender == owner, "only SupplyController or Owner");
require(_newSupplyController != address(0), "cannot set supply controller to address zero");
emit SupplyControllerSet(supplyController, _newSupplyController);
supplyController = _newSupplyController;
}
modifier onlySupplyController() {
require(msg.sender == supplyController, "onlySupplyController");
_;
}
/**
* @dev Increases the total supply by minting the specified number of tokens to the supply controller account.
* @param _value The number of tokens to add.
* @return A boolean that indicates if the operation was successful.
*/
function increaseSupply(uint256 _value) public onlySupplyController returns (bool success) {
totalSupply_ = totalSupply_.add(_value);
balances[supplyController] = balances[supplyController].add(_value);
emit SupplyIncreased(supplyController, _value);
emit Transfer(address(0), supplyController, _value);
return true;
}
/**
* @dev Decreases the total supply by burning the specified number of tokens from the supply controller account.
* @param _value The number of tokens to remove.
* @return A boolean that indicates if the operation was successful.
*/
function decreaseSupply(uint256 _value) public onlySupplyController returns (bool success) {
require(_value <= balances[supplyController], "not enough supply");
balances[supplyController] = balances[supplyController].sub(_value);
totalSupply_ = totalSupply_.sub(_value);
emit SupplyDecreased(supplyController, _value);
emit Transfer(supplyController, address(0), _value);
return true;
}
// DELEGATED TRANSFER FUNCTIONALITY
/**
* @dev returns the next seq for a target address.
* The transactor must submit nextSeqOf(transactor) in the next transaction for it to be valid.
* Note: that the seq context is specific to this smart contract.
* @param target The target address.
* @return the seq.
*/
//
function nextSeqOf(address target) public view returns (uint256) {
return nextSeqs[target];
}
/**
* @dev Performs a transfer on behalf of the from address, identified by its signature on the delegatedTransfer msg.
* Splits a signature byte array into r,s,v for convenience.
* @param sig the signature of the delgatedTransfer msg.
* @param to The address to transfer to.
* @param value The amount to be transferred.
* @param serviceFee an optional ERC20 service fee paid to the executor of betaDelegatedTransfer by the from address.
* @param seq a sequencing number included by the from address specific to this contract to protect from replays.
* @param deadline a block number after which the pre-signed transaction has expired.
* @return A boolean that indicates if the operation was successful.
*/
function betaDelegatedTransfer(
bytes sig, address to, uint256 value, uint256 serviceFee, uint256 seq, uint256 deadline
) public returns (bool) {
require(sig.length == 65, "signature should have length 65");
bytes32 r;
bytes32 s;
uint8 v;
assembly {
r := mload(add(sig, 32))
s := mload(add(sig, 64))
v := byte(0, mload(add(sig, 96)))
}
require(_betaDelegatedTransfer(r, s, v, to, value, serviceFee, seq, deadline), "failed transfer");
return true;
}
/**
* @dev Performs a transfer on behalf of the from address, identified by its signature on the betaDelegatedTransfer msg.
* Note: both the delegate and transactor sign in the service fees. The transactor, however,
* has no control over the gas price, and therefore no control over the transaction time.
* Beta prefix chosen to avoid a name clash with an emerging standard in ERC865 or elsewhere.
* Internal to the contract - see betaDelegatedTransfer and betaDelegatedTransferBatch.
* @param r the r signature of the delgatedTransfer msg.
* @param s the s signature of the delgatedTransfer msg.
* @param v the v signature of the delgatedTransfer msg.
* @param to The address to transfer to.
* @param value The amount to be transferred.
* @param serviceFee an optional ERC20 service fee paid to the delegate of betaDelegatedTransfer by the from address.
* @param seq a sequencing number included by the from address specific to this contract to protect from replays.
* @param deadline a block number after which the pre-signed transaction has expired.
* @return A boolean that indicates if the operation was successful.
*/
function _betaDelegatedTransfer(
bytes32 r, bytes32 s, uint8 v, address to, uint256 value, uint256 serviceFee, uint256 seq, uint256 deadline
) internal whenNotPaused returns (bool) {
require(betaDelegateWhitelist[msg.sender], "Beta feature only accepts whitelisted delegates");
require(value > 0 || serviceFee > 0, "cannot transfer zero tokens with zero service fee");
require(block.number <= deadline, "transaction expired");
// prevent sig malleability from ecrecover()
require(uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "signature incorrect");
require(v == 27 || v == 28, "signature incorrect");
// EIP712 scheme: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-712.md
bytes32 hash = keccak256(abi.encodePacked(EIP191_HEADER, EIP712_DOMAIN_HASH, keccak256(abi.encodePacked(// solium-disable-line
EIP712_DELEGATED_TRANSFER_SCHEMA_HASH, bytes32(to), value, serviceFee, seq, deadline
))));
address _from = ecrecover(hash, v, r, s);
require(_from != address(0), "error determining from address from signature");
require(to != address(0), "cannot use address zero");
require(!frozen[to] && !frozen[_from] && !frozen[msg.sender], "address frozen");
require(value.add(serviceFee) <= balances[_from], "insufficient funds or bad signature");
require(nextSeqs[_from] == seq, "incorrect seq");
nextSeqs[_from] = nextSeqs[_from].add(1);
uint256 _principle = _transfer(_from, to, value);
if (serviceFee != 0) {
balances[_from] = balances[_from].sub(serviceFee);
balances[msg.sender] = balances[msg.sender].add(serviceFee);
emit Transfer(_from, msg.sender, serviceFee);
}
emit BetaDelegatedTransfer(_from, to, _principle, seq, serviceFee);
return true;
}
/**
* @dev Performs an atomic batch of transfers on behalf of the from addresses, identified by their signatures.
* Lack of nested array support in arguments requires all arguments to be passed as equal size arrays where
* delegated transfer number i is the combination of all arguments at index i
* @param r the r signatures of the delgatedTransfer msg.
* @param s the s signatures of the delgatedTransfer msg.
* @param v the v signatures of the delgatedTransfer msg.
* @param to The addresses to transfer to.
* @param value The amounts to be transferred.
* @param serviceFee optional ERC20 service fees paid to the delegate of betaDelegatedTransfer by the from address.
* @param seq sequencing numbers included by the from address specific to this contract to protect from replays.
* @param deadline block numbers after which the pre-signed transactions have expired.
* @return A boolean that indicates if the operation was successful.
*/
function betaDelegatedTransferBatch(
bytes32[] r, bytes32[] s, uint8[] v, address[] to, uint256[] value, uint256[] serviceFee, uint256[] seq, uint256[] deadline
) public returns (bool) {
require(r.length == s.length && r.length == v.length && r.length == to.length && r.length == value.length, "length mismatch");
require(r.length == serviceFee.length && r.length == seq.length && r.length == deadline.length, "length mismatch");
for (uint i = 0; i < r.length; i++) {
require(
_betaDelegatedTransfer(r[i], s[i], v[i], to[i], value[i], serviceFee[i], seq[i], deadline[i]),
"failed transfer"
);
}
return true;
}
/**
* @dev Gets whether the address is currently whitelisted for betaDelegateTransfer.
* @param _addr The address to check if whitelisted.
* @return A bool representing whether the given address is whitelisted.
*/
function isWhitelistedBetaDelegate(address _addr) public view returns (bool) {
return betaDelegateWhitelist[_addr];
}
/**
* @dev Sets a new betaDelegate whitelister.
* @param _newWhitelister The address allowed to whitelist betaDelegates.
*/
function setBetaDelegateWhitelister(address _newWhitelister) public {
require(msg.sender == betaDelegateWhitelister || msg.sender == owner, "only Whitelister or Owner");
betaDelegateWhitelister = _newWhitelister;
emit BetaDelegateWhitelisterSet(betaDelegateWhitelister, _newWhitelister);
}
modifier onlyBetaDelegateWhitelister() {
require(msg.sender == betaDelegateWhitelister, "onlyBetaDelegateWhitelister");
_;
}
/**
* @dev Whitelists an address to allow calling BetaDelegatedTransfer.
* @param _addr The new address to whitelist.
*/
function whitelistBetaDelegate(address _addr) public onlyBetaDelegateWhitelister {
require(!betaDelegateWhitelist[_addr], "delegate already whitelisted");
betaDelegateWhitelist[_addr] = true;
emit BetaDelegateWhitelisted(_addr);
}
/**
* @dev Unwhitelists an address to disallow calling BetaDelegatedTransfer.
* @param _addr The new address to whitelist.
*/
function unwhitelistBetaDelegate(address _addr) public onlyBetaDelegateWhitelister {
require(betaDelegateWhitelist[_addr], "delegate not whitelisted");
betaDelegateWhitelist[_addr] = false;
emit BetaDelegateUnwhitelisted(_addr);
}
// FEE CONTROLLER FUNCTIONALITY
/**
* @dev Sets a new fee controller address.
* @param _newFeeController The address allowed to set the fee rate and the fee recipient.
*/
function setFeeController(address _newFeeController) public {
require(msg.sender == feeController || msg.sender == owner, "only FeeController or Owner");
require(_newFeeController != address(0), "cannot set fee controller to address zero");
address _oldFeeController = feeController;
feeController = _newFeeController;
emit FeeControllerSet(_oldFeeController, feeController);
}
modifier onlyFeeController() {
require(msg.sender == feeController, "only FeeController");
_;
}
/**
* @dev Sets a new fee recipient address.
* @param _newFeeRecipient The address allowed to collect transfer fees for transfers.
*/
function setFeeRecipient(address _newFeeRecipient) public onlyFeeController {
require(_newFeeRecipient != address(0), "cannot set fee recipient to address zero");
address _oldFeeRecipient = feeRecipient;
feeRecipient = _newFeeRecipient;
emit FeeRecipientSet(_oldFeeRecipient, feeRecipient);
}
/**
* @dev Sets a new fee rate.
* @param _newFeeRate The new fee rate to collect as transfer fees for transfers.
*/
function setFeeRate(uint256 _newFeeRate) public onlyFeeController {
require(_newFeeRate <= feeParts, "cannot set fee rate above 100%");
uint256 _oldFeeRate = feeRate;
feeRate = _newFeeRate;
emit FeeRateSet(_oldFeeRate, feeRate);
}
/**
* @dev Gets a fee for a given value
* ex: given feeRate = 200 and feeParts = 1,000,000 then getFeeFor(10000) = 2
* @param _value The amount to get the fee for.
*/
function getFeeFor(uint256 _value) public view returns (uint256) {
if (feeRate == 0) {
return 0;
}
return _value.mul(feeRate).div(feeParts);
}
} | * @dev sets 0 initial tokens, the owner, the supplyController, the fee controller and fee recipient. this serves as the constructor for the proxy but compiles to the memory model of the Implementation contract./ | function initialize() public {
require(!initialized, "already initialized");
owner = msg.sender;
proposedOwner = address(0);
assetProtectionRole = address(0);
totalSupply_ = 0;
supplyController = msg.sender;
feeRate = 0;
feeController = msg.sender;
feeRecipient = msg.sender;
initializeDomainSeparator();
initialized = true;
}
| 2,024,289 | [
1,
4424,
374,
2172,
2430,
16,
326,
3410,
16,
326,
14467,
2933,
16,
326,
14036,
2596,
471,
14036,
8027,
18,
333,
26255,
487,
326,
3885,
364,
326,
2889,
1496,
1161,
1449,
358,
326,
3778,
938,
434,
326,
25379,
6835,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
4046,
1435,
1071,
288,
203,
3639,
2583,
12,
5,
13227,
16,
315,
17583,
6454,
8863,
203,
3639,
3410,
273,
1234,
18,
15330,
31,
203,
3639,
20084,
5541,
273,
1758,
12,
20,
1769,
203,
3639,
3310,
16938,
2996,
273,
1758,
12,
20,
1769,
203,
3639,
2078,
3088,
1283,
67,
273,
374,
31,
203,
3639,
14467,
2933,
273,
1234,
18,
15330,
31,
203,
3639,
14036,
4727,
273,
374,
31,
203,
3639,
14036,
2933,
273,
1234,
18,
15330,
31,
203,
3639,
14036,
18241,
273,
1234,
18,
15330,
31,
203,
3639,
4046,
3748,
6581,
5621,
203,
3639,
6454,
273,
638,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0xF13e21653AEB763595D5E4baA1dC115689Da49b9/sources/contracts/thirdparty/proxies/Proxy.sol | * @dev Tells the address of the implementation where every call will be delegated. @return impl address of the implementation to which it will be delegated/ | receive() payable external {
_fallback();
}
| 4,025,231 | [
1,
21009,
87,
326,
1758,
434,
326,
4471,
1625,
3614,
745,
903,
506,
30055,
18,
327,
9380,
1758,
434,
326,
4471,
358,
1492,
518,
903,
506,
30055,
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,
6798,
1435,
8843,
429,
3903,
288,
203,
565,
389,
16471,
5621,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/3/0xD0D14e32105E95058a28d8753eF930B024ee38eE/sources/SpotLogic.sol | from StorJ -- https:github.com/nginnever/storj-audit-verifier/contracts/MerkleVerifyv3.sol use the index to determine the node ordering (index ranges 1 to n) we don't assume that the tree is padded to a power of 2 if the index is odd then the proof will start with a hash at a higher layer, so we have to adjust the index to be the index at that layer | function checkProofOrdered(bytes memory proof, bytes32 root, bytes32 leaf, uint index) public pure returns (bool) {
bytes32 element;
bytes32 hash = leaf;
uint remaining;
for (uint j = 32; j <= proof.length; j += 32) {
assembly {
element := mload(add(proof, j))
}
while (remaining > 0 && index % 2 == 1 && index > 2 ** remaining) {
index = uint(index) / 2 + 1;
}
if (index % 2 == 0) {
hash = keccak256(abi.encodePacked(abi.encodePacked(element, hash)));
index = index / 2;
hash = keccak256(abi.encodePacked(abi.encodePacked(hash, element)));
index = uint(index) / 2 + 1;
}
}
return hash == root;
}
| 5,086,587 | [
1,
2080,
934,
280,
46,
1493,
2333,
30,
6662,
18,
832,
19,
82,
1912,
4644,
502,
19,
334,
280,
78,
17,
17413,
17,
31797,
19,
16351,
87,
19,
8478,
15609,
8097,
90,
23,
18,
18281,
999,
326,
770,
358,
4199,
326,
756,
9543,
261,
1615,
7322,
404,
358,
290,
13,
732,
2727,
1404,
6750,
716,
326,
2151,
353,
14426,
358,
279,
7212,
434,
576,
309,
326,
770,
353,
14800,
1508,
326,
14601,
903,
787,
598,
279,
1651,
622,
279,
10478,
3018,
16,
1427,
732,
1240,
358,
5765,
326,
770,
358,
506,
326,
770,
622,
716,
3018,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
866,
20439,
16756,
12,
3890,
3778,
14601,
16,
1731,
1578,
1365,
16,
1731,
1578,
7839,
16,
2254,
770,
13,
1071,
16618,
1135,
261,
6430,
13,
288,
203,
203,
565,
1731,
1578,
930,
31,
203,
565,
1731,
1578,
1651,
273,
7839,
31,
203,
565,
2254,
4463,
31,
203,
565,
364,
261,
11890,
525,
273,
3847,
31,
525,
1648,
14601,
18,
2469,
31,
525,
1011,
3847,
13,
288,
203,
1377,
19931,
288,
203,
3639,
930,
519,
312,
945,
12,
1289,
12,
24207,
16,
525,
3719,
203,
1377,
289,
203,
203,
203,
1377,
1323,
261,
17956,
405,
374,
597,
770,
738,
576,
422,
404,
597,
770,
405,
576,
2826,
4463,
13,
288,
203,
3639,
770,
273,
2254,
12,
1615,
13,
342,
576,
397,
404,
31,
203,
1377,
289,
203,
203,
1377,
309,
261,
1615,
738,
576,
422,
374,
13,
288,
203,
3639,
1651,
273,
417,
24410,
581,
5034,
12,
21457,
18,
3015,
4420,
329,
12,
21457,
18,
3015,
4420,
329,
12,
2956,
16,
1651,
3719,
1769,
203,
3639,
770,
273,
770,
342,
576,
31,
203,
3639,
1651,
273,
417,
24410,
581,
5034,
12,
21457,
18,
3015,
4420,
329,
12,
21457,
18,
3015,
4420,
329,
12,
2816,
16,
930,
3719,
1769,
203,
3639,
770,
273,
2254,
12,
1615,
13,
342,
576,
397,
404,
31,
203,
1377,
289,
203,
565,
289,
203,
565,
327,
1651,
422,
1365,
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
] |
./partial_match/1/0x00000000000006c7676171937C444f6BDe3D6282/sources/contracts/helpers/PointerLibraries.sol | @dev Reads the uint72 at `mPtr` in memory. | function readUint72(
MemoryPointer mPtr
) internal pure returns (uint72 value) {
assembly {
value := mload(mPtr)
}
}
| 4,300,624 | [
1,
7483,
326,
2254,
9060,
622,
1375,
81,
5263,
68,
316,
3778,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
855,
5487,
9060,
12,
203,
3639,
9251,
4926,
312,
5263,
203,
565,
262,
2713,
16618,
1135,
261,
11890,
9060,
460,
13,
288,
203,
3639,
19931,
288,
203,
5411,
460,
519,
312,
945,
12,
81,
5263,
13,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// ZuFinance is a DeFi Token issued on Binance Smart Chain (BEP-20),
// Designed to serve the gaming and sports betting industry, with three simple features implemented at its core;
// LP Acquisition 5%
// Burning on each trade 3%
// Static Reward (Reflection) 2% to all existing holders
// Burn function and all fees - automatically set to 0 as soon as 1B of Tokens remaining in circulation
// No team member benefits from Static Reward (Reflection)
// The transaction fees applies to all team members (except the owner)
// SPDX-License-Identifier: MIT
pragma solidity 0.8.4;
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 Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor () {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
function owner() public view virtual returns (address) {
return _owner;
}
modifier onlyOwner() {
require(owner() == _msgSender(), "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;
}
}
interface IFactory {
function createPair(address tokenA, address tokenB) external returns (address pair);
}
interface IRouter {
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);
function swapExactETHForTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable returns (uint[] memory amounts);
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline) external;
}
abstract contract ZuFinanceBase is IERC20, Ownable {
event UpdateFee(string indexed feeType, uint256 previousTaxFee, uint256 newTaxFee);
event IncludeReflectionAccount(address account);
event ExcludeReflectionAccount(address account);
event IncludeInFee(address account);
event ExcludeFromFee(address account);
event Burn(address account, uint256 amount);
event SwapAndLiquifyEnabledUpdated(bool enabled);
event SwapAndLiquify(
uint256 tokensSwapped,
uint256 bnbReceived,
uint256 tokensIntoLiquidity
);
address public constant BURNING_ADDRESS = 0x000000000000000000000000000000000000dEaD;
mapping (address => uint256) _rOwned;
mapping (address => uint256) _tOwned;
mapping (address => mapping (address => uint256)) _allowances;
mapping (address => bool) _isExcludedFromFee;
mapping (address => bool) _isExcluded;
address[] _excluded;
uint256 constant MAX = ~uint256(0);
uint256 internal _tTotal = 100 * 10**12 * 10**9;
uint256 internal _rTotal = (MAX - (MAX % _tTotal));
uint256 public maxTxAmount = 1 * 10**9 * 10**9;
uint256 public numTokensToSwap = 1 * 10**8 * 10**9;
uint256 public constant numTokensRemainingToStopFees = 1 * 10**9 * 10**9;
bool inSwapAndLiquify;
bool public swapAndLiquifyEnabled = true;
IRouter public immutable router;
address public immutable pair;
constructor() {
_rOwned[_msgSender()] = _rTotal;
//exclude owner and this contract from fee
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[address(this)] = true;
IRouter _router = IRouter(0x10ED43C718714eb63d5aA57B78B54704E256024E);
// Create a uniswap pair for this new token
address _pair = IFactory(_router.factory()).createPair(address(this), _router.WETH());
pair = _pair;
// The team wallet addresses are fully disclosed for transparency
_isExcluded[0x89EbF88686dC667d37738e15866eF80d3862B237] = true;
_isExcluded[0xD3B7a3c4E88883588e2cF1C0Afce1e97A8fF1C97] = true;
_isExcluded[0xf9C934f119A8D2c81B6438135B2e9167E024Ab95] = true;
_isExcluded[0xA113489399F935A260866bEe007d8B0411D2bf75] = true;
_isExcluded[0x63e2d52e099d5f43E1dbcE74c4FA56a8CF178CB6] = true;
_isExcluded[0xC1E22b0fE83804677230515C60f80517DC652fe9] = true;
_isExcluded[0x17c82411CDAAfFAAEEC0b37A4CeF4591393b082E] = true;
_isExcluded[0x4a2a888F04028E307A6450FeF3c5690A9600eA0b] = true;
_isExcluded[0x99781dDE8cf5Fb8c2d32A5B33196b21c3Bb6296B] = true;
_isExcluded[0x5663D90E7e592E6e35B713d99CFd9A52351512cD] = true;
_isExcluded[_pair] = true;
_isExcluded[address(this)] = true;
// set the rest of the contract variables
router = _router;
uint256 tokenToBurn = _tTotal / 10; // 10% is to be burned
_tokenTransferNoFee(_msgSender(), BURNING_ADDRESS, tokenToBurn);
emit Transfer(address(0), _msgSender(), _tTotal - tokenToBurn);
}
modifier lockTheSwap {
inSwapAndLiquify = true;
_;
inSwapAndLiquify = false;
}
uint256 public _taxFee = 2;
uint256 _previousTaxFee = _taxFee;
uint256 public _liquidityFee = 5;
uint256 _previousLiquidityFee = _liquidityFee;
uint256 public _burnFee = 3;
uint256 _previousBurnFee = _burnFee;
struct TotFeesPaidStruct{
uint256 taxFee;
uint256 burnFee;
uint256 liquidityFee;
}
TotFeesPaidStruct public totFeesPaid;
function _balanceOf(address account) internal view returns (uint256) {
if (_isExcluded[account]) return _tOwned[account];
return tokenFromReflection(_rOwned[account]);
}
function _reflectionFromToken(uint256 tAmount, bool deductFee) internal view returns (uint256) {
require(tAmount <= _tTotal, "Amount must be less than supply");
if (!deductFee) {
(uint256 rAmount,,,,,) = _getValues(tAmount);
return rAmount;
} else {
(,uint256 rTransferAmount,,,,) = _getValues(tAmount);
return rTransferAmount;
}
}
function tokenFromReflection(uint256 rAmount) public view returns(uint256) {
require(rAmount <= _rTotal, "Amount must be less than total reflections");
uint256 currentRate = _getRate();
return rAmount / currentRate;
}
function _approve(address owner, address spender, uint256 amount) internal {
require(owner != address(0), "ERC20: approve from 0 address");
require(spender != address(0), "ERC20: approve to 0 address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _reflectFee(uint256 rFee, uint256 tFee) private {
_rTotal = _rTotal - rFee;
totFeesPaid.taxFee += tFee;
}
function _getRate() private view returns(uint256) {
(uint256 rSupply, uint256 tSupply) = _getCurrentSupply();
return rSupply / tSupply;
}
function _excludeAccount(address account) internal {
// require(account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 'We can not exclude Uniswap router.');
require(!_isExcluded[account], "Account is already excluded");
if (_rOwned[account] > 0) {
_tOwned[account] = tokenFromReflection(_rOwned[account]);
}
_isExcluded[account] = true;
_excluded.push(account);
emit ExcludeReflectionAccount(account);
}
function _includeAccount(address account) internal {
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;
}
}
emit IncludeReflectionAccount(account);
}
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 {
totFeesPaid.liquidityFee +=tLiquidity;
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 _removeAllFee() private {
if (_taxFee == 0 &&
_liquidityFee == 0 &&
_burnFee == 0
)
return;
_previousTaxFee = _taxFee;
_previousLiquidityFee = _liquidityFee;
_previousBurnFee = _burnFee;
_taxFee = 0;
_liquidityFee = 0;
_burnFee = 0;
}
function _restoreAllFee() private {
_taxFee = _previousTaxFee;
_liquidityFee = _previousLiquidityFee;
_burnFee = _previousBurnFee;
}
function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) {
(uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getTValues(tAmount);
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tLiquidity, _getRate());
return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tLiquidity);
}
function _getTValues(uint256 tAmount)
internal
view
returns (uint256, uint256, uint256)
{
uint256 tFee = _calculateTaxFee(tAmount);
uint256 tLiquidity = _calculateLiquidityFee(tAmount);
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 _calculateTaxFee(uint256 _amount) private view returns (uint256) {
return _amount * _taxFee / 100;
}
function _calculateLiquidityFee(uint256 _amount) private view returns (uint256) {
return _amount * _liquidityFee / 100;
}
function checkCircSupply() public view returns(uint256){
return (_tTotal - _balanceOf(BURNING_ADDRESS));
}
function _swapTokensForBNB(uint256 tokenAmount) private {
// generate the uniswap pair path of token -> weth
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = router.WETH();
_approve(address(this), address(router), tokenAmount);
// make the swap
router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0, // accept any amount of BNB
path,
address(this),
block.timestamp
);
}
function _addLiquidity(uint256 tokenAmount, uint256 bnbAmount) private {
// approve token transfer to cover all possible scenarios
_approve(address(this), address(router), tokenAmount);
// add the liquidity
router.addLiquidityETH{value: bnbAmount} (
address(this),
tokenAmount,
0, // slippage is unavoidable
0, // slippage is unavoidable
BURNING_ADDRESS, // 3 possibilities: 1) address(0); 2) address(this); 3) address(another contract)
block.timestamp
);
}
function _transfer(
address from,
address to,
uint256 amount
) internal {
require(from != address(0), "ERC20: transfer from 0 address");
require(to != address(0), "ERC20: transfer to 0 address");
require(amount > 0, "ERC20: amount must be greater than 0");
if (from != owner() && to != owner())
require(amount <= maxTxAmount, "Amount exceeds maxTxAmount");
// is the token balance of this contract address over the min number of
// tokens that we need to initiate a swap + liquidity lock?
// also, don't get caught in a circular liquidity event.
// also, don't swap & liquify if sender is uniswap pair.
uint256 contractTokenBalance = _balanceOf(address(this));
if (contractTokenBalance >= maxTxAmount) {
contractTokenBalance = maxTxAmount;
}
bool overMinTokenBalance = contractTokenBalance >= numTokensToSwap;
if (overMinTokenBalance &&
!inSwapAndLiquify &&
from != pair &&
swapAndLiquifyEnabled
) {
contractTokenBalance = numTokensToSwap;
//add liquidity
_swapAndLiquify(contractTokenBalance);
}
//indicates if fee should be deducted from transfer
bool takeFee = true;
uint256 circSupply = checkCircSupply();
//if any account belongs to _isExcludedFromFee account then remove the fee
if (circSupply <= numTokensRemainingToStopFees ||
_isExcludedFromFee[from] ||
_isExcludedFromFee[to])
{
takeFee = false;
}
//transfer amount, it will take tax, burn, liquidity fee
_tokenTransfer(from, to, amount, takeFee);
}
function _swapAndLiquify(uint256 contractTokenBalance) private lockTheSwap {
// split the contract balance into halves
uint256 half = contractTokenBalance / 2;
uint256 otherHalf = contractTokenBalance - half;
// capture the contract's current BNB balance.
// this is so that we can capture exactly the amount of BNB that the
// swap creates, and not make the liquidity event include any BNB that
// has been manually sent to the contract
uint256 initialBalance = address(this).balance;
// swap tokens for BNB
_swapTokensForBNB(half);
// how much BNB did we just swap into
uint256 newBalance = address(this).balance - initialBalance;
// add liquidity to uniswap
_addLiquidity(otherHalf, newBalance);
emit SwapAndLiquify(half, newBalance, otherHalf);
}
//this method is responsible for taking all fee, if takeFee is true
function _tokenTransfer(address sender, address recipient, uint256 amount, bool takeFee) private {
if (!takeFee)
_removeAllFee();
else if(_burnFee > 0) {
uint256 burnAmt = amount * _burnFee / 100;
_tokenTransferNoFee(sender, BURNING_ADDRESS, burnAmt);
totFeesPaid.burnFee += burnAmt;
amount = amount - burnAmt;
}
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]) {
_transferBothExcluded(sender, recipient, amount);
} else {
_transferStandard(sender, recipient, amount);
}
if (!takeFee)
_restoreAllFee();
}
function _tokenTransferNoFee(address sender, address recipient, uint256 amount) private {
_rOwned[sender] = _rOwned[sender] - amount * _getRate();
_rOwned[recipient] = _rOwned[recipient] + amount * _getRate();
if (_isExcluded[sender]) {
_tOwned[sender] = _tOwned[sender] - amount;
}
if (_isExcluded[recipient]) {
_tOwned[recipient] = _tOwned[recipient] + amount;
}
emit Transfer(sender, recipient, amount);
}
function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount);
_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 _transferStandard(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount);
_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);
_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);
_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 _buyback() internal {
uint256 balance = address(this).balance;
require(balance > 0, "Insufficient BNB balance");
address[] memory path = new address[](2);
path[0] = router.WETH();
path[1] = address(this);
router.swapExactETHForTokens{value: balance} (
0,
path,
BURNING_ADDRESS,
block.timestamp
);
}
}
contract ZuFinance is ZuFinanceBase {
string public constant name = "ZuFinance";
string public constant symbol = "ZUF";
uint8 public constant decimals = 9;
receive() external payable {}
function totalSupply() external view override returns (uint256) {
return _tTotal;
}
function balanceOf(address account) external override view returns (uint256) {
return _balanceOf(account);
}
function transfer(address recipient, uint256 amount) external override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) external view override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) external override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function buyback() external onlyOwner returns (bool) {
_buyback();
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) external override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
_approve(sender, _msgSender(), currentAllowance - amount);
return true;
}
function increaseAllowance(address spender, uint256 addedValue) external returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] - subtractedValue);
return true;
}
function reflectionFromToken(uint256 tAmount, bool deductFee) external view returns (uint256) {
return _reflectionFromToken(tAmount, deductFee);
}
function excludeAccountForReflection(address account) external onlyOwner {
_excludeAccount(account);
}
function includeAccountForReflection(address account) external onlyOwner {
_includeAccount(account);
}
function isExcludedFromReflection(address account) external view returns (bool) {
return _isExcluded[account];
}
function excludeFromFee(address account) external onlyOwner {
_isExcludedFromFee[account] = true;
emit ExcludeFromFee(account);
}
function includeInFee(address account) external onlyOwner {
_isExcludedFromFee[account] = false;
emit IncludeInFee(account);
}
function isExcludedFromFee(address account) external view returns (bool) {
return _isExcludedFromFee[account];
}
function setTaxFeePercent(uint256 taxFee) external onlyOwner {
require(taxFee <= 10, "TaxFee exceeds 10");
_taxFee = taxFee;
emit UpdateFee("Tax", _taxFee, taxFee);
}
function setLiquidityFeePercent(uint256 liquidityFee) external onlyOwner {
require(liquidityFee <= 10, "LiquidityFee exceeds 10");
_liquidityFee = liquidityFee;
emit UpdateFee("Liquidity", _liquidityFee, liquidityFee);
}
function setBurnFeePercent(uint256 burnFee) external onlyOwner {
require(burnFee <= 10, "BurnFee exceeds 10");
_burnFee = burnFee;
emit UpdateFee("Burn", _burnFee, burnFee);
}
function setMaxTxPercent(uint256 maxTxPercent) external onlyOwner {
require(maxTxPercent <= 50, "MaxTxPercent exceeds 50");
uint256 newMaxTxAmount = _tTotal * maxTxPercent / 10**2;
maxTxAmount = newMaxTxAmount;
emit UpdateFee("MaxTx", maxTxAmount, newMaxTxAmount);
}
function setNumTokensToSwap(uint256 amount) external onlyOwner{
numTokensToSwap = amount * 10**9;
}
function setSwapAndLiquifyEnabled(bool enabled) external onlyOwner {
swapAndLiquifyEnabled = enabled;
emit SwapAndLiquifyEnabledUpdated(swapAndLiquifyEnabled);
}
}
| require(account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 'We can not exclude Uniswap router.'); | function _excludeAccount(address account) internal {
require(!_isExcluded[account], "Account is already excluded");
if (_rOwned[account] > 0) {
_tOwned[account] = tokenFromReflection(_rOwned[account]);
}
_isExcluded[account] = true;
_excluded.push(account);
emit ExcludeReflectionAccount(account);
}
| 15,802,276 | [
1,
6528,
12,
4631,
480,
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,
16,
296,
3218,
848,
486,
4433,
1351,
291,
91,
438,
4633,
1093,
1769,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
389,
10157,
3032,
12,
2867,
2236,
13,
2713,
288,
203,
3639,
2583,
12,
5,
67,
291,
16461,
63,
4631,
6487,
315,
3032,
353,
1818,
8845,
8863,
203,
3639,
309,
261,
67,
86,
5460,
329,
63,
4631,
65,
405,
374,
13,
288,
203,
5411,
389,
88,
5460,
329,
63,
4631,
65,
273,
1147,
1265,
9801,
24899,
86,
5460,
329,
63,
4631,
19226,
203,
3639,
289,
203,
3639,
389,
291,
16461,
63,
4631,
65,
273,
638,
31,
203,
3639,
389,
24602,
18,
6206,
12,
4631,
1769,
203,
3639,
3626,
20760,
9801,
3032,
12,
4631,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity >=0.5.4 <0.6.0;
interface tokenRecipient { function RECEIVEAPPROVAL172(address _from, uint256 _value, address _token, bytes calldata _extraData) external; } //inject NONSTANDARD NAMING
library SafeMath {
function MUL710(uint256 a, uint256 b) internal pure returns (uint256 c) { //inject NONSTANDARD NAMING
// 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;
}
function DIV595(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
function SUB853(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
assert(b <= a);
return a - b;
}
function ADD540(uint256 a, uint256 b) internal pure returns (uint256 c) { //inject NONSTANDARD NAMING
c = a + b;
assert(c >= a);
return c;
}
}
interface INameTAOPosition {
function SENDERISADVOCATE978(address _sender, address _id) external view returns (bool); //inject NONSTANDARD NAMING
function SENDERISLISTENER841(address _sender, address _id) external view returns (bool); //inject NONSTANDARD NAMING
function SENDERISSPEAKER648(address _sender, address _id) external view returns (bool); //inject NONSTANDARD NAMING
function SENDERISPOSITION99(address _sender, address _id) external view returns (bool); //inject NONSTANDARD NAMING
function GETADVOCATE521(address _id) external view returns (address); //inject NONSTANDARD NAMING
function NAMEISADVOCATE881(address _nameId, address _id) external view returns (bool); //inject NONSTANDARD NAMING
function NAMEISPOSITION327(address _nameId, address _id) external view returns (bool); //inject NONSTANDARD NAMING
function INITIALIZE405(address _id, address _advocateId, address _listenerId, address _speakerId) external returns (bool); //inject NONSTANDARD NAMING
function DETERMINEPOSITION456(address _sender, address _id) external view returns (uint256); //inject NONSTANDARD NAMING
}
contract TokenERC20 {
// Public variables of the token
string public name;
string public symbol;
uint8 public decimals = 18;
// 18 decimals is the strongly suggested default, avoid changing it
uint256 public totalSupply;
// This creates an array with all balances
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
// This generates a public event on the blockchain that will notify clients
event TRANSFER193(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
// This generates a public event on the blockchain that will notify clients
event APPROVAL454(address indexed _owner, address indexed _spender, uint256 _value); //inject NONSTANDARD NAMING
// This notifies clients about the amount burnt
event BURN994(address indexed from, uint256 value); //inject NONSTANDARD NAMING
constructor (uint256 initialSupply, string memory tokenName, string memory tokenSymbol) public {
totalSupply = initialSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount
balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens
name = tokenName; // Set the name for display purposes
symbol = tokenSymbol; // Set the symbol for display purposes
}
function _TRANSFER285(address _from, address _to, uint _value) internal { //inject NONSTANDARD NAMING
// Prevent transfer to 0x0 address. Use burn() instead
require(_to != address(0));
// Check if the sender has enough
require(balanceOf[_from] >= _value);
// Check for overflows
require(balanceOf[_to] + _value > balanceOf[_to]);
// Save this for an assertion in the future
uint previousBalances = balanceOf[_from] + balanceOf[_to];
// Subtract from the sender
balanceOf[_from] -= _value;
// Add the same to the recipient
balanceOf[_to] += _value;
emit TRANSFER193(_from, _to, _value);
// Asserts are used to use static analysis to find bugs in your code. They should never fail
assert(balanceOf[_from] + balanceOf[_to] == previousBalances);
}
function TRANSFER874(address _to, uint256 _value) public returns (bool success) { //inject NONSTANDARD NAMING
_TRANSFER285(msg.sender, _to, _value);
return true;
}
function TRANSFERFROM282(address _from, address _to, uint256 _value) public returns (bool success) { //inject NONSTANDARD NAMING
require(_value <= allowance[_from][msg.sender]); // Check allowance
allowance[_from][msg.sender] -= _value;
_TRANSFER285(_from, _to, _value);
return true;
}
function APPROVE265(address _spender, uint256 _value) public returns (bool success) { //inject NONSTANDARD NAMING
allowance[msg.sender][_spender] = _value;
emit APPROVAL454(msg.sender, _spender, _value);
return true;
}
function APPROVEANDCALL88(address _spender, uint256 _value, bytes memory _extraData) public returns (bool success) { //inject NONSTANDARD NAMING
tokenRecipient spender = tokenRecipient(_spender);
if (APPROVE265(_spender, _value)) {
spender.RECEIVEAPPROVAL172(msg.sender, _value, address(this), _extraData);
return true;
}
}
function BURN239(uint256 _value) public returns (bool success) { //inject NONSTANDARD NAMING
require(balanceOf[msg.sender] >= _value); // Check if the sender has enough
balanceOf[msg.sender] -= _value; // Subtract from the sender
totalSupply -= _value; // Updates totalSupply
emit BURN994(msg.sender, _value);
return true;
}
function BURNFROM882(address _from, uint256 _value) public returns (bool success) { //inject NONSTANDARD NAMING
require(balanceOf[_from] >= _value); // Check if the targeted balance is enough
require(_value <= allowance[_from][msg.sender]); // Check allowance
balanceOf[_from] -= _value; // Subtract from the targeted balance
allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance
totalSupply -= _value; // Update totalSupply
emit BURN994(_from, _value);
return true;
}
}
contract TAO {
using SafeMath for uint256;
address public vaultAddress;
string public name; // the name for this TAO
address public originId; // the ID of the Name that created this TAO. If Name, it's the eth address
// TAO's data
string public datHash;
string public database;
string public keyValue;
bytes32 public contentId;
uint8 public typeId;
constructor (string memory _name,
address _originId,
string memory _datHash,
string memory _database,
string memory _keyValue,
bytes32 _contentId,
address _vaultAddress
) public {
name = _name;
originId = _originId;
datHash = _datHash;
database = _database;
keyValue = _keyValue;
contentId = _contentId;
// Creating TAO
typeId = 0;
vaultAddress = _vaultAddress;
}
modifier ONLYVAULT404 { //inject NONSTANDARD NAMING
require (msg.sender == vaultAddress);
_;
}
function () external payable {
}
function TRANSFERETH144(address payable _recipient, uint256 _amount) public ONLYVAULT404 returns (bool) { //inject NONSTANDARD NAMING
_recipient.transfer(_amount);
return true;
}
function TRANSFERERC20563(address _erc20TokenAddress, address _recipient, uint256 _amount) public ONLYVAULT404 returns (bool) { //inject NONSTANDARD NAMING
TokenERC20 _erc20 = TokenERC20(_erc20TokenAddress);
_erc20.TRANSFER874(_recipient, _amount);
return true;
}
}
contract Name is TAO {
constructor (string memory _name, address _originId, string memory _datHash, string memory _database, string memory _keyValue, bytes32 _contentId, address _vaultAddress)
TAO (_name, _originId, _datHash, _database, _keyValue, _contentId, _vaultAddress) public {
// Creating Name
typeId = 1;
}
}
library AOLibrary {
using SafeMath for uint256;
uint256 constant private _multiplier_divisor322 = 10 ** 6; // 1000000 = 1 //inject NONSTANDARD NAMING
uint256 constant private _percentage_divisor262 = 10 ** 6; // 100% = 1000000 //inject NONSTANDARD NAMING
function ISTAO231(address _taoId) public view returns (bool) { //inject NONSTANDARD NAMING
return (_taoId != address(0) && bytes(TAO(address(uint160(_taoId))).name()).length > 0 && TAO(address(uint160(_taoId))).originId() != address(0) && TAO(address(uint160(_taoId))).typeId() == 0);
}
function ISNAME781(address _nameId) public view returns (bool) { //inject NONSTANDARD NAMING
return (_nameId != address(0) && bytes(TAO(address(uint160(_nameId))).name()).length > 0 && Name(address(uint160(_nameId))).originId() != address(0) && Name(address(uint160(_nameId))).typeId() == 1);
}
function ISVALIDERC20TOKENADDRESS312(address _tokenAddress) public view returns (bool) { //inject NONSTANDARD NAMING
if (_tokenAddress == address(0)) {
return false;
}
TokenERC20 _erc20 = TokenERC20(_tokenAddress);
return (_erc20.totalSupply() >= 0 && bytes(_erc20.name()).length > 0 && bytes(_erc20.symbol()).length > 0);
}
function ISTHEAO403(address _sender, address _theAO, address _nameTAOPositionAddress) public view returns (bool) { //inject NONSTANDARD NAMING
return (_sender == _theAO ||
(
(ISTAO231(_theAO) || ISNAME781(_theAO)) &&
_nameTAOPositionAddress != address(0) &&
INameTAOPosition(_nameTAOPositionAddress).SENDERISADVOCATE978(_sender, _theAO)
)
);
}
function PERCENTAGE_DIVISOR218() public pure returns (uint256) { //inject NONSTANDARD NAMING
return _percentage_divisor262;
}
function MULTIPLIER_DIVISOR371() public pure returns (uint256) { //inject NONSTANDARD NAMING
return _multiplier_divisor322;
}
function DEPLOYTAO162(string memory _name, //inject NONSTANDARD NAMING
address _originId,
string memory _datHash,
string memory _database,
string memory _keyValue,
bytes32 _contentId,
address _nameTAOVaultAddress
) public returns (TAO _tao) {
_tao = new TAO(_name, _originId, _datHash, _database, _keyValue, _contentId, _nameTAOVaultAddress);
}
function DEPLOYNAME486(string memory _name, //inject NONSTANDARD NAMING
address _originId,
string memory _datHash,
string memory _database,
string memory _keyValue,
bytes32 _contentId,
address _nameTAOVaultAddress
) public returns (Name _myName) {
_myName = new Name(_name, _originId, _datHash, _database, _keyValue, _contentId, _nameTAOVaultAddress);
}
function CALCULATEWEIGHTEDMULTIPLIER712(uint256 _currentWeightedMultiplier, uint256 _currentPrimordialBalance, uint256 _additionalWeightedMultiplier, uint256 _additionalPrimordialAmount) public pure returns (uint256) { //inject NONSTANDARD NAMING
if (_currentWeightedMultiplier > 0) {
uint256 _totalWeightedIons = (_currentWeightedMultiplier.MUL710(_currentPrimordialBalance)).ADD540(_additionalWeightedMultiplier.MUL710(_additionalPrimordialAmount));
uint256 _totalIons = _currentPrimordialBalance.ADD540(_additionalPrimordialAmount);
return _totalWeightedIons.DIV595(_totalIons);
} else {
return _additionalWeightedMultiplier;
}
}
function CALCULATEPRIMORDIALMULTIPLIER760(uint256 _purchaseAmount, uint256 _totalPrimordialMintable, uint256 _totalPrimordialMinted, uint256 _startingMultiplier, uint256 _endingMultiplier) public pure returns (uint256) { //inject NONSTANDARD NAMING
if (_purchaseAmount > 0 && _purchaseAmount <= _totalPrimordialMintable.SUB853(_totalPrimordialMinted)) {
uint256 temp = _totalPrimordialMinted.ADD540(_purchaseAmount.DIV595(2));
uint256 multiplier = (_multiplier_divisor322.SUB853(_multiplier_divisor322.MUL710(temp).DIV595(_totalPrimordialMintable))).MUL710(_startingMultiplier.SUB853(_endingMultiplier));
return multiplier.DIV595(_multiplier_divisor322);
} else {
return 0;
}
}
function CALCULATENETWORKBONUSPERCENTAGE146(uint256 _purchaseAmount, uint256 _totalPrimordialMintable, uint256 _totalPrimordialMinted, uint256 _startingMultiplier, uint256 _endingMultiplier) public pure returns (uint256) { //inject NONSTANDARD NAMING
if (_purchaseAmount > 0 && _purchaseAmount <= _totalPrimordialMintable.SUB853(_totalPrimordialMinted)) {
uint256 temp = _totalPrimordialMinted.ADD540(_purchaseAmount.DIV595(2));
uint256 bonusPercentage = (_percentage_divisor262.SUB853(_percentage_divisor262.MUL710(temp).DIV595(_totalPrimordialMintable))).MUL710(_startingMultiplier.SUB853(_endingMultiplier)).DIV595(_percentage_divisor262);
return bonusPercentage;
} else {
return 0;
}
}
function CALCULATENETWORKBONUSAMOUNT621(uint256 _purchaseAmount, uint256 _totalPrimordialMintable, uint256 _totalPrimordialMinted, uint256 _startingMultiplier, uint256 _endingMultiplier) public pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 bonusPercentage = CALCULATENETWORKBONUSPERCENTAGE146(_purchaseAmount, _totalPrimordialMintable, _totalPrimordialMinted, _startingMultiplier, _endingMultiplier);
uint256 networkBonus = bonusPercentage.MUL710(_purchaseAmount).DIV595(_percentage_divisor262);
return networkBonus;
}
function CALCULATEMAXIMUMBURNAMOUNT319(uint256 _primordialBalance, uint256 _currentWeightedMultiplier, uint256 _maximumMultiplier) public pure returns (uint256) { //inject NONSTANDARD NAMING
return (_maximumMultiplier.MUL710(_primordialBalance).SUB853(_primordialBalance.MUL710(_currentWeightedMultiplier))).DIV595(_maximumMultiplier);
}
function CALCULATEMULTIPLIERAFTERBURN888(uint256 _primordialBalance, uint256 _currentWeightedMultiplier, uint256 _amountToBurn) public pure returns (uint256) { //inject NONSTANDARD NAMING
return _primordialBalance.MUL710(_currentWeightedMultiplier).DIV595(_primordialBalance.SUB853(_amountToBurn));
}
function CALCULATEMULTIPLIERAFTERCONVERSION91(uint256 _primordialBalance, uint256 _currentWeightedMultiplier, uint256 _amountToConvert) public pure returns (uint256) { //inject NONSTANDARD NAMING
return _primordialBalance.MUL710(_currentWeightedMultiplier).DIV595(_primordialBalance.ADD540(_amountToConvert));
}
function NUMDIGITS612(uint256 number) public pure returns (uint8) { //inject NONSTANDARD NAMING
uint8 digits = 0;
while(number != 0) {
number = number.DIV595(10);
digits++;
}
return digits;
}
}
contract TheAO {
address public theAO;
address public nameTAOPositionAddress;
// Check whether an address is whitelisted and granted access to transact
// on behalf of others
mapping (address => bool) public whitelist;
constructor() public {
theAO = msg.sender;
}
modifier INWHITELIST24() { //inject NONSTANDARD NAMING
require (whitelist[msg.sender] == true);
_;
}
function TRANSFEROWNERSHIP920(address _theAO) public { //inject NONSTANDARD NAMING
require (msg.sender == theAO);
require (_theAO != address(0));
theAO = _theAO;
}
function SETWHITELIST120(address _account, bool _whitelist) public { //inject NONSTANDARD NAMING
require (msg.sender == theAO);
require (_account != address(0));
whitelist[_account] = _whitelist;
}
}
contract TAOCurrency is TheAO {
using SafeMath for uint256;
// Public variables of the contract
string public name;
string public symbol;
uint8 public decimals;
// To differentiate denomination of TAO Currency
uint256 public powerOfTen;
uint256 public totalSupply;
// This creates an array with all balances
// address is the address of nameId, not the eth public address
mapping (address => uint256) public balanceOf;
// This generates a public event on the blockchain that will notify clients
// address is the address of TAO/Name Id, not eth public address
event TRANSFER193(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
// This notifies clients about the amount burnt
// address is the address of TAO/Name Id, not eth public address
event BURN994(address indexed from, uint256 value); //inject NONSTANDARD NAMING
constructor (string memory _name, string memory _symbol, address _nameTAOPositionAddress) public {
name = _name; // Set the name for display purposes
symbol = _symbol; // Set the symbol for display purposes
powerOfTen = 0;
decimals = 0;
SETNAMETAOPOSITIONADDRESS170(_nameTAOPositionAddress);
}
modifier ONLYTHEAO376 { //inject NONSTANDARD NAMING
require (AOLibrary.ISTHEAO403(msg.sender, theAO, nameTAOPositionAddress));
_;
}
modifier ISNAMEORTAO154(address _id) { //inject NONSTANDARD NAMING
require (AOLibrary.ISNAME781(_id) || AOLibrary.ISTAO231(_id));
_;
}
function TRANSFEROWNERSHIP920(address _theAO) public ONLYTHEAO376 { //inject NONSTANDARD NAMING
require (_theAO != address(0));
theAO = _theAO;
}
function SETWHITELIST120(address _account, bool _whitelist) public ONLYTHEAO376 { //inject NONSTANDARD NAMING
require (_account != address(0));
whitelist[_account] = _whitelist;
}
function SETNAMETAOPOSITIONADDRESS170(address _nameTAOPositionAddress) public ONLYTHEAO376 { //inject NONSTANDARD NAMING
require (_nameTAOPositionAddress != address(0));
nameTAOPositionAddress = _nameTAOPositionAddress;
}
function TRANSFERFROM282(address _from, address _to, uint256 _value) public INWHITELIST24 ISNAMEORTAO154(_from) ISNAMEORTAO154(_to) returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER285(_from, _to, _value);
return true;
}
function MINT678(address target, uint256 mintedAmount) public INWHITELIST24 ISNAMEORTAO154(target) returns (bool) { //inject NONSTANDARD NAMING
_MINT887(target, mintedAmount);
return true;
}
function WHITELISTBURNFROM289(address _from, uint256 _value) public INWHITELIST24 ISNAMEORTAO154(_from) returns (bool success) { //inject NONSTANDARD NAMING
require(balanceOf[_from] >= _value); // Check if the targeted balance is enough
balanceOf[_from] = balanceOf[_from].SUB853(_value); // Subtract from the targeted balance
totalSupply = totalSupply.SUB853(_value); // Update totalSupply
emit BURN994(_from, _value);
return true;
}
function _TRANSFER285(address _from, address _to, uint256 _value) internal { //inject NONSTANDARD NAMING
require (_to != address(0)); // Prevent transfer to 0x0 address. Use burn() instead
require (balanceOf[_from] >= _value); // Check if the sender has enough
require (balanceOf[_to].ADD540(_value) >= balanceOf[_to]); // Check for overflows
uint256 previousBalances = balanceOf[_from].ADD540(balanceOf[_to]);
balanceOf[_from] = balanceOf[_from].SUB853(_value); // Subtract from the sender
balanceOf[_to] = balanceOf[_to].ADD540(_value); // Add the same to the recipient
emit TRANSFER193(_from, _to, _value);
assert(balanceOf[_from].ADD540(balanceOf[_to]) == previousBalances);
}
function _MINT887(address target, uint256 mintedAmount) internal { //inject NONSTANDARD NAMING
balanceOf[target] = balanceOf[target].ADD540(mintedAmount);
totalSupply = totalSupply.ADD540(mintedAmount);
emit TRANSFER193(address(0), address(this), mintedAmount);
emit TRANSFER193(address(this), target, mintedAmount);
}
}
contract PathosGiga is TAOCurrency {
constructor(string memory _name, string memory _symbol, address _nameTAOPositionAddress)
TAOCurrency(_name, _symbol, _nameTAOPositionAddress) public {
powerOfTen = 9;
decimals = 9;
}
} | inject NONSTANDARD NAMING
| function DETERMINEPOSITION456(address _sender, address _id) external view returns (uint256); | 13,026,329 | [
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,
202,
915,
463,
1584,
654,
49,
3740,
15258,
24,
4313,
12,
2867,
389,
15330,
16,
1758,
389,
350,
13,
3903,
1476,
1135,
261,
11890,
5034,
1769,
202,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/42/0xA18Cfc81E9DaE65447F7e4323a062E5C2f1DdFe4/sources/browser/Bitcoin.sol | * @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), "BTC::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "BTC::delegateBySig: invalid nonce");
require(now <= expiry, "BTC::delegateBySig: signature expired");
return _delegate(signatory, delegatee);
}
| 9,587,066 | [
1,
15608,
815,
19588,
628,
1573,
8452,
358,
1375,
22216,
73,
68,
225,
7152,
73,
1021,
1758,
358,
7152,
19588,
358,
225,
7448,
1021,
6835,
919,
1931,
358,
845,
326,
3372,
225,
10839,
1021,
813,
622,
1492,
358,
6930,
326,
3372,
225,
331,
1021,
11044,
1160,
434,
326,
3372,
225,
436,
670,
6186,
434,
326,
7773,
19748,
3372,
3082,
225,
272,
670,
6186,
434,
326,
7773,
19748,
3372,
3082,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
7152,
858,
8267,
12,
203,
3639,
1758,
7152,
73,
16,
203,
3639,
2254,
7448,
16,
203,
3639,
2254,
10839,
16,
203,
3639,
2254,
28,
331,
16,
203,
3639,
1731,
1578,
436,
16,
203,
3639,
1731,
1578,
272,
203,
565,
262,
203,
3639,
3903,
203,
565,
288,
203,
3639,
1731,
1578,
2461,
6581,
273,
417,
24410,
581,
5034,
12,
203,
5411,
24126,
18,
3015,
12,
203,
7734,
27025,
67,
2399,
15920,
16,
203,
7734,
417,
24410,
581,
5034,
12,
3890,
12,
529,
10756,
3631,
203,
7734,
30170,
548,
9334,
203,
7734,
1758,
12,
2211,
13,
203,
5411,
262,
203,
3639,
11272,
203,
203,
3639,
1731,
1578,
1958,
2310,
273,
417,
24410,
581,
5034,
12,
203,
5411,
24126,
18,
3015,
12,
203,
7734,
2030,
19384,
2689,
67,
2399,
15920,
16,
203,
7734,
7152,
73,
16,
203,
7734,
7448,
16,
203,
7734,
10839,
203,
5411,
262,
203,
3639,
11272,
203,
203,
3639,
1731,
1578,
5403,
273,
417,
24410,
581,
5034,
12,
203,
5411,
24126,
18,
3015,
4420,
329,
12,
203,
7734,
1548,
92,
3657,
64,
92,
1611,
3113,
203,
7734,
2461,
6581,
16,
203,
7734,
1958,
2310,
203,
5411,
262,
203,
3639,
11272,
203,
203,
3639,
1758,
1573,
8452,
273,
425,
1793,
3165,
12,
10171,
16,
331,
16,
436,
16,
272,
1769,
203,
3639,
2583,
12,
2977,
8452,
480,
1758,
12,
20,
3631,
315,
38,
15988,
2866,
22216,
858,
8267,
30,
2057,
3372,
8863,
203,
3639,
2583,
12,
12824,
422,
1661,
764,
63,
2977,
8452,
3737,
15,
16,
315,
38,
15988,
2866,
22216,
858,
8267,
2
] |
pragma solidity ^0.4.24;
import "../contracts/SafeToken.sol";
contract SafeTokenHarness is SafeToken {
// adding the completely valid 'view' declaration to this function causes gas usage test in SafeTokenHarnessTest.js
// to fail because the result of calling this function is 'undefined.'
// TODO: Figure out how SafeTokenHarnessTest of checkInboundTransfer can be modified so it doesn't fail if this is declared as view
function checkInboundTransfer(address asset, address from, uint amount) public view returns (uint256) {
Error err = checkTransferIn(asset, from, amount);
return uint(err);
}
function doInboundTransfer(address asset, address from, uint amount) public returns (uint256) {
Error err = doTransferIn(asset, from, amount);
return uint(err);
}
function doOutboundTransfer(address asset, address to, uint amount) public returns (uint256) {
Error err = doTransferOut(asset, to, amount);
return uint(err);
}
} | adding the completely valid 'view' declaration to this function causes gas usage test in SafeTokenHarnessTest.js to fail because the result of calling this function is 'undefined.' TODO: Figure out how SafeTokenHarnessTest of checkInboundTransfer can be modified so it doesn't fail if this is declared as view | contract SafeTokenHarness is SafeToken {
function checkInboundTransfer(address asset, address from, uint amount) public view returns (uint256) {
Error err = checkTransferIn(asset, from, amount);
return uint(err);
}
function doInboundTransfer(address asset, address from, uint amount) public returns (uint256) {
Error err = doTransferIn(asset, from, amount);
return uint(err);
}
function doOutboundTransfer(address asset, address to, uint amount) public returns (uint256) {
Error err = doTransferOut(asset, to, amount);
return uint(err);
}
} | 7,286,500 | [
1,
3439,
326,
14416,
923,
296,
1945,
11,
8266,
358,
333,
445,
14119,
16189,
4084,
1842,
316,
14060,
1345,
44,
1303,
403,
4709,
18,
2924,
358,
2321,
2724,
326,
563,
434,
4440,
333,
445,
353,
296,
5978,
1093,
2660,
30,
18818,
596,
3661,
14060,
1345,
44,
1303,
403,
4709,
434,
866,
20571,
5912,
848,
506,
4358,
1427,
518,
3302,
1404,
2321,
309,
333,
353,
7886,
487,
1476,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
16351,
14060,
1345,
44,
1303,
403,
353,
14060,
1345,
288,
203,
203,
565,
445,
866,
20571,
5912,
12,
2867,
3310,
16,
1758,
628,
16,
2254,
3844,
13,
1071,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
1068,
393,
273,
866,
5912,
382,
12,
9406,
16,
628,
16,
3844,
1769,
203,
203,
3639,
327,
2254,
12,
370,
1769,
203,
565,
289,
203,
203,
565,
445,
741,
20571,
5912,
12,
2867,
3310,
16,
1758,
628,
16,
2254,
3844,
13,
1071,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
1068,
393,
273,
741,
5912,
382,
12,
9406,
16,
628,
16,
3844,
1769,
203,
203,
3639,
327,
2254,
12,
370,
1769,
203,
565,
289,
203,
203,
565,
445,
741,
17873,
5912,
12,
2867,
3310,
16,
1758,
358,
16,
2254,
3844,
13,
1071,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
1068,
393,
273,
741,
5912,
1182,
12,
9406,
16,
358,
16,
3844,
1769,
203,
203,
3639,
327,
2254,
12,
370,
1769,
203,
565,
289,
203,
203,
97,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/0x5094a8f54B12AEc540bF7cCd0Dd7B62f4FecF7f2/sources/Users/Elena/Source/argent-contracts/contracts/modules/TransferManager.sol | * @notice Implementation of EIP 1271. Should return whether the signature provided is valid for the provided data. @param _msgHash Hash of a message signed on the behalf of address(this) @param _signature Signature byte array associated with _msgHash/ | function isValidSignature(bytes32 _msgHash, bytes memory _signature) public view returns (bytes4) {
require(_signature.length == 65, "TM: invalid signature length");
address signer = Utils.recoverSigner(_msgHash, _signature, 0);
require(isOwner(msg.sender, signer), "TM: Invalid signer");
return ERC1271_ISVALIDSIGNATURE_BYTES32;
}
| 9,255,172 | [
1,
13621,
434,
512,
2579,
2593,
11212,
18,
9363,
327,
2856,
326,
3372,
2112,
353,
923,
364,
326,
2112,
501,
18,
225,
389,
3576,
2310,
2474,
434,
279,
883,
6726,
603,
326,
12433,
6186,
434,
1758,
12,
2211,
13,
225,
389,
8195,
9249,
1160,
526,
3627,
598,
389,
3576,
2310,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
4908,
5374,
12,
3890,
1578,
389,
3576,
2310,
16,
1731,
3778,
389,
8195,
13,
1071,
1476,
1135,
261,
3890,
24,
13,
288,
203,
3639,
2583,
24899,
8195,
18,
2469,
422,
15892,
16,
315,
22903,
30,
2057,
3372,
769,
8863,
203,
3639,
1758,
10363,
273,
6091,
18,
266,
3165,
15647,
24899,
3576,
2310,
16,
389,
8195,
16,
374,
1769,
203,
3639,
2583,
12,
291,
5541,
12,
3576,
18,
15330,
16,
10363,
3631,
315,
22903,
30,
1962,
10363,
8863,
203,
3639,
327,
4232,
39,
2138,
11212,
67,
5127,
5063,
26587,
67,
13718,
1578,
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
] |
./partial_match/3/0xB81bFfBf4E1e1d2C4100F71425F98Df17D5bF272/sources/BountyMoneyV1Miner.sol | record token mint block | uint256 public lastProduceBlock;
| 5,314,346 | [
1,
3366,
1147,
312,
474,
1203,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
2254,
5034,
1071,
1142,
25884,
1768,
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
] |
./full_match/3/0xdd77AC2db94D5Ba21c537B244E2DfE7Ff898D208/sources/browser/insurance/insuranceEvents.sol | * Votes for the event using given user. Must be admin to execute */ | function voteForEventByAdmin(
uint256 eventId,
address userAddress
) public whenNotPaused {
require(hasRole(ADMIN_ROLE, msg.sender), "Can be issued only by admin");
_voteForEvent(msg.sender, userAddress, eventId);
}
| 14,136,027 | [
1,
29637,
364,
326,
871,
1450,
864,
729,
18,
6753,
506,
3981,
358,
1836,
342,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
12501,
1290,
1133,
858,
4446,
12,
203,
565,
2254,
5034,
26004,
16,
203,
565,
1758,
729,
1887,
203,
225,
262,
1071,
1347,
1248,
28590,
288,
203,
565,
2583,
12,
5332,
2996,
12,
15468,
67,
16256,
16,
1234,
18,
15330,
3631,
315,
2568,
506,
16865,
1338,
635,
3981,
8863,
203,
565,
389,
25911,
1290,
1133,
12,
3576,
18,
15330,
16,
729,
1887,
16,
26004,
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
] |
./partial_match/80001/0x062292e464fc5A7dC1D00CC5dd214bC0efB65a1C/sources/Users/famousbirthdays/Sites/mb-contracts/contracts/MetaBoards.sol | * @dev Pays out all the stakers of this spot and resets its balance. Payouts are distributed like so: 10% - burned forever 10% - sent to the jackpot 5% - sent to dev address 75% - split evenly between all stakers (active or not) - To be eligible to receive the payout the player must have the card staked and rolled in the last day - Any staked share that is not eligible will be burned Requirements - `_spotId` cannot be the zero address. - `account` must have at least `amount` tokens./get all the addresses that have this card stakedtotal up the stakers10% to burn10% to jackpot5% to devclear the spot balance | function _payOutSpot(uint256 _spotId) internal {
require(_spotId + 1 <= gameStats.totalSpaces && boardInfo[_spotId].balance > 0, "Invalid");
uint256 totalToDistribute = boardInfo[_spotId].balance;
uint256 toBurn = (totalToDistribute * 10)/100;
uint256 toJackpot = (totalToDistribute * 10)/100;
uint256 toDev = (totalToDistribute * 5)/100;
boardInfo[_spotId].balance = 0;
uint256 toSend = 0;
if(gameSettings.shareRent){
toSend = totalToDistribute - toBurn - toJackpot - toDev;
if(contracts.rentShares.totalRentSharePoints(boardInfo[_spotId].nftId) > 0){
contracts.rentShares.collectRent(boardInfo[_spotId].nftId,toSend);
toBurn = toBurn + toSend;
}
}
gameStats.jackpotBalance = gameStats.jackpotBalance + toJackpot;
/ ) (
\(_)/ */
safeTokenTransfer(feeAddress,toDev);
emit SpotPaid(msg.sender, gameId, _spotId, boardInfo[_spotId].nftId,toSend,toBurn,toJackpot,toDev );
if(gameSettings.shareRent){
toSend = totalToDistribute - toBurn - toJackpot - toDev;
if(contracts.rentShares.totalRentSharePoints(boardInfo[_spotId].nftId) > 0){
contracts.rentShares.collectRent(boardInfo[_spotId].nftId,toSend);
toBurn = toBurn + toSend;
}
}
gameStats.jackpotBalance = gameStats.jackpotBalance + toJackpot;
/ ) (
\(_)/ */
safeTokenTransfer(feeAddress,toDev);
emit SpotPaid(msg.sender, gameId, _spotId, boardInfo[_spotId].nftId,toSend,toBurn,toJackpot,toDev );
} else {
} else {
toJackpot = (totalToDistribute * 20)/100;
toDev = (totalToDistribute * 5)/100;
toBurn = totalToDistribute - toJackpot - toDev;
) \
safeTokenTransfer(address(burnAddress), toBurn);
}
| 8,804,660 | [
1,
26744,
596,
777,
326,
384,
581,
414,
434,
333,
16463,
471,
20063,
2097,
11013,
18,
453,
2012,
87,
854,
16859,
3007,
1427,
30,
1728,
9,
300,
18305,
329,
21238,
1728,
9,
300,
3271,
358,
326,
525,
484,
13130,
1381,
9,
300,
3271,
358,
4461,
1758,
18821,
9,
300,
1416,
5456,
715,
3086,
777,
384,
581,
414,
261,
3535,
578,
486,
13,
300,
2974,
506,
21351,
358,
6798,
326,
293,
2012,
326,
7291,
1297,
1240,
326,
5270,
384,
9477,
471,
28693,
316,
326,
1142,
2548,
300,
5502,
384,
9477,
7433,
716,
353,
486,
21351,
903,
506,
18305,
329,
29076,
300,
1375,
67,
19032,
548,
68,
2780,
506,
326,
3634,
1758,
18,
300,
1375,
4631,
68,
1297,
1240,
622,
4520,
1375,
8949,
68,
2430,
18,
19,
588,
777,
326,
6138,
716,
1240,
333,
5270,
384,
9477,
4963,
731,
326,
384,
581,
414,
2163,
9,
358,
18305,
2163,
9,
358,
525,
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,
389,
10239,
1182,
17292,
12,
11890,
5034,
389,
19032,
548,
13,
2713,
288,
203,
3639,
2583,
24899,
19032,
548,
397,
404,
1648,
7920,
4195,
18,
4963,
12077,
597,
11094,
966,
63,
67,
19032,
548,
8009,
12296,
405,
374,
16,
315,
1941,
8863,
203,
203,
3639,
2254,
5034,
2078,
774,
1669,
887,
273,
11094,
966,
63,
67,
19032,
548,
8009,
12296,
31,
203,
203,
3639,
2254,
5034,
358,
38,
321,
273,
261,
4963,
774,
1669,
887,
380,
1728,
13176,
6625,
31,
203,
203,
3639,
2254,
5034,
358,
46,
484,
13130,
273,
261,
4963,
774,
1669,
887,
380,
1728,
13176,
6625,
31,
203,
203,
3639,
2254,
5034,
358,
8870,
273,
261,
4963,
774,
1669,
887,
380,
1381,
13176,
6625,
31,
203,
203,
3639,
11094,
966,
63,
67,
19032,
548,
8009,
12296,
273,
374,
31,
203,
3639,
2254,
5034,
358,
3826,
273,
374,
31,
203,
3639,
309,
12,
13957,
2628,
18,
14419,
54,
319,
15329,
203,
5411,
358,
3826,
273,
2078,
774,
1669,
887,
300,
358,
38,
321,
300,
358,
46,
484,
13130,
300,
358,
8870,
31,
203,
5411,
309,
12,
16351,
87,
18,
547,
24051,
18,
4963,
54,
319,
9535,
5636,
12,
3752,
966,
63,
67,
19032,
548,
8009,
82,
1222,
548,
13,
405,
374,
15329,
203,
7734,
20092,
18,
547,
24051,
18,
14676,
54,
319,
12,
3752,
966,
63,
67,
19032,
548,
8009,
82,
1222,
548,
16,
869,
3826,
1769,
203,
7734,
358,
38,
321,
273,
358,
38,
321,
397,
358,
3826,
31,
203,
5411,
289,
203,
203,
203,
203,
3639,
289,
203,
2
] |
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "./interfaces/IConvenience.sol";
import "./authorizers/interfaces/IAuthorizer.sol";
import "./interfaces/IAirnode.sol";
contract Convenience is IConvenience {
IAirnode public airnode;
constructor (address _airnode)
public
{
airnode = IAirnode(_airnode);
}
/// @notice A convenience function to retrieve provider parameters and the
/// block number with a single call
/// @param providerId Provider ID
/// @return admin Provider admin
/// @return xpub Master public key of the provider node
/// @return blockNumber Block number
function getProviderAndBlockNumber(bytes32 providerId)
external
view
override
returns (
address admin,
string memory xpub,
uint256 blockNumber
)
{
(admin, xpub) = airnode.getProvider(providerId);
blockNumber = block.number;
}
/// @notice A convenience function to retrieve multiple templates with a
/// single call
/// @param templateIds Request template IDs
/// @return providerIds Provider IDs from ProviderStore
/// @return endpointIds Endpoint IDs from EndpointStore
/// @return requesterIndices Requester indices from RequesterStore
/// @return designatedWallets Designated wallets that are requested to
/// fulfill the request
/// @return fulfillAddresses Addresses that will be called to fulfill
/// @return fulfillFunctionIds Signatures of the functions that will be
/// called to fulfill
/// @return parameters Array of static request parameters (i.e., parameters
/// that will not change between requests, unlike the dynamic parameters
/// determined at runtime)
function getTemplates(bytes32[] calldata templateIds)
external
view
override
returns (
bytes32[] memory providerIds,
bytes32[] memory endpointIds,
uint256[] memory requesterIndices,
address[] memory designatedWallets,
address[] memory fulfillAddresses,
bytes4[] memory fulfillFunctionIds,
bytes[] memory parameters
)
{
providerIds = new bytes32[](templateIds.length);
endpointIds = new bytes32[](templateIds.length);
requesterIndices = new uint256[](templateIds.length);
designatedWallets = new address[](templateIds.length);
fulfillAddresses = new address[](templateIds.length);
fulfillFunctionIds = new bytes4[](templateIds.length);
parameters = new bytes[](templateIds.length);
for (uint256 ind = 0; ind < templateIds.length; ind++)
{
(
providerIds[ind],
endpointIds[ind],
requesterIndices[ind],
designatedWallets[ind],
fulfillAddresses[ind],
fulfillFunctionIds[ind],
parameters[ind]
) = airnode.getTemplate(templateIds[ind]);
}
}
/// @notice Uses the authorizer contracts of an endpoint of a provider to
/// decide if a client contract is authorized to call the endpoint. Once an
/// oracle node receives a request, it calls this method to determine if it
/// should respond. Similarly, third parties can use this method to
/// determine if a client contract is authorized to call an endpoint.
/// @dev Authorizer contracts are not trusted, so this method should only
/// be called off-chain.
/// The elements of the authorizer array are either addresses of Authorizer
/// contracts with the interface defined in IAuthorizer or 0.
/// Say we have authorizer contracts X, Y, Z, T, and our authorizer
/// array is [X, Y, 0, Z, T]. This means that the requester should satisfy
/// (X AND Y) OR (Z AND T) to be considered authorized. In other words,
/// consequent authorizer contracts need to verify authorization
/// simultaneously, while 0 represents the start of an independent
/// authorization policy. From a logical standpoint, consequent authorizers
/// get ANDed while 0 acts as an OR gate, providing great flexibility in
/// forming an authorization policy out of simple building blocks. We could
/// also define a NOT gate here to achieve a full set of universal logic
/// gates, but that does not make much sense in this context because
/// authorizers tend to check for positive conditions (have paid, is
/// whitelisted, etc.) and we would not need policies that require these to
/// be false.
/// Note that authorizers should not start or end with 0, and 0s should
/// not be used consecutively (e.g., [X, Y, 0, 0, Z, T]).
/// [] returns false (deny everyone), [0] returns true (accept everyone).
/// @param providerId Provider ID from ProviderStore
/// @param requestId Request ID
/// @param endpointId Endpoint ID from EndpointStore
/// @param requesterIndex Requester index from RequesterStore
/// @param designatedWallet Designated wallet
/// @param clientAddress Client address
/// @return status Authorization status of the request
function checkAuthorizationStatus(
bytes32 providerId,
bytes32 requestId,
bytes32 endpointId,
uint256 requesterIndex,
address designatedWallet,
address clientAddress
)
public
view
override
returns(bool status)
{
address[] memory authorizers = airnode.getEndpointAuthorizers(providerId, endpointId);
uint256 noAuthorizers = authorizers.length;
// If no authorizers have been set, deny access by default
if (noAuthorizers == 0)
{
return false;
}
// authorizedByAll will remain true as long as none of the authorizers
// in a group reports that the client is unauthorized
bool authorizedByAll = true;
for (uint256 ind = 0; ind < noAuthorizers; ind++)
{
address authorizerAddress = authorizers[ind];
if (authorizerAddress == address(0)) {
// If we have reached a 0 without getting any unauthorized
// reports, we can return true
if (authorizedByAll) {
return true;
}
// Otherwise, reset authorizedByAll and start checking the next
// group
authorizedByAll = true;
}
// We only need to check the next authorizer if we have a good track
// record for this group
else if (authorizedByAll) {
IAuthorizer authorizer = IAuthorizer(authorizerAddress);
// Set authorizedByAll to false if we got an unauthorized report.
// This means that we will not be able to return a true from
// this group of authorizers.
if (!authorizer.checkIfAuthorized(
requestId, providerId, endpointId, requesterIndex, designatedWallet, clientAddress
)) {
authorizedByAll = false;
}
}
}
// Finally, if we have reached the end of the authorizers (i.e., we
// are at the last element of the last group), just return the current
// authorizedByAll, which will only be true if all authorizers from the
// last group have returned true.
return authorizedByAll;
}
/// @notice A convenience function to make multiple authorization status
/// checks with a single call
/// @param providerId Provider ID from ProviderStore
/// @param requestIds Request IDs
/// @param endpointIds Endpoint IDs from EndpointStore
/// @param requesterIndices Requester indices from RequesterStore
/// @param designatedWallets Designated wallets
/// @param clientAddresses Client addresses
/// @return statuses Authorization statuses of the request
function checkAuthorizationStatuses(
bytes32 providerId,
bytes32[] calldata requestIds,
bytes32[] calldata endpointIds,
uint256[] calldata requesterIndices,
address[] calldata designatedWallets,
address[] calldata clientAddresses
)
external
view
override
returns (bool[] memory statuses)
{
require(
requestIds.length == endpointIds.length
&& requestIds.length == requesterIndices.length
&& requestIds.length == designatedWallets.length
&& requestIds.length == clientAddresses.length,
"Parameter lengths must be equal"
);
statuses = new bool[](requestIds.length);
for (uint256 ind = 0; ind < requestIds.length; ind++)
{
statuses[ind] = checkAuthorizationStatus(
providerId,
requestIds[ind],
endpointIds[ind],
requesterIndices[ind],
designatedWallets[ind],
clientAddresses[ind]
);
}
}
}
| @notice A convenience function to retrieve multiple templates with a single call @param templateIds Request template IDs @return providerIds Provider IDs from ProviderStore @return endpointIds Endpoint IDs from EndpointStore @return requesterIndices Requester indices from RequesterStore @return designatedWallets Designated wallets that are requested to fulfill the request @return fulfillAddresses Addresses that will be called to fulfill @return fulfillFunctionIds Signatures of the functions that will be called to fulfill @return parameters Array of static request parameters (i.e., parameters that will not change between requests, unlike the dynamic parameters determined at runtime) | function getTemplates(bytes32[] calldata templateIds)
external
view
override
returns (
bytes32[] memory providerIds,
bytes32[] memory endpointIds,
uint256[] memory requesterIndices,
address[] memory designatedWallets,
address[] memory fulfillAddresses,
bytes4[] memory fulfillFunctionIds,
bytes[] memory parameters
)
{
providerIds = new bytes32[](templateIds.length);
endpointIds = new bytes32[](templateIds.length);
requesterIndices = new uint256[](templateIds.length);
designatedWallets = new address[](templateIds.length);
fulfillAddresses = new address[](templateIds.length);
fulfillFunctionIds = new bytes4[](templateIds.length);
parameters = new bytes[](templateIds.length);
for (uint256 ind = 0; ind < templateIds.length; ind++)
{
(
providerIds[ind],
endpointIds[ind],
requesterIndices[ind],
designatedWallets[ind],
fulfillAddresses[ind],
fulfillFunctionIds[ind],
parameters[ind]
) = airnode.getTemplate(templateIds[ind]);
}
}
| 5,360,032 | [
1,
37,
13553,
445,
358,
4614,
3229,
5539,
598,
279,
2202,
745,
225,
1542,
2673,
1567,
1542,
7115,
327,
2893,
2673,
7561,
7115,
628,
7561,
2257,
327,
2494,
2673,
6961,
7115,
628,
6961,
2257,
327,
19961,
8776,
868,
21207,
4295,
628,
868,
21207,
2257,
327,
25264,
26558,
2413,
29703,
690,
17662,
2413,
716,
854,
3764,
358,
22290,
326,
590,
327,
22290,
7148,
23443,
716,
903,
506,
2566,
358,
22290,
327,
22290,
2083,
2673,
4383,
2790,
434,
326,
4186,
716,
903,
506,
2566,
358,
22290,
327,
1472,
1510,
434,
760,
590,
1472,
261,
77,
18,
73,
12990,
1472,
716,
903,
486,
2549,
3086,
3285,
16,
640,
5625,
326,
5976,
1472,
11383,
622,
3099,
13,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
336,
8218,
12,
3890,
1578,
8526,
745,
892,
1542,
2673,
13,
203,
3639,
3903,
203,
3639,
1476,
203,
3639,
3849,
203,
3639,
1135,
261,
203,
5411,
1731,
1578,
8526,
3778,
2893,
2673,
16,
203,
5411,
1731,
1578,
8526,
3778,
2494,
2673,
16,
203,
5411,
2254,
5034,
8526,
3778,
19961,
8776,
16,
203,
5411,
1758,
8526,
3778,
25264,
26558,
2413,
16,
203,
5411,
1758,
8526,
3778,
22290,
7148,
16,
203,
5411,
1731,
24,
8526,
3778,
22290,
2083,
2673,
16,
203,
5411,
1731,
8526,
3778,
1472,
203,
3639,
262,
203,
565,
288,
203,
3639,
2893,
2673,
273,
394,
1731,
1578,
8526,
12,
3202,
2673,
18,
2469,
1769,
203,
3639,
2494,
2673,
273,
394,
1731,
1578,
8526,
12,
3202,
2673,
18,
2469,
1769,
203,
3639,
19961,
8776,
273,
394,
2254,
5034,
8526,
12,
3202,
2673,
18,
2469,
1769,
203,
3639,
25264,
26558,
2413,
273,
394,
1758,
8526,
12,
3202,
2673,
18,
2469,
1769,
203,
3639,
22290,
7148,
273,
394,
1758,
8526,
12,
3202,
2673,
18,
2469,
1769,
203,
3639,
22290,
2083,
2673,
273,
394,
1731,
24,
8526,
12,
3202,
2673,
18,
2469,
1769,
203,
3639,
1472,
273,
394,
1731,
8526,
12,
3202,
2673,
18,
2469,
1769,
203,
3639,
364,
261,
11890,
5034,
1547,
273,
374,
31,
1547,
411,
1542,
2673,
18,
2469,
31,
1547,
27245,
203,
3639,
288,
203,
5411,
261,
203,
7734,
2893,
2673,
63,
728,
6487,
203,
7734,
2494,
2673,
63,
728,
6487,
203,
7734,
19961,
8776,
63,
728,
6487,
203,
7734,
25264,
26558,
2413,
63,
728,
6487,
203,
7734,
22290,
7148,
63,
2
] |
// SPDX-License-Identifier: MIT
/**
* @authors: [@hbarcelos]
* @reviewers: [@ferittuncer*, @fnanni-0, @nix1g]
* @auditors: []
* @bounties: []
* @deployments: []
*/
pragma solidity ^0.7.2;
import "@kleros/erc-792/contracts/IArbitrator.sol";
import "@kleros/erc-792/contracts/IArbitrable.sol";
import "@kleros/erc-792/contracts/erc-1497/IEvidence.sol";
import "./dependencies/IAMB.sol";
import "./ArbitrationProxyInterfaces.sol";
contract RealitioForeignArbitrationProxy is IForeignArbitrationProxy, IArbitrable, IEvidence {
/// @dev The contract governor. TRUSTED.
address public governor = msg.sender;
/// @dev The address of the arbitrator. TRUSTED.
IArbitrator public immutable arbitrator;
/// @dev The extra data used to raise a dispute in the arbitrator.
bytes public arbitratorExtraData;
/// @dev The ID of the MetaEvidence for disputes.
uint256 public metaEvidenceID;
/// @dev The number of choices for the arbitrator.
uint256 public constant NUMBER_OF_CHOICES_FOR_ARBITRATOR = (2**256) - 2;
/// @dev ArbitraryMessageBridge contract address. TRUSTED.
IAMB public immutable amb;
/// @dev Address of the counter-party proxy on the Home Chain. TRUSTED.
address public homeProxy;
/// @dev The chain ID where the home proxy is deployed.
uint256 public homeChainId;
/// @dev The path for the Terms of Service for Kleros as an arbitrator for Realitio.
string public termsOfService;
enum Status {None, Requested, Created, Failed}
struct Arbitration {
// Status of the arbitration.
Status status;
// Address that made the arbitration request.
address payable requester;
// The deposit paid by the requester at the time of the arbitration.
uint256 deposit;
}
/// @dev Tracks arbitration requests for question ID.
mapping(bytes32 => Arbitration) public arbitrations;
/// @dev Associates dispute IDs to question IDs.
mapping(uint256 => bytes32) public disputeIDToQuestionID;
/**
* @notice Should be emitted when the arbitration is requested.
* @param _questionID The ID of the question to be arbitrated.
* @param _answer The answer provided by the requester.
* @param _requester The requester.
*/
event ArbitrationRequested(bytes32 indexed _questionID, bytes32 _answer, address indexed _requester);
/**
* @notice Should be emitted when the dispute is created.
* @param _questionID The ID of the question to be arbitrated.
* @param _disputeID The ID of the dispute.
*/
event ArbitrationCreated(bytes32 indexed _questionID, uint256 indexed _disputeID);
/**
* @notice Should be emitted when the dispute could not be created.
* @dev This will happen if there is an increase in the arbitration fees
* between the time the arbitration is made and the time it is acknowledged.
* @param _questionID The ID of the question to be arbitrated.
*/
event ArbitrationFailed(bytes32 indexed _questionID);
/**
* @notice Should be emitted when the arbitration is canceled by the Home Chain.
* @param _questionID The ID of the question to be arbitrated.
*/
event ArbitrationCanceled(bytes32 indexed _questionID);
modifier onlyArbitrator() {
require(msg.sender == address(arbitrator), "Only arbitrator allowed");
_;
}
modifier onlyGovernor() {
require(msg.sender == governor, "Only governor allowed");
_;
}
modifier onlyHomeProxy() {
require(msg.sender == address(amb), "Only AMB allowed");
require(amb.messageSourceChainId() == bytes32(homeChainId), "Only home chain allowed");
require(amb.messageSender() == homeProxy, "Only home proxy allowed");
_;
}
modifier onlyIfInitialized() {
require(homeProxy != address(0), "Not initialized yet");
_;
}
/**
* @notice Creates an arbitration proxy on the foreign chain.
* @dev Contract will still require initialization before being usable.
* @param _amb ArbitraryMessageBridge contract address.
* @param _arbitrator Arbitrator contract address.
* @param _arbitratorExtraData The extra data used to raise a dispute in the arbitrator.
* @param _metaEvidence The URI of the meta evidence file.
* @param _termsOfService The path for the Terms of Service for Kleros as an arbitrator for Realitio.
*/
constructor(
IAMB _amb,
IArbitrator _arbitrator,
bytes memory _arbitratorExtraData,
string memory _metaEvidence,
string memory _termsOfService
) {
amb = _amb;
arbitrator = _arbitrator;
arbitratorExtraData = _arbitratorExtraData;
termsOfService = _termsOfService;
emit MetaEvidence(metaEvidenceID, _metaEvidence);
}
/**
* @notice Changes the address of a new governor.
* @param _governor The address of the new governor.
*/
function changeGovernor(address _governor) external onlyGovernor {
governor = _governor;
}
/**
* @notice Sets the address of the arbitration proxy on the Home Chain.
* @param _homeProxy The address of the proxy.
* @param _homeChainId The chain ID where the home proxy is deployed.
*/
function setHomeProxy(address _homeProxy, uint256 _homeChainId) external onlyGovernor {
require(homeProxy == address(0), "Home proxy already set");
homeProxy = _homeProxy;
homeChainId = _homeChainId;
}
/**
* @notice Changes the meta evidence used for disputes.
* @param _metaEvidence URI to the new meta evidence file.
*/
function changeMetaEvidence(string calldata _metaEvidence) external onlyGovernor {
metaEvidenceID += 1;
emit MetaEvidence(metaEvidenceID, _metaEvidence);
}
/**
* @notice Changes the terms of service for Realitio.
* @param _termsOfService URI to the new Terms of Service file.
*/
function changeTermsOfService(string calldata _termsOfService) external onlyGovernor {
termsOfService = _termsOfService;
}
/**
* @notice Requests arbitration for given question ID.
* @dev Can be executed only if the contract has been initialized.
* @param _questionID The ID of the question.
* @param _contestedAnswer The answer the requester deems to be incorrect.
*/
function requestArbitration(bytes32 _questionID, bytes32 _contestedAnswer) external payable onlyIfInitialized {
Arbitration storage arbitration = arbitrations[_questionID];
require(arbitration.status == Status.None, "Arbitration already requested");
uint256 arbitrationCost = arbitrator.arbitrationCost(arbitratorExtraData);
require(msg.value >= arbitrationCost, "Deposit value too low");
arbitration.status = Status.Requested;
arbitration.requester = msg.sender;
arbitration.deposit = msg.value;
bytes4 methodSelector = IHomeArbitrationProxy(0).receiveArbitrationRequest.selector;
bytes memory data = abi.encodeWithSelector(methodSelector, _questionID, _contestedAnswer, msg.sender);
amb.requireToPassMessage(homeProxy, data, amb.maxGasPerTx());
emit ArbitrationRequested(_questionID, _contestedAnswer, msg.sender);
}
/**
* @notice Requests arbitration for given question ID.
* @param _questionID The ID of the question.
*/
function acknowledgeArbitration(bytes32 _questionID) external override onlyHomeProxy {
Arbitration storage arbitration = arbitrations[_questionID];
require(arbitration.status == Status.Requested, "Invalid arbitration status");
uint256 arbitrationCost = arbitrator.arbitrationCost(arbitratorExtraData);
if (arbitration.deposit >= arbitrationCost) {
try
arbitrator.createDispute{value: arbitrationCost}(NUMBER_OF_CHOICES_FOR_ARBITRATOR, arbitratorExtraData)
returns (uint256 disputeID) {
disputeIDToQuestionID[disputeID] = _questionID;
// At this point, arbitration.deposit is guaranteed to be greater than or equal to the arbitration cost.
uint256 remainder = arbitration.deposit - arbitrationCost;
arbitration.status = Status.Created;
arbitration.deposit = 0;
if (remainder > 0) {
arbitration.requester.send(remainder);
}
emit ArbitrationCreated(_questionID, disputeID);
emit Dispute(arbitrator, disputeID, metaEvidenceID, uint256(_questionID));
} catch {
arbitration.status = Status.Failed;
emit ArbitrationFailed(_questionID);
}
} else {
arbitration.status = Status.Failed;
emit ArbitrationFailed(_questionID);
}
}
/**
* @notice Cancels the arbitration.
* @param _questionID The ID of the question.
*/
function cancelArbitration(bytes32 _questionID) external override onlyHomeProxy {
Arbitration storage arbitration = arbitrations[_questionID];
require(arbitration.status == Status.Requested, "Invalid arbitration status");
arbitration.requester.send(arbitration.deposit);
delete arbitrations[_questionID];
emit ArbitrationCanceled(_questionID);
}
/**
* @notice Cancels the arbitration in case the dispute could not be created.
* @param _questionID The ID of the question.
*/
function handleFailedDisputeCreation(bytes32 _questionID) external onlyIfInitialized {
Arbitration storage arbitration = arbitrations[_questionID];
require(arbitration.status == Status.Failed, "Invalid arbitration status");
arbitration.requester.send(arbitration.deposit);
delete arbitrations[_questionID];
bytes4 methodSelector = IHomeArbitrationProxy(0).receiveArbitrationFailure.selector;
bytes memory data = abi.encodeWithSelector(methodSelector, _questionID);
amb.requireToPassMessage(homeProxy, data, amb.maxGasPerTx());
emit ArbitrationCanceled(_questionID);
}
/**
* @notice Rules a specified dispute.
* @dev Note that 0 is reserved for "Unable/refused to arbitrate" and we map it to `bytes32(-1)` which has a similar connotation in Realitio.
* @param _disputeID The ID of the dispute in the ERC792 arbitrator.
* @param _ruling The ruling given by the arbitrator.
*/
function rule(uint256 _disputeID, uint256 _ruling) external override onlyArbitrator {
bytes32 questionID = disputeIDToQuestionID[_disputeID];
Arbitration storage arbitration = arbitrations[questionID];
require(arbitration.status == Status.Created, "Invalid arbitration status");
delete arbitrations[questionID];
delete disputeIDToQuestionID[_disputeID];
// Realitio ruling is shifted by 1 compared to Kleros.
// For example, jurors refusing to rule is `0` on Kleros, but uint(-1) on Realitio.
// The line below could be written more explicitly as:
// bytes32(_ruling == 0 ? uint256(-1) : _ruling - 1)
// But the way it is written saves some gas.
bytes32 answer = bytes32(_ruling - 1);
bytes4 methodSelector = IHomeArbitrationProxy(0).receiveArbitrationAnswer.selector;
bytes memory data = abi.encodeWithSelector(methodSelector, questionID, answer);
amb.requireToPassMessage(homeProxy, data, amb.maxGasPerTx());
emit Ruling(arbitrator, _disputeID, _ruling);
}
/**
* @notice Gets the fee to create a dispute.
* @return The fee to create a dispute.
*/
function getDisputeFee(bytes32 questionID) external view override returns (uint256) {
return arbitrator.arbitrationCost(arbitratorExtraData);
}
}
| * @notice Cancels the arbitration. @param _questionID The ID of the question./ | function cancelArbitration(bytes32 _questionID) external override onlyHomeProxy {
Arbitration storage arbitration = arbitrations[_questionID];
require(arbitration.status == Status.Requested, "Invalid arbitration status");
arbitration.requester.send(arbitration.deposit);
delete arbitrations[_questionID];
emit ArbitrationCanceled(_questionID);
}
| 2,472,525 | [
1,
6691,
87,
326,
10056,
7034,
18,
225,
389,
4173,
734,
1021,
1599,
434,
326,
5073,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
3755,
686,
3682,
7034,
12,
3890,
1578,
389,
4173,
734,
13,
3903,
3849,
1338,
8684,
3886,
288,
203,
3639,
1201,
3682,
7034,
2502,
10056,
7034,
273,
10056,
86,
1012,
63,
67,
4173,
734,
15533,
203,
3639,
2583,
12,
297,
3682,
7034,
18,
2327,
422,
2685,
18,
11244,
16,
315,
1941,
10056,
7034,
1267,
8863,
203,
203,
3639,
10056,
7034,
18,
26192,
18,
4661,
12,
297,
3682,
7034,
18,
323,
1724,
1769,
203,
203,
3639,
1430,
10056,
86,
1012,
63,
67,
4173,
734,
15533,
203,
203,
3639,
3626,
1201,
3682,
7034,
23163,
24899,
4173,
734,
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
] |
./full_match/80001/0xd0f330338c533a0394d1533E47a8a4425E0Fd076/sources/contracts/Staking.sol | * Header: Withdraw staking token rewards [var] _amount: Amount of staking tokens note: Used to withdraw tokens from the contract to stake on CLM/ to prevent locking of direct-transferred tokensderivativeTokenBalance = _amount > derivativeTokenBalance ? 0 : derivativeTokenBalance - _amount; | function _WithdrawTokens(uint _amount) internal {
require(msg.sender == owner(), "Not authorized");
require(thisContract.balance >= _amount, "Not enough tokens in contract");
payable(msg.sender).transfer(_amount);
}
| 9,496,565 | [
1,
1864,
30,
3423,
9446,
384,
6159,
1147,
283,
6397,
225,
306,
1401,
65,
389,
8949,
30,
16811,
434,
384,
6159,
2430,
225,
4721,
30,
10286,
358,
598,
9446,
2430,
628,
326,
6835,
358,
384,
911,
603,
14934,
49,
19,
358,
5309,
18887,
434,
2657,
17,
2338,
4193,
2430,
20615,
1535,
1345,
13937,
273,
389,
8949,
405,
16417,
1345,
13937,
692,
374,
294,
16417,
1345,
13937,
300,
389,
8949,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
389,
1190,
9446,
5157,
12,
11890,
389,
8949,
13,
2713,
288,
203,
3639,
2583,
12,
3576,
18,
15330,
422,
3410,
9334,
315,
1248,
10799,
8863,
203,
3639,
2583,
12,
2211,
8924,
18,
12296,
1545,
389,
8949,
16,
315,
1248,
7304,
2430,
316,
6835,
8863,
203,
203,
3639,
8843,
429,
12,
3576,
18,
15330,
2934,
13866,
24899,
8949,
1769,
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
] |
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../../utils/Context.sol";
import "./IERC20.sol";
import "../../math/SafeMath.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name_, string memory symbol_) public {
_name = name_;
_symbol = symbol_;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal virtual {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IExternalPosition Contract
/// @author Enzyme Council <[email protected]>
interface IExternalPosition {
function getDebtAssets() external returns (address[] memory, uint256[] memory);
function getManagedAssets() external returns (address[] memory, uint256[] memory);
function init(bytes memory) external;
function receiveCallFromVault(bytes memory) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title AaveDebtPositionLibBase1 Contract
/// @author Enzyme Council <[email protected]>
/// @notice A persistent contract containing all required storage variables and
/// required functions for a AaveDebtPositionLib implementation
/// @dev DO NOT EDIT CONTRACT. If new events or storage are necessary, they should be added to
/// a numbered AaveDebtPositionLibBaseXXX that inherits the previous base.
/// e.g., `AaveDebtPositionLibBase2 is AaveDebtPositionLibBase1`
contract AaveDebtPositionLibBase1 {
event BorrowedAssetAdded(address indexed asset);
event BorrowedAssetRemoved(address indexed asset);
event CollateralAssetAdded(address indexed asset);
event CollateralAssetRemoved(address indexed asset);
address[] internal borrowedAssets;
address[] internal collateralAssets;
// Rather than storing a boolean, stores the associated debt token to save gas for future lookups
mapping(address => address) internal borrowedAssetToDebtToken;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title AaveDebtPositionDataDecoder Contract
/// @author Enzyme Council <[email protected]>
/// @notice Abstract contract containing data decodings for AaveDebtPosition payloads
abstract contract AaveDebtPositionDataDecoder {
/// @dev Helper to decode args used during the AddCollateral action
function __decodeAddCollateralActionArgs(bytes memory _actionArgs)
internal
pure
returns (address[] memory aTokens_, uint256[] memory amounts_)
{
return abi.decode(_actionArgs, (address[], uint256[]));
}
/// @dev Helper to decode args used during the Borrow action
function __decodeBorrowActionArgs(bytes memory _actionArgs)
internal
pure
returns (address[] memory tokens_, uint256[] memory amounts_)
{
return abi.decode(_actionArgs, (address[], uint256[]));
}
/// @dev Helper to decode args used during the ClaimRewards action
function __decodeClaimRewardsActionArgs(bytes memory _actionArgs)
internal
pure
returns (address[] memory assets_)
{
return abi.decode(_actionArgs, (address[]));
}
/// @dev Helper to decode args used during the RemoveCollateral action
function __decodeRemoveCollateralActionArgs(bytes memory _actionArgs)
internal
pure
returns (address[] memory aTokens_, uint256[] memory amounts_)
{
return abi.decode(_actionArgs, (address[], uint256[]));
}
/// @dev Helper to decode args used during the RepayBorrow action
function __decodeRepayBorrowActionArgs(bytes memory _actionArgs)
internal
pure
returns (address[] memory tokens_, uint256[] memory amounts_)
{
return abi.decode(_actionArgs, (address[], uint256[]));
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "../../../../../persistent/external-positions/aave-debt/AaveDebtPositionLibBase1.sol";
import "../../../../interfaces/IAaveIncentivesController.sol";
import "../../../../interfaces/IAaveLendingPool.sol";
import "../../../../interfaces/IAaveLendingPoolAddressProvider.sol";
import "../../../../interfaces/IAaveProtocolDataProvider.sol";
import "../../../../utils/AddressArrayLib.sol";
import "../../../../utils/AssetHelpers.sol";
import "./AaveDebtPositionDataDecoder.sol";
import "./IAaveDebtPosition.sol";
/// @title AaveDebtPositionLib Contract
/// @author Enzyme Council <[email protected]>
/// @notice An External Position library contract for Aave debt positions
contract AaveDebtPositionLib is
AaveDebtPositionLibBase1,
IAaveDebtPosition,
AaveDebtPositionDataDecoder,
AssetHelpers
{
using AddressArrayLib for address[];
using SafeERC20 for ERC20;
uint16 private constant AAVE_REFERRAL_CODE = 158;
address private immutable AAVE_DATA_PROVIDER;
address private immutable AAVE_INCENTIVES_CONTROLLER;
address private immutable AAVE_LENDING_POOL_ADDRESS_PROVIDER;
uint256 private constant VARIABLE_INTEREST_RATE = 2;
constructor(
address _aaveDataProvider,
address _aaveLendingPoolAddressProvider,
address _aaveIncentivesController
) public {
AAVE_DATA_PROVIDER = _aaveDataProvider;
AAVE_LENDING_POOL_ADDRESS_PROVIDER = _aaveLendingPoolAddressProvider;
AAVE_INCENTIVES_CONTROLLER = _aaveIncentivesController;
}
/// @notice Initializes the external position
/// @dev Nothing to initialize for this contract
function init(bytes memory) external override {}
/// @notice Receives and executes a call from the Vault
/// @param _actionData Encoded data to execute the action
function receiveCallFromVault(bytes memory _actionData) external override {
(uint256 actionId, bytes memory actionArgs) = abi.decode(_actionData, (uint256, bytes));
if (actionId == uint256(Actions.AddCollateral)) {
__addCollateralAssets(actionArgs);
} else if (actionId == uint256(Actions.RemoveCollateral)) {
__removeCollateralAssets(actionArgs);
} else if (actionId == uint256(Actions.Borrow)) {
__borrowAssets(actionArgs);
} else if (actionId == uint256(Actions.RepayBorrow)) {
__repayBorrowedAssets(actionArgs);
} else if (actionId == uint256(Actions.ClaimRewards)) {
__claimRewards(actionArgs);
} else {
revert("receiveCallFromVault: Invalid actionId");
}
}
/// @dev Receives and adds aTokens as collateral
function __addCollateralAssets(bytes memory actionArgs) private {
(address[] memory aTokens, ) = __decodeAddCollateralActionArgs(actionArgs);
for (uint256 i; i < aTokens.length; i++) {
if (!assetIsCollateral(aTokens[i])) {
collateralAssets.push(aTokens[i]);
emit CollateralAssetAdded(aTokens[i]);
}
}
}
/// @dev Borrows assets using the available collateral
function __borrowAssets(bytes memory actionArgs) private {
(address[] memory tokens, uint256[] memory amounts) = __decodeBorrowActionArgs(actionArgs);
address lendingPoolAddress = IAaveLendingPoolAddressProvider(
AAVE_LENDING_POOL_ADDRESS_PROVIDER
)
.getLendingPool();
for (uint256 i; i < tokens.length; i++) {
IAaveLendingPool(lendingPoolAddress).borrow(
tokens[i],
amounts[i],
VARIABLE_INTEREST_RATE,
AAVE_REFERRAL_CODE,
address(this)
);
ERC20(tokens[i]).safeTransfer(msg.sender, amounts[i]);
if (!assetIsBorrowed(tokens[i])) {
// Store the debt token as a flag that the token is now a borrowed asset
(, , address debtToken) = IAaveProtocolDataProvider(AAVE_DATA_PROVIDER)
.getReserveTokensAddresses(tokens[i]);
borrowedAssetToDebtToken[tokens[i]] = debtToken;
borrowedAssets.push(tokens[i]);
emit BorrowedAssetAdded(tokens[i]);
}
}
}
/// @dev Claims all rewards accrued and send it to the Vault
function __claimRewards(bytes memory actionArgs) private {
address[] memory assets = __decodeClaimRewardsActionArgs(actionArgs);
IAaveIncentivesController(AAVE_INCENTIVES_CONTROLLER).claimRewards(
assets,
type(uint256).max,
msg.sender
);
}
/// @dev Removes assets from collateral
function __removeCollateralAssets(bytes memory actionArgs) private {
(address[] memory aTokens, uint256[] memory amounts) = __decodeRemoveCollateralActionArgs(
actionArgs
);
for (uint256 i; i < aTokens.length; i++) {
require(
assetIsCollateral(aTokens[i]),
"__removeCollateralAssets: Invalid collateral asset"
);
uint256 collateralBalance = ERC20(aTokens[i]).balanceOf(address(this));
if (amounts[i] == type(uint256).max) {
amounts[i] = collateralBalance;
}
// If the full collateral of an asset is removed, it can be removed from collateral assets
if (amounts[i] == collateralBalance) {
collateralAssets.removeStorageItem(aTokens[i]);
emit CollateralAssetRemoved(aTokens[i]);
}
ERC20(aTokens[i]).safeTransfer(msg.sender, amounts[i]);
}
}
/// @dev Repays borrowed assets, reducing the borrow balance
function __repayBorrowedAssets(bytes memory actionArgs) private {
(address[] memory tokens, uint256[] memory amounts) = __decodeRepayBorrowActionArgs(
actionArgs
);
address lendingPoolAddress = IAaveLendingPoolAddressProvider(
AAVE_LENDING_POOL_ADDRESS_PROVIDER
)
.getLendingPool();
for (uint256 i; i < tokens.length; i++) {
require(assetIsBorrowed(tokens[i]), "__repayBorrowedAssets: Invalid borrowed asset");
__approveAssetMaxAsNeeded(tokens[i], lendingPoolAddress, amounts[i]);
IAaveLendingPool(lendingPoolAddress).repay(
tokens[i],
amounts[i],
VARIABLE_INTEREST_RATE,
address(this)
);
uint256 remainingBalance = ERC20(tokens[i]).balanceOf(address(this));
if (remainingBalance > 0) {
ERC20(tokens[i]).safeTransfer(msg.sender, remainingBalance);
}
// Remove borrowed asset state from storage, if there is no remaining borrowed balance
if (ERC20(getDebtTokenForBorrowedAsset(tokens[i])).balanceOf(address(this)) == 0) {
delete borrowedAssetToDebtToken[tokens[i]];
borrowedAssets.removeStorageItem(tokens[i]);
emit BorrowedAssetRemoved(tokens[i]);
}
}
}
////////////////////
// POSITION VALUE //
////////////////////
/// @notice Retrieves the debt assets (negative value) of the external position
/// @return assets_ Debt assets
/// @return amounts_ Debt asset amounts
function getDebtAssets()
external
override
returns (address[] memory assets_, uint256[] memory amounts_)
{
assets_ = borrowedAssets;
amounts_ = new uint256[](assets_.length);
for (uint256 i; i < assets_.length; i++) {
amounts_[i] = ERC20(getDebtTokenForBorrowedAsset(assets_[i])).balanceOf(address(this));
}
return (assets_, amounts_);
}
/// @notice Retrieves the managed assets (positive value) of the external position
/// @return assets_ Managed assets
/// @return amounts_ Managed asset amounts
function getManagedAssets()
external
override
returns (address[] memory assets_, uint256[] memory amounts_)
{
assets_ = collateralAssets;
amounts_ = new uint256[](collateralAssets.length);
for (uint256 i; i < assets_.length; i++) {
amounts_[i] = ERC20(assets_[i]).balanceOf(address(this));
}
return (assets_, amounts_);
}
///////////////////
// STATE GETTERS //
///////////////////
/// @dev Checks whether an asset is borrowed
/// @return isBorrowed_ True if the asset is part of the borrowed assets of the external position
function assetIsBorrowed(address _asset) public view returns (bool isBorrowed_) {
return getDebtTokenForBorrowedAsset(_asset) != address(0);
}
/// @notice Checks whether an asset is collateral
/// @return isCollateral_ True if the asset is part of the collateral assets of the external position
function assetIsCollateral(address _asset) public view returns (bool isCollateral_) {
return collateralAssets.contains(_asset);
}
/// @notice Gets the debt token associated with a specified asset that has been borrowed
/// @param _borrowedAsset The asset that has been borrowed
/// @return debtToken_ The associated debt token
/// @dev Returns empty if _borrowedAsset is not a valid borrowed asset
function getDebtTokenForBorrowedAsset(address _borrowedAsset)
public
view
override
returns (address debtToken_)
{
return borrowedAssetToDebtToken[_borrowedAsset];
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
import "../../../../../persistent/external-positions/IExternalPosition.sol";
pragma solidity 0.6.12;
/// @title IAaveDebtPosition Interface
/// @author Enzyme Council <[email protected]>
interface IAaveDebtPosition is IExternalPosition {
enum Actions {AddCollateral, RemoveCollateral, Borrow, RepayBorrow, ClaimRewards}
function getDebtTokenForBorrowedAsset(address) external view returns (address);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IAaveIncentivesController interface
/// @author Enzyme Council <[email protected]>
interface IAaveIncentivesController {
function claimRewards(
address[] memory,
uint256,
address
) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IAaveLendingPool interface
/// @author Enzyme Council <[email protected]>
interface IAaveLendingPool {
function borrow(
address,
uint256,
uint256,
uint16,
address
) external;
function deposit(
address,
uint256,
address,
uint16
) external;
function repay(
address,
uint256,
uint256,
address
) external returns (uint256);
function withdraw(
address,
uint256,
address
) external returns (uint256);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IAaveLendingPoolAddressProvider interface
/// @author Enzyme Council <[email protected]>
interface IAaveLendingPoolAddressProvider {
function getLendingPool() external view returns (address);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IAaveProtocolDataProvider interface
/// @author Enzyme Council <[email protected]>
interface IAaveProtocolDataProvider {
function getReserveTokensAddresses(address)
external
view
returns (
address,
address,
address
);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title AddressArray Library
/// @author Enzyme Council <[email protected]>
/// @notice A library to extend the address array data type
library AddressArrayLib {
/////////////
// STORAGE //
/////////////
/// @dev Helper to remove an item from a storage array
function removeStorageItem(address[] storage _self, address _itemToRemove)
internal
returns (bool removed_)
{
uint256 itemCount = _self.length;
for (uint256 i; i < itemCount; i++) {
if (_self[i] == _itemToRemove) {
if (i < itemCount - 1) {
_self[i] = _self[itemCount - 1];
}
_self.pop();
removed_ = true;
break;
}
}
return removed_;
}
////////////
// MEMORY //
////////////
/// @dev Helper to add an item to an array. Does not assert uniqueness of the new item.
function addItem(address[] memory _self, address _itemToAdd)
internal
pure
returns (address[] memory nextArray_)
{
nextArray_ = new address[](_self.length + 1);
for (uint256 i; i < _self.length; i++) {
nextArray_[i] = _self[i];
}
nextArray_[_self.length] = _itemToAdd;
return nextArray_;
}
/// @dev Helper to add an item to an array, only if it is not already in the array.
function addUniqueItem(address[] memory _self, address _itemToAdd)
internal
pure
returns (address[] memory nextArray_)
{
if (contains(_self, _itemToAdd)) {
return _self;
}
return addItem(_self, _itemToAdd);
}
/// @dev Helper to verify if an array contains a particular value
function contains(address[] memory _self, address _target)
internal
pure
returns (bool doesContain_)
{
for (uint256 i; i < _self.length; i++) {
if (_target == _self[i]) {
return true;
}
}
return false;
}
/// @dev Helper to merge the unique items of a second array.
/// Does not consider uniqueness of either array, only relative uniqueness.
/// Preserves ordering.
function mergeArray(address[] memory _self, address[] memory _arrayToMerge)
internal
pure
returns (address[] memory nextArray_)
{
uint256 newUniqueItemCount;
for (uint256 i; i < _arrayToMerge.length; i++) {
if (!contains(_self, _arrayToMerge[i])) {
newUniqueItemCount++;
}
}
if (newUniqueItemCount == 0) {
return _self;
}
nextArray_ = new address[](_self.length + newUniqueItemCount);
for (uint256 i; i < _self.length; i++) {
nextArray_[i] = _self[i];
}
uint256 nextArrayIndex = _self.length;
for (uint256 i; i < _arrayToMerge.length; i++) {
if (!contains(_self, _arrayToMerge[i])) {
nextArray_[nextArrayIndex] = _arrayToMerge[i];
nextArrayIndex++;
}
}
return nextArray_;
}
/// @dev Helper to verify if array is a set of unique values.
/// Does not assert length > 0.
function isUniqueSet(address[] memory _self) internal pure returns (bool isUnique_) {
if (_self.length <= 1) {
return true;
}
uint256 arrayLength = _self.length;
for (uint256 i; i < arrayLength; i++) {
for (uint256 j = i + 1; j < arrayLength; j++) {
if (_self[i] == _self[j]) {
return false;
}
}
}
return true;
}
/// @dev Helper to remove items from an array. Removes all matching occurrences of each item.
/// Does not assert uniqueness of either array.
function removeItems(address[] memory _self, address[] memory _itemsToRemove)
internal
pure
returns (address[] memory nextArray_)
{
if (_itemsToRemove.length == 0) {
return _self;
}
bool[] memory indexesToRemove = new bool[](_self.length);
uint256 remainingItemsCount = _self.length;
for (uint256 i; i < _self.length; i++) {
if (contains(_itemsToRemove, _self[i])) {
indexesToRemove[i] = true;
remainingItemsCount--;
}
}
if (remainingItemsCount == _self.length) {
nextArray_ = _self;
} else if (remainingItemsCount > 0) {
nextArray_ = new address[](remainingItemsCount);
uint256 nextArrayIndex;
for (uint256 i; i < _self.length; i++) {
if (!indexesToRemove[i]) {
nextArray_[nextArrayIndex] = _self[i];
nextArrayIndex++;
}
}
}
return nextArray_;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
/// @title AssetHelpers Contract
/// @author Enzyme Council <[email protected]>
/// @notice A util contract for common token actions
abstract contract AssetHelpers {
using SafeERC20 for ERC20;
using SafeMath for uint256;
/// @dev Helper to approve a target account with the max amount of an asset.
/// This is helpful for fully trusted contracts, such as adapters that
/// interact with external protocol like Uniswap, Compound, etc.
function __approveAssetMaxAsNeeded(
address _asset,
address _target,
uint256 _neededAmount
) internal {
uint256 allowance = ERC20(_asset).allowance(address(this), _target);
if (allowance < _neededAmount) {
if (allowance > 0) {
ERC20(_asset).safeApprove(_target, 0);
}
ERC20(_asset).safeApprove(_target, type(uint256).max);
}
}
/// @dev Helper to transfer full asset balances from the current contract to a target
function __pushFullAssetBalances(address _target, address[] memory _assets)
internal
returns (uint256[] memory amountsTransferred_)
{
amountsTransferred_ = new uint256[](_assets.length);
for (uint256 i; i < _assets.length; i++) {
ERC20 assetContract = ERC20(_assets[i]);
amountsTransferred_[i] = assetContract.balanceOf(address(this));
if (amountsTransferred_[i] > 0) {
assetContract.safeTransfer(_target, amountsTransferred_[i]);
}
}
return amountsTransferred_;
}
} | @notice Retrieves the debt assets (negative value) of the external position @return assets_ Debt assets @return amounts_ Debt asset amounts | function getDebtAssets()
external
override
returns (address[] memory assets_, uint256[] memory amounts_)
{
assets_ = borrowedAssets;
amounts_ = new uint256[](assets_.length);
for (uint256 i; i < assets_.length; i++) {
amounts_[i] = ERC20(getDebtTokenForBorrowedAsset(assets_[i])).balanceOf(address(this));
}
return (assets_, amounts_);
}
| 381,982 | [
1,
6960,
326,
18202,
88,
7176,
261,
13258,
460,
13,
434,
326,
3903,
1754,
327,
7176,
67,
1505,
23602,
7176,
327,
30980,
67,
1505,
23602,
3310,
30980,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
336,
758,
23602,
10726,
1435,
203,
3639,
3903,
203,
3639,
3849,
203,
3639,
1135,
261,
2867,
8526,
3778,
7176,
67,
16,
2254,
5034,
8526,
3778,
30980,
67,
13,
203,
565,
288,
203,
3639,
7176,
67,
273,
29759,
329,
10726,
31,
203,
3639,
30980,
67,
273,
394,
2254,
5034,
8526,
12,
9971,
27799,
2469,
1769,
203,
203,
3639,
364,
261,
11890,
5034,
277,
31,
277,
411,
7176,
27799,
2469,
31,
277,
27245,
288,
203,
5411,
30980,
67,
63,
77,
65,
273,
4232,
39,
3462,
12,
588,
758,
23602,
1345,
1290,
38,
15318,
329,
6672,
12,
9971,
67,
63,
77,
5717,
2934,
12296,
951,
12,
2867,
12,
2211,
10019,
203,
3639,
289,
203,
203,
3639,
327,
261,
9971,
67,
16,
30980,
67,
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
] |
pragma solidity ^0.4.20;
/*
* Welcome to harjcoin
* ==========================*
d8888b. d88888b db db d888888b d8888b. db db .d8b. d8888b. d88b
88 `8D 88' 88 88 `88' 88 `8D 88 88 d8' `8b 88 `8D `8P'
88 88 88ooooo Y8 8P 88 88 88 88ooo88 88ooo88 88oobY' 88
88 88 88~~~~~ `8b d8' 88 88 88 88~~~88 88~~~88 88`8b 88
88 .8D 88. `8bd8' .88. 88 .8D 88 88 88 88 88 `88. db. 88
Y8888D' Y88888P YP Y888888P Y8888D' YP YP YP YP 88 YD Y8888P
* -> What?
* This source code is copy of Proof of Weak Legs (POWL) which is copy of POWH3D
* Only difference is that, you will receive 25% dividends.
*/
contract PODEVIDHARJ {
/*=================================
= MODIFIERS =
=================================*/
// only people with tokens
modifier onlyBagholders() {
require(myTokens() > 0);
_;
}
// only people with profits
modifier onlyStronghands() {
require(myDividends(true) > 0);
_;
}
// administrators can:
// -> change the name of the contract
// -> change the name of the token
// -> change the PoS difficulty (How many tokens it costs to hold a masternode, in case it gets crazy high later)
// they CANNOT:
// -> take funds
// -> disable withdrawals
// -> kill the contract
// -> change the price of tokens
modifier onlyAdministrator(){
address _customerAddress = msg.sender;
require(administrators[keccak256(_customerAddress)]);
_;
}
// ensures that the first tokens in the contract will be equally distributed
// meaning, no divine dump will be ever possible
// result: healthy longevity.
modifier antiEarlyWhale(uint256 _amountOfEthereum){
address _customerAddress = msg.sender;
// are we still in the vulnerable phase?
// if so, enact anti early whale protocol
if( onlyAmbassadors && ((totalEthereumBalance() - _amountOfEthereum) <= ambassadorQuota_ )){
require(
// is the customer in the ambassador list?
ambassadors_[_customerAddress] == true &&
// does the customer purchase exceed the max ambassador quota?
(ambassadorAccumulatedQuota_[_customerAddress] + _amountOfEthereum) <= ambassadorMaxPurchase_
);
// updated the accumulated quota
ambassadorAccumulatedQuota_[_customerAddress] = SafeMath.add(ambassadorAccumulatedQuota_[_customerAddress], _amountOfEthereum);
// execute
_;
} else {
// in case the ether count drops low, the ambassador phase won't reinitiate
onlyAmbassadors = false;
_;
}
}
/*==============================
= EVENTS =
==============================*/
event onTokenPurchase(
address indexed customerAddress,
uint256 incomingEthereum,
uint256 tokensMinted,
address indexed referredBy
);
event onTokenSell(
address indexed customerAddress,
uint256 tokensBurned,
uint256 ethereumEarned
);
event onReinvestment(
address indexed customerAddress,
uint256 ethereumReinvested,
uint256 tokensMinted
);
event onWithdraw(
address indexed customerAddress,
uint256 ethereumWithdrawn
);
// ERC20
event Transfer(
address indexed from,
address indexed to,
uint256 tokens
);
/*=====================================
= CONFIGURABLES =
=====================================*/
string public name = "DEVIDHARJ";
string public symbol = "DEVIDHARJ";
uint8 constant public decimals = 18;
uint8 constant internal dividendFee_ = 100;
uint256 constant internal tokenPriceInitial_ = 0.0000001 ether;
uint256 constant internal tokenPriceIncremental_ = 0.00000001 ether;
uint256 constant internal magnitude = 2**64;
// proof of stake (defaults at 100 tokens)
uint256 public stakingRequirement = 5e18;
// ambassador program
mapping(address => bool) internal ambassadors_;
uint256 constant internal ambassadorMaxPurchase_ = 10 ether;
uint256 constant internal ambassadorQuota_ = 10 ether;
/*================================
= DATASETS =
================================*/
// amount of shares for each address (scaled number)
mapping(address => uint256) internal tokenBalanceLedger_;
mapping(address => uint256) internal referralBalance_;
mapping(address => int256) internal payoutsTo_;
mapping(address => uint256) internal ambassadorAccumulatedQuota_;
uint256 internal tokenSupply_ = 0;
uint256 internal profitPerShare_;
// administrator list (see above on what they can do)
mapping(bytes32 => bool) public administrators;
// when this is set to true, only ambassadors can purchase tokens (this prevents a whale premine, it ensures a fairly distributed upper pyramid)
bool public onlyAmbassadors = false;
/*=======================================
= PUBLIC FUNCTIONS =
=======================================*/
/*
* -- APPLICATION ENTRY POINTS --
*/
function Hourglass()
public
{
}
/**
* Converts all incoming ethereum to tokens for the caller, and passes down the referral addy (if any)
*/
function buy(address _referredBy)
public
payable
returns(uint256)
{
purchaseTokens(msg.value, _referredBy);
}
/**
* Fallback function to handle ethereum that was send straight to the contract
* Unfortunately we cannot use a referral address this way.
*/
function()
payable
public
{
purchaseTokens(msg.value, 0x0);
}
/**
* Converts all of caller's dividends to tokens.
*/
function reinvest()
onlyStronghands()
public
{
// fetch dividends
uint256 _dividends = myDividends(false); // retrieve ref. bonus later in the code
// pay out the dividends virtually
address _customerAddress = msg.sender;
payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude);
// retrieve ref. bonus
_dividends += referralBalance_[_customerAddress];
referralBalance_[_customerAddress] = 0;
// dispatch a buy order with the virtualized "withdrawn dividends"
uint256 _tokens = purchaseTokens(_dividends, 0x0);
// fire event
onReinvestment(_customerAddress, _dividends, _tokens);
}
/**
* Alias of sell() and withdraw().
*/
function exit()
public
{
// get token count for caller & sell them all
address _customerAddress = msg.sender;
uint256 _tokens = tokenBalanceLedger_[_customerAddress];
if(_tokens > 0) sell(_tokens);
// lambo delivery service
withdraw();
}
/**
* Withdraws all of the callers earnings.
*/
function withdraw()
onlyStronghands()
public
{
// setup data
address _customerAddress = msg.sender;
uint256 _dividends = myDividends(false); // get ref. bonus later in the code
// update dividend tracker
payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude);
// add ref. bonus
_dividends += referralBalance_[_customerAddress];
referralBalance_[_customerAddress] = 0;
// lambo delivery service
_customerAddress.transfer(_dividends);
// fire event
onWithdraw(_customerAddress, _dividends);
}
/**
* Liquifies tokens to ethereum.
*/
function sell(uint256 _amountOfTokens)
onlyBagholders()
public
{
// setup data
address _customerAddress = msg.sender;
// russian hackers BTFO
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
uint256 _tokens = _amountOfTokens;
uint256 _ethereum = tokensToEthereum_(_tokens);
uint256 _dividends = SafeMath.div(_ethereum, dividendFee_);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
// burn the sold tokens
tokenSupply_ = SafeMath.sub(tokenSupply_, _tokens);
tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _tokens);
// update dividends tracker
int256 _updatedPayouts = (int256) (profitPerShare_ * _tokens + (_taxedEthereum * magnitude));
payoutsTo_[_customerAddress] -= _updatedPayouts;
// dividing by zero is a bad idea
if (tokenSupply_ > 0) {
// update the amount of dividends per token
profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_);
}
// fire event
onTokenSell(_customerAddress, _tokens, _taxedEthereum);
}
/**
* Transfer tokens from the caller to a new holder.
* Remember, there's a 10% fee here as well.
*/
function transfer(address _toAddress, uint256 _amountOfTokens)
onlyBagholders()
public
returns(bool)
{
// setup
address _customerAddress = msg.sender;
// make sure we have the requested tokens
// also disables transfers until ambassador phase is over
// ( we dont want whale premines )
require(!onlyAmbassadors && _amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
// withdraw all outstanding dividends first
if(myDividends(true) > 0) withdraw();
// liquify 10% of the tokens that are transfered
// these are dispersed to shareholders
uint256 _tokenFee = SafeMath.div(_amountOfTokens, dividendFee_);
uint256 _taxedTokens = SafeMath.sub(_amountOfTokens, _tokenFee);
uint256 _dividends = tokensToEthereum_(_tokenFee);
// burn the fee tokens
tokenSupply_ = SafeMath.sub(tokenSupply_, _tokenFee);
// exchange tokens
tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _amountOfTokens);
tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], _taxedTokens);
// update dividend trackers
payoutsTo_[_customerAddress] -= (int256) (profitPerShare_ * _amountOfTokens);
payoutsTo_[_toAddress] += (int256) (profitPerShare_ * _taxedTokens);
// disperse dividends among holders
profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_);
// fire event
Transfer(_customerAddress, _toAddress, _taxedTokens);
// ERC20
return true;
}
/*---------- ADMINISTRATOR ONLY FUNCTIONS ----------*/
/**
* In case the amassador quota is not met, the administrator can manually disable the ambassador phase.
*/
function disableInitialStage()
onlyAdministrator()
public
{
onlyAmbassadors = false;
}
/**
* In case one of us dies, we need to replace ourselves.
*/
function setAdministrator(bytes32 _identifier, bool _status)
onlyAdministrator()
public
{
administrators[_identifier] = _status;
}
/**
* Precautionary measures in case we need to adjust the masternode rate.
*/
function setStakingRequirement(uint256 _amountOfTokens)
onlyAdministrator()
public
{
stakingRequirement = _amountOfTokens;
}
/**
* If we want to rebrand, we can.
*/
function setName(string _name)
onlyAdministrator()
public
{
name = _name;
}
/**
* If we want to rebrand, we can.
*/
function setSymbol(string _symbol)
onlyAdministrator()
public
{
symbol = _symbol;
}
/*---------- HELPERS AND CALCULATORS ----------*/
/**
* Method to view the current Ethereum stored in the contract
* Example: totalEthereumBalance()
*/
function totalEthereumBalance()
public
view
returns(uint)
{
return this.balance;
}
/**
* Retrieve the total token supply.
*/
function totalSupply()
public
view
returns(uint256)
{
return tokenSupply_;
}
/**
* Retrieve the tokens owned by the caller.
*/
function myTokens()
public
view
returns(uint256)
{
address _customerAddress = msg.sender;
return balanceOf(_customerAddress);
}
/**
* Retrieve the dividends owned by the caller.
* If `_includeReferralBonus` is to to 1/true, the referral bonus will be included in the calculations.
* The reason for this, is that in the frontend, we will want to get the total divs (global + ref)
* But in the internal calculations, we want them separate.
*/
function myDividends(bool _includeReferralBonus)
public
view
returns(uint256)
{
address _customerAddress = msg.sender;
return _includeReferralBonus ? dividendsOf(_customerAddress) + referralBalance_[_customerAddress] : dividendsOf(_customerAddress) ;
}
/**
* Retrieve the token balance of any single address.
*/
function balanceOf(address _customerAddress)
view
public
returns(uint256)
{
return tokenBalanceLedger_[_customerAddress];
}
/**
* Retrieve the dividend balance of any single address.
*/
function dividendsOf(address _customerAddress)
view
public
returns(uint256)
{
return (uint256) ((int256)(profitPerShare_ * tokenBalanceLedger_[_customerAddress]) - payoutsTo_[_customerAddress]) / magnitude;
}
/**
* Return the buy price of 1 individual token.
*/
function sellPrice()
public
view
returns(uint256)
{
// our calculation relies on the token supply, so we need supply. Doh.
if(tokenSupply_ == 0){
return tokenPriceInitial_ - tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(_ethereum, dividendFee_ );
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
}
/**
* Return the sell price of 1 individual token.
*/
function buyPrice()
public
view
returns(uint256)
{
// our calculation relies on the token supply, so we need supply. Doh.
if(tokenSupply_ == 0){
return tokenPriceInitial_ + tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(_ethereum, dividendFee_ );
uint256 _taxedEthereum = SafeMath.add(_ethereum, _dividends);
return _taxedEthereum;
}
}
/**
* Function for the frontend to dynamically retrieve the price scaling of buy orders.
*/
function calculateTokensReceived(uint256 _ethereumToSpend)
public
view
returns(uint256)
{
uint256 _dividends = SafeMath.div(_ethereumToSpend, dividendFee_);
uint256 _taxedEthereum = SafeMath.sub(_ethereumToSpend, _dividends);
uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum);
return _amountOfTokens;
}
/**
* Function for the frontend to dynamically retrieve the price scaling of sell orders.
*/
function calculateEthereumReceived(uint256 _tokensToSell)
public
view
returns(uint256)
{
require(_tokensToSell <= tokenSupply_);
uint256 _ethereum = tokensToEthereum_(_tokensToSell);
uint256 _dividends = SafeMath.div(_ethereum, dividendFee_);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
/*==========================================
= INTERNAL FUNCTIONS =
==========================================*/
function purchaseTokens(uint256 _incomingEthereum, address _referredBy)
antiEarlyWhale(_incomingEthereum)
internal
returns(uint256)
{
// data setup
address _customerAddress = msg.sender;
uint256 _undividedDividends = SafeMath.div(_incomingEthereum, dividendFee_);
uint256 _referralBonus = SafeMath.div(_undividedDividends, 3);
uint256 _dividends = SafeMath.sub(_undividedDividends, _referralBonus);
uint256 _taxedEthereum = SafeMath.sub(_incomingEthereum, _undividedDividends);
uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum);
uint256 _fee = _dividends * magnitude;
// no point in continuing execution if OP is a poorfag russian hacker
// prevents overflow in the case that the pyramid somehow magically starts being used by everyone in the world
// (or hackers)
// and yes we know that the safemath function automatically rules out the "greater then" equasion.
require(_amountOfTokens > 0 && (SafeMath.add(_amountOfTokens,tokenSupply_) > tokenSupply_));
// is the user referred by a masternode?
if(
// is this a referred purchase?
_referredBy != 0x0000000000000000000000000000000000000000 &&
// no cheating!
_referredBy != _customerAddress &&
// does the referrer have at least X whole tokens?
// i.e is the referrer a godly chad masternode
tokenBalanceLedger_[_referredBy] >= stakingRequirement
){
// wealth redistribution
referralBalance_[_referredBy] = SafeMath.add(referralBalance_[_referredBy], _referralBonus);
} else {
// no ref purchase
// add the referral bonus back to the global dividends cake
_dividends = SafeMath.add(_dividends, _referralBonus);
_fee = _dividends * magnitude;
}
// we can't give people infinite ethereum
if(tokenSupply_ > 0){
// add tokens to the pool
tokenSupply_ = SafeMath.add(tokenSupply_, _amountOfTokens);
// take the amount of dividends gained through this transaction, and allocates them evenly to each shareholder
profitPerShare_ += (_dividends * magnitude / (tokenSupply_));
// calculate the amount of tokens the customer receives over his purchase
_fee = _fee - (_fee-(_amountOfTokens * (_dividends * magnitude / (tokenSupply_))));
} else {
// add tokens to the pool
tokenSupply_ = _amountOfTokens;
}
// update circulating supply & the ledger address for the customer
tokenBalanceLedger_[_customerAddress] = SafeMath.add(tokenBalanceLedger_[_customerAddress], _amountOfTokens);
// Tells the contract that the buyer doesn't deserve dividends for the tokens before they owned them;
//really i know you think you do but you don't
int256 _updatedPayouts = (int256) ((profitPerShare_ * _amountOfTokens) - _fee);
payoutsTo_[_customerAddress] += _updatedPayouts;
// fire event
onTokenPurchase(_customerAddress, _incomingEthereum, _amountOfTokens, _referredBy);
return _amountOfTokens;
}
/**
* Calculate Token price based on an amount of incoming ethereum
* It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation;
* Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code.
*/
function ethereumToTokens_(uint256 _ethereum)
internal
view
returns(uint256)
{
uint256 _tokenPriceInitial = tokenPriceInitial_ * 1e18;
uint256 _tokensReceived =
(
(
// underflow attempts BTFO
SafeMath.sub(
(sqrt
(
(_tokenPriceInitial**2)
+
(2*(tokenPriceIncremental_ * 1e18)*(_ethereum * 1e18))
+
(((tokenPriceIncremental_)**2)*(tokenSupply_**2))
+
(2*(tokenPriceIncremental_)*_tokenPriceInitial*tokenSupply_)
)
), _tokenPriceInitial
)
)/(tokenPriceIncremental_)
)-(tokenSupply_)
;
return _tokensReceived;
}
/**
* Calculate token sell value.
* It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation;
* Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code.
*/
function tokensToEthereum_(uint256 _tokens)
internal
view
returns(uint256)
{
uint256 tokens_ = (_tokens + 1e18);
uint256 _tokenSupply = (tokenSupply_ + 1e18);
uint256 _etherReceived =
(
// underflow attempts BTFO
SafeMath.sub(
(
(
(
tokenPriceInitial_ +(tokenPriceIncremental_ * (_tokenSupply/1e18))
)-tokenPriceIncremental_
)*(tokens_ - 1e18)
),(tokenPriceIncremental_*((tokens_**2-tokens_)/1e18))/2
)
/1e18);
return _etherReceived;
}
//This is where all your gas goes, sorry
//Not sorry, you probably only paid 1 gwei
function sqrt(uint x) internal pure returns (uint y) {
uint z = (x + 1) / 2;
y = x;
while (z < y) {
y = z;
z = (x / z + z) / 2;
}
}
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
} | ensures that the first tokens in the contract will be equally distributed meaning, no divine dump will be ever possible result: healthy longevity. are we still in the vulnerable phase? if so, enact anti early whale protocol is the customer in the ambassador list? does the customer purchase exceed the max ambassador quota? updated the accumulated quota execute in case the ether count drops low, the ambassador phase won't reinitiate | modifier antiEarlyWhale(uint256 _amountOfEthereum){
address _customerAddress = msg.sender;
if( onlyAmbassadors && ((totalEthereumBalance() - _amountOfEthereum) <= ambassadorQuota_ )){
require(
ambassadors_[_customerAddress] == true &&
(ambassadorAccumulatedQuota_[_customerAddress] + _amountOfEthereum) <= ambassadorMaxPurchase_
);
ambassadorAccumulatedQuota_[_customerAddress] = SafeMath.add(ambassadorAccumulatedQuota_[_customerAddress], _amountOfEthereum);
_;
onlyAmbassadors = false;
_;
}
}
==============================*/
event onTokenPurchase(
address indexed customerAddress,
uint256 incomingEthereum,
uint256 tokensMinted,
address indexed referredBy
);
event onTokenSell(
address indexed customerAddress,
uint256 tokensBurned,
uint256 ethereumEarned
);
event onReinvestment(
address indexed customerAddress,
uint256 ethereumReinvested,
uint256 tokensMinted
);
event onWithdraw(
address indexed customerAddress,
uint256 ethereumWithdrawn
);
address indexed from,
address indexed to,
uint256 tokens
);
=====================================*/
string public name = "DEVIDHARJ";
string public symbol = "DEVIDHARJ";
uint8 constant public decimals = 18;
uint8 constant internal dividendFee_ = 100;
uint256 constant internal tokenPriceInitial_ = 0.0000001 ether;
uint256 constant internal tokenPriceIncremental_ = 0.00000001 ether;
uint256 constant internal magnitude = 2**64;
uint256 constant internal ambassadorMaxPurchase_ = 10 ether;
uint256 constant internal ambassadorQuota_ = 10 ether;
================================*/
mapping(address => uint256) internal referralBalance_;
mapping(address => int256) internal payoutsTo_;
mapping(address => uint256) internal ambassadorAccumulatedQuota_;
uint256 internal tokenSupply_ = 0;
uint256 internal profitPerShare_;
=======================================*/
| 11,670,691 | [
1,
773,
1823,
716,
326,
1122,
2430,
316,
326,
6835,
903,
506,
1298,
1230,
16859,
12256,
16,
1158,
3739,
558,
4657,
903,
506,
14103,
3323,
563,
30,
28819,
4281,
908,
16438,
18,
854,
732,
4859,
316,
326,
331,
19063,
429,
6855,
35,
309,
1427,
16,
570,
621,
30959,
11646,
600,
5349,
1771,
353,
326,
6666,
316,
326,
13232,
428,
23671,
666,
35,
1552,
326,
6666,
23701,
9943,
326,
943,
13232,
428,
23671,
13257,
35,
3526,
326,
24893,
13257,
1836,
316,
648,
326,
225,
2437,
1056,
29535,
4587,
16,
326,
13232,
428,
23671,
6855,
8462,
1404,
283,
2738,
3840,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
30959,
41,
20279,
2888,
5349,
12,
11890,
5034,
389,
8949,
951,
41,
18664,
379,
15329,
203,
3639,
1758,
389,
10061,
1887,
273,
1234,
18,
15330,
31,
203,
540,
203,
3639,
309,
12,
1338,
30706,
428,
361,
1383,
597,
14015,
4963,
41,
18664,
379,
13937,
1435,
300,
389,
8949,
951,
41,
18664,
379,
13,
1648,
13232,
428,
23671,
10334,
67,
8623,
95,
203,
5411,
2583,
12,
203,
7734,
13232,
428,
361,
1383,
67,
63,
67,
10061,
1887,
65,
422,
638,
597,
203,
1171,
203,
7734,
261,
2536,
428,
23671,
8973,
5283,
690,
10334,
67,
63,
67,
10061,
1887,
65,
397,
389,
8949,
951,
41,
18664,
379,
13,
1648,
13232,
428,
23671,
2747,
23164,
67,
203,
1171,
203,
5411,
11272,
203,
2398,
203,
5411,
13232,
428,
23671,
8973,
5283,
690,
10334,
67,
63,
67,
10061,
1887,
65,
273,
14060,
10477,
18,
1289,
12,
2536,
428,
23671,
8973,
5283,
690,
10334,
67,
63,
67,
10061,
1887,
6487,
389,
8949,
951,
41,
18664,
379,
1769,
203,
540,
203,
5411,
389,
31,
203,
5411,
1338,
30706,
428,
361,
1383,
273,
629,
31,
203,
5411,
389,
31,
377,
203,
3639,
289,
203,
540,
203,
565,
289,
203,
377,
203,
377,
203,
565,
28562,
14468,
5549,
203,
565,
871,
603,
1345,
23164,
12,
203,
3639,
1758,
8808,
6666,
1887,
16,
203,
3639,
2254,
5034,
6935,
41,
18664,
379,
16,
203,
3639,
2254,
5034,
2430,
49,
474,
329,
16,
203,
3639,
1758,
8808,
29230,
858,
203,
565,
11272,
203,
377,
203,
565,
871,
603,
1345,
55,
1165,
12,
203,
3639,
2
] |
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.7.4;
import "../../openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol";
import "../../openzeppelin/contracts-upgradeable/utils/EnumerableSetUpgradeable.sol";
import "../../openzeppelin/contracts-upgradeable/utils/SafeCastUpgradeable.sol";
import "./libraries/SafeMathExt.sol";
import "./libraries/Utils.sol";
import "./module/MarginAccountModule.sol";
import "./module/PerpetualModule.sol";
import "./module/LiquidityPoolModule.sol";
import "./module/AMMModule.sol";
import "./Type.sol";
import "./Storage.sol";
/**
* @notice Getter is a helper to help getting status of liquidity from external.
*/
contract Getter is Storage {
using SafeMathUpgradeable for uint256;
using SafeCastUpgradeable for uint256;
using SafeMathExt for int256;
using SafeMathExt for uint256;
using Utils for EnumerableSetUpgradeable.AddressSet;
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;
using MarginAccountModule for PerpetualStorage;
using PerpetualModule for PerpetualStorage;
using LiquidityPoolModule for LiquidityPoolStorage;
using AMMModule for LiquidityPoolStorage;
/**
* @notice Get the info of the liquidity pool.
* WARN: the result of this function is base on current storage of liquidityPool, not the latest.
* To get the latest status, call `syncState` first.
*
* @return isRunning True if the liquidity pool is running.
* @return isFastCreationEnabled True if the operator of the liquidity pool is allowed to create new perpetual
* when the liquidity pool is running.
* @return addresses The related addresses of the liquidity pool.
* @return intNums An fixed length array of int type properties, see comments for details.
* @return uintNums An fixed length array of uint type properties, see comments for details.
*/
function getLiquidityPoolInfo()
public
view
returns (
bool isRunning,
bool isFastCreationEnabled,
// [0] creator,
// [1] operator,
// [2] transferringOperator,
// [3] governor,
// [4] shareToken,
// [5] collateralToken,
// [6] vault,
address[7] memory addresses,
// [0] vaultFeeRate,
// [1] poolCash,
// [2] insuranceFundCap,
// [3] insuranceFund,
// [4] donatedInsuranceFund,
int256[5] memory intNums,
// [0] collateralDecimals,
// [1] perpetualCount,
// [2] fundingTime,
// [3] operatorExpiration,
uint256[4] memory uintNums
)
{
isRunning = _liquidityPool.isRunning;
isFastCreationEnabled = _liquidityPool.isFastCreationEnabled;
addresses = [
_liquidityPool.creator,
_liquidityPool.getOperator(),
_liquidityPool.transferringOperator,
_liquidityPool.governor,
_liquidityPool.shareToken,
_liquidityPool.collateralToken,
_liquidityPool.getVault()
];
intNums[0] = _liquidityPool.getVaultFeeRate();
intNums[1] = _liquidityPool.poolCash;
intNums[2] = _liquidityPool.insuranceFundCap;
intNums[3] = _liquidityPool.insuranceFund;
intNums[4] = _liquidityPool.donatedInsuranceFund;
uintNums[0] = _liquidityPool.collateralDecimals;
uintNums[1] = _liquidityPool.perpetualCount;
uintNums[2] = _liquidityPool.fundingTime;
uintNums[3] = _liquidityPool.operatorExpiration;
}
/**
* @notice Get the info of the perpetual. Need to update the funding state and the oracle price
* of each perpetual before and update the funding rate of each perpetual after.
* WARN: the result of this function is base on current storage of liquidityPool, not the latest.
* To get the latest status, call `syncState` first.
*
* @param perpetualIndex The index of the perpetual in the liquidity pool.
* @return state The state of the perpetual.
* @return oracle The address of the current oracle in perpetual.
* @return nums An fixed length array of uint type properties, see comments for details.
*/
function getPerpetualInfo(uint256 perpetualIndex)
public
view
onlyExistedPerpetual(perpetualIndex)
returns (
PerpetualState state,
address oracle,
// [0] totalCollateral
// [1] markPrice, (return settlementPrice if it is in EMERGENCY state)
// [2] indexPrice,
// [3] fundingRate,
// [4] unitAccumulativeFunding,
// [5] initialMarginRate,
// [6] maintenanceMarginRate,
// [7] operatorFeeRate,
// [8] lpFeeRate,
// [9] referralRebateRate,
// [10] liquidationPenaltyRate,
// [11] keeperGasReward,
// [12] insuranceFundRate,
// [13-15] halfSpread value, min, max,
// [16-18] openSlippageFactor value, min, max,
// [19-21] closeSlippageFactor value, min, max,
// [22-24] fundingRateLimit value, min, max,
// [25-27] ammMaxLeverage value, min, max,
// [28-30] maxClosePriceDiscount value, min, max,
// [31] openInterest,
// [32] maxOpenInterestRate,
// [33-35] fundingRateFactor value, min, max,
// [36-38] defaultTargetLeverage value, min, max,
int256[39] memory nums
)
{
PerpetualStorage storage perpetual = _liquidityPool.perpetuals[perpetualIndex];
state = perpetual.state;
oracle = perpetual.oracle;
nums = [
// [0]
perpetual.totalCollateral,
perpetual.getMarkPrice(),
perpetual.getIndexPrice(),
perpetual.fundingRate,
perpetual.unitAccumulativeFunding,
perpetual.initialMarginRate,
perpetual.maintenanceMarginRate,
perpetual.operatorFeeRate,
perpetual.lpFeeRate,
perpetual.referralRebateRate,
// [10]
perpetual.liquidationPenaltyRate,
perpetual.keeperGasReward,
perpetual.insuranceFundRate,
perpetual.halfSpread.value,
perpetual.halfSpread.minValue,
perpetual.halfSpread.maxValue,
perpetual.openSlippageFactor.value,
perpetual.openSlippageFactor.minValue,
perpetual.openSlippageFactor.maxValue,
perpetual.closeSlippageFactor.value,
// [20]
perpetual.closeSlippageFactor.minValue,
perpetual.closeSlippageFactor.maxValue,
perpetual.fundingRateLimit.value,
perpetual.fundingRateLimit.minValue,
perpetual.fundingRateLimit.maxValue,
perpetual.ammMaxLeverage.value,
perpetual.ammMaxLeverage.minValue,
perpetual.ammMaxLeverage.maxValue,
perpetual.maxClosePriceDiscount.value,
perpetual.maxClosePriceDiscount.minValue,
// [30]
perpetual.maxClosePriceDiscount.maxValue,
perpetual.openInterest,
perpetual.maxOpenInterestRate,
perpetual.fundingRateFactor.value,
perpetual.fundingRateFactor.minValue,
perpetual.fundingRateFactor.maxValue,
perpetual.defaultTargetLeverage.value,
perpetual.defaultTargetLeverage.minValue,
perpetual.defaultTargetLeverage.maxValue
];
}
/**
* @notice Get the account info of the trader. Need to update the funding state and the oracle price
* of each perpetual before and update the funding rate of each perpetual after
* WARN: the result of this function is base on current storage of liquidityPool, not the latest.
* To get the latest status, call `syncState` first.
*
* @param perpetualIndex The index of the perpetual in the liquidity pool.
* @param trader The address of the trader.
* When trader == liquidityPool, isSafe are meanless. Do not forget to sum
* poolCash and availableCash of all perpetuals in a liquidityPool when
* calculating AMM margin
* @return cash The cash of the account.
* @return position The position of the account.
* @return availableMargin The available margin of the account.
* @return margin The margin of the account.
* @return settleableMargin The settleable margin of the account.
* @return isInitialMarginSafe True if the account is initial margin safe.
* @return isMaintenanceMarginSafe True if the account is maintenance margin safe.
* @return isMarginSafe True if the total value of margin account is beyond 0.
* @return targetLeverage The target leverage for openning position.
*/
function getMarginAccount(uint256 perpetualIndex, address trader)
public
view
onlyExistedPerpetual(perpetualIndex)
returns (
int256 cash,
int256 position,
int256 availableMargin,
int256 margin,
int256 settleableMargin,
bool isInitialMarginSafe,
bool isMaintenanceMarginSafe,
bool isMarginSafe,
int256 targetLeverage
)
{
PerpetualStorage storage perpetual = _liquidityPool.perpetuals[perpetualIndex];
MarginAccount storage account = perpetual.marginAccounts[trader];
int256 markPrice = perpetual.getMarkPrice();
cash = account.cash;
position = account.position;
availableMargin = perpetual.getAvailableMargin(trader, markPrice);
margin = perpetual.getMargin(trader, markPrice);
settleableMargin = perpetual.getSettleableMargin(trader, markPrice);
isInitialMarginSafe = perpetual.isInitialMarginSafe(trader, markPrice);
isMaintenanceMarginSafe = perpetual.isMaintenanceMarginSafe(trader, markPrice);
isMarginSafe = perpetual.isMarginSafe(trader, markPrice);
targetLeverage = perpetual.getTargetLeverage(trader);
}
/**
* @notice Get the number of active accounts in the given perpetual.
* Active means the trader has margin (margin != 0) in the margin account.
* @param perpetualIndex The index of the perpetual in liquidity pool.
* @return activeAccountCount The number of active accounts in the perpetual.
*/
function getActiveAccountCount(uint256 perpetualIndex)
public
view
onlyExistedPerpetual(perpetualIndex)
returns (uint256 activeAccountCount)
{
activeAccountCount = _liquidityPool.perpetuals[perpetualIndex].activeAccounts.length();
}
/**
* @notice Get the active accounts in the perpetual whose index with range [begin, end).
* @param perpetualIndex The index of the perpetual in the liquidity pool.
* @param begin The begin index of account to retrieve.
* @param end The end index of account, exclusive.
* @return result An array of active addresses.
*/
function listActiveAccounts(
uint256 perpetualIndex,
uint256 begin,
uint256 end
) public view onlyExistedPerpetual(perpetualIndex) returns (address[] memory result) {
PerpetualStorage storage perpetual = _liquidityPool.perpetuals[perpetualIndex];
result = perpetual.activeAccounts.toArray(begin, end);
}
/**
* @notice Get the progress of clearing active accounts.
* @param perpetualIndex The index of the perpetual in the liquidity pool
* @return left Number of left active accounts.
* @return total Number of total active accounts.
*/
function getClearProgress(uint256 perpetualIndex)
public
view
onlyExistedPerpetual(perpetualIndex)
returns (uint256 left, uint256 total)
{
PerpetualStorage storage perpetual = _liquidityPool.perpetuals[perpetualIndex];
left = perpetual.activeAccounts.length();
total = perpetual.state == PerpetualState.NORMAL
? perpetual.activeAccounts.length()
: perpetual.totalAccount;
}
/**
* @notice Get the pool margin of the liquidity pool.
* Pool margin is how much collateral of the pool considering the AMM's positions of perpetuals
* WARN: the result of this function is base on current storage of liquidityPool, not the latest.
* To get the latest status, call `syncState` first.
* @return poolMargin The pool margin of the liquidity pool
* @return isAMMSafe True if AMM is safe
*/
function getPoolMargin() public view returns (int256 poolMargin, bool isAMMSafe) {
(poolMargin, isAMMSafe) = _liquidityPool.getPoolMargin();
}
/**
* @notice Query the cost and position amount that amm could afford based on current liquidity.
* This method should returns the same result as a 'read-only' trade, and trading fee is not included.
* WARN: the result of this function is base on current storage of liquidityPool, not the latest.
* To get the latest status, call `syncState` first.
*
* @param perpetualIndex The index of the perpetual in liquidity pool.
* @param amount The expected(max) amount of position to trade.
* @return deltaCash The cost of cash of trade.
* @return deltaPosition The update position of the trader after the trade
*/
function queryTradeWithAMM(uint256 perpetualIndex, int256 amount)
public
view
returns (int256 deltaCash, int256 deltaPosition)
{
(deltaCash, deltaPosition) = _liquidityPool.queryTradeWithAMM(
perpetualIndex,
amount.neg(),
false
);
deltaCash = deltaCash.neg();
deltaPosition = deltaPosition.neg();
}
bytes32[50] private __gap;
}
| * @notice Get the account info of the trader. Need to update the funding state and the oracle price of each perpetual before and update the funding rate of each perpetual after WARN: the result of this function is base on current storage of liquidityPool, not the latest. To get the latest status, call `syncState` first. @param perpetualIndex The index of the perpetual in the liquidity pool. @param trader The address of the trader. When trader == liquidityPool, isSafe are meanless. Do not forget to sum poolCash and availableCash of all perpetuals in a liquidityPool when calculating AMM margin @return cash The cash of the account. @return position The position of the account. @return availableMargin The available margin of the account. @return margin The margin of the account. @return settleableMargin The settleable margin of the account. @return isInitialMarginSafe True if the account is initial margin safe. @return isMaintenanceMarginSafe True if the account is maintenance margin safe. @return isMarginSafe True if the total value of margin account is beyond 0. @return targetLeverage The target leverage for openning position./ | function getMarginAccount(uint256 perpetualIndex, address trader)
public
view
onlyExistedPerpetual(perpetualIndex)
returns (
int256 cash,
int256 position,
int256 availableMargin,
int256 margin,
int256 settleableMargin,
bool isInitialMarginSafe,
bool isMaintenanceMarginSafe,
bool isMarginSafe,
int256 targetLeverage
)
{
PerpetualStorage storage perpetual = _liquidityPool.perpetuals[perpetualIndex];
MarginAccount storage account = perpetual.marginAccounts[trader];
int256 markPrice = perpetual.getMarkPrice();
cash = account.cash;
position = account.position;
availableMargin = perpetual.getAvailableMargin(trader, markPrice);
margin = perpetual.getMargin(trader, markPrice);
settleableMargin = perpetual.getSettleableMargin(trader, markPrice);
isInitialMarginSafe = perpetual.isInitialMarginSafe(trader, markPrice);
isMaintenanceMarginSafe = perpetual.isMaintenanceMarginSafe(trader, markPrice);
isMarginSafe = perpetual.isMarginSafe(trader, markPrice);
targetLeverage = perpetual.getTargetLeverage(trader);
}
| 12,856,656 | [
1,
967,
326,
2236,
1123,
434,
326,
1284,
765,
18,
12324,
358,
1089,
326,
22058,
919,
471,
326,
20865,
6205,
1850,
434,
1517,
1534,
6951,
1462,
1865,
471,
1089,
326,
22058,
4993,
434,
1517,
1534,
6951,
1462,
1839,
1850,
20440,
30,
326,
563,
434,
333,
445,
353,
1026,
603,
783,
2502,
434,
4501,
372,
24237,
2864,
16,
486,
326,
4891,
18,
1850,
2974,
336,
326,
4891,
1267,
16,
745,
1375,
8389,
1119,
68,
1122,
18,
225,
1534,
6951,
1462,
1016,
565,
1021,
770,
434,
326,
1534,
6951,
1462,
316,
326,
4501,
372,
24237,
2845,
18,
225,
1284,
765,
5411,
1021,
1758,
434,
326,
1284,
765,
18,
12900,
5203,
1284,
765,
422,
4501,
372,
24237,
2864,
16,
353,
9890,
854,
3722,
2656,
18,
2256,
486,
13776,
358,
2142,
12900,
2845,
39,
961,
471,
2319,
39,
961,
434,
777,
1534,
6951,
12588,
316,
279,
4501,
372,
24237,
2864,
1347,
12900,
21046,
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,
2108,
5243,
3032,
12,
11890,
5034,
1534,
6951,
1462,
1016,
16,
1758,
1284,
765,
13,
203,
3639,
1071,
203,
3639,
1476,
203,
3639,
1338,
4786,
329,
2173,
6951,
1462,
12,
457,
6951,
1462,
1016,
13,
203,
3639,
1135,
261,
203,
5411,
509,
5034,
276,
961,
16,
203,
5411,
509,
5034,
1754,
16,
203,
5411,
509,
5034,
2319,
9524,
16,
203,
5411,
509,
5034,
7333,
16,
203,
5411,
509,
5034,
444,
5929,
429,
9524,
16,
203,
5411,
1426,
353,
4435,
9524,
9890,
16,
203,
5411,
1426,
353,
11045,
9524,
9890,
16,
203,
5411,
1426,
353,
9524,
9890,
16,
203,
5411,
509,
5034,
1018,
1682,
5682,
203,
3639,
262,
203,
565,
288,
203,
3639,
5722,
6951,
1462,
3245,
2502,
1534,
6951,
1462,
273,
389,
549,
372,
24237,
2864,
18,
457,
6951,
12588,
63,
457,
6951,
1462,
1016,
15533,
203,
3639,
490,
5243,
3032,
2502,
2236,
273,
1534,
6951,
1462,
18,
10107,
13971,
63,
313,
1143,
15533,
203,
3639,
509,
5034,
2267,
5147,
273,
1534,
6951,
1462,
18,
588,
3882,
5147,
5621,
203,
3639,
276,
961,
273,
2236,
18,
71,
961,
31,
203,
3639,
1754,
273,
2236,
18,
3276,
31,
203,
3639,
2319,
9524,
273,
1534,
6951,
1462,
18,
588,
5268,
9524,
12,
313,
1143,
16,
2267,
5147,
1769,
203,
3639,
7333,
273,
1534,
6951,
1462,
18,
588,
9524,
12,
313,
1143,
16,
2267,
5147,
1769,
203,
3639,
444,
5929,
429,
9524,
273,
1534,
6951,
1462,
18,
588,
694,
5929,
429,
9524,
12,
313,
1143,
16,
2267,
5147,
1769,
203,
3639,
353,
4435,
9524,
9890,
2
] |
./full_match/1/0x87ee9BdB7241EBD95B22c0237e7bBc5D6BE658Eb/sources/browser/YAX-MAIN/Timelock.flat.main.sol | XXX: change to 1 day from 2 days to allow more flexibility during the early phase of the project | contract Timelock {
using SafeMath for uint;
event NewAdmin(address indexed newAdmin);
event NewPendingAdmin(address indexed newPendingAdmin);
event NewDelay(uint indexed newDelay);
event CancelTransaction(bytes32 indexed txHash, address indexed target, uint value, string signature, bytes data, uint eta);
event ExecuteTransaction(bytes32 indexed txHash, address indexed target, uint value, string signature, bytes data, uint eta);
event QueueTransaction(bytes32 indexed txHash, address indexed target, uint value, string signature, bytes data, uint eta);
uint public constant GRACE_PERIOD = 14 days;
uint public constant MINIMUM_DELAY = 1 days;
uint public constant MAXIMUM_DELAY = 30 days;
address public admin;
address public pendingAdmin;
uint public delay;
bool public admin_initialized;
mapping (bytes32 => bool) public queuedTransactions;
constructor(address admin_, uint delay_) public {
require(delay_ >= MINIMUM_DELAY, "Timelock::constructor: Delay must exceed minimum delay.");
require(delay_ <= MAXIMUM_DELAY, "Timelock::constructor: Delay must not exceed maximum delay.");
admin = admin_;
delay = delay_;
admin_initialized = false;
}
receive() external payable { }
function setDelay(uint delay_) public {
require(msg.sender == address(this), "Timelock::setDelay: Call must come from Timelock.");
require(delay_ >= MINIMUM_DELAY, "Timelock::setDelay: Delay must exceed minimum delay.");
require(delay_ <= MAXIMUM_DELAY, "Timelock::setDelay: Delay must not exceed maximum delay.");
delay = delay_;
emit NewDelay(delay);
}
function acceptAdmin() public {
require(msg.sender == pendingAdmin, "Timelock::acceptAdmin: Call must come from pendingAdmin.");
admin = msg.sender;
pendingAdmin = address(0);
emit NewAdmin(admin);
}
function setPendingAdmin(address pendingAdmin_) public {
if (admin_initialized) {
require(msg.sender == address(this), "Timelock::setPendingAdmin: Call must come from Timelock.");
require(msg.sender == admin, "Timelock::setPendingAdmin: First call must come from admin.");
admin_initialized = true;
}
pendingAdmin = pendingAdmin_;
emit NewPendingAdmin(pendingAdmin);
}
function setPendingAdmin(address pendingAdmin_) public {
if (admin_initialized) {
require(msg.sender == address(this), "Timelock::setPendingAdmin: Call must come from Timelock.");
require(msg.sender == admin, "Timelock::setPendingAdmin: First call must come from admin.");
admin_initialized = true;
}
pendingAdmin = pendingAdmin_;
emit NewPendingAdmin(pendingAdmin);
}
} else {
function queueTransaction(address target, uint value, string memory signature, bytes memory data, uint eta) public returns (bytes32) {
require(msg.sender == admin, "Timelock::queueTransaction: Call must come from admin.");
require(eta >= getBlockTimestamp().add(delay), "Timelock::queueTransaction: Estimated execution block must satisfy delay.");
bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta));
queuedTransactions[txHash] = true;
emit QueueTransaction(txHash, target, value, signature, data, eta);
return txHash;
}
function cancelTransaction(address target, uint value, string memory signature, bytes memory data, uint eta) public {
require(msg.sender == admin, "Timelock::cancelTransaction: Call must come from admin.");
bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta));
queuedTransactions[txHash] = false;
emit CancelTransaction(txHash, target, value, signature, data, eta);
}
function executeTransaction(address target, uint value, string memory signature, bytes memory data, uint eta) public payable returns (bytes memory) {
require(msg.sender == admin, "Timelock::executeTransaction: Call must come from admin.");
bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta));
require(queuedTransactions[txHash], "Timelock::executeTransaction: Transaction hasn't been queued.");
require(getBlockTimestamp() >= eta, "Timelock::executeTransaction: Transaction hasn't surpassed time lock.");
require(getBlockTimestamp() <= eta.add(GRACE_PERIOD), "Timelock::executeTransaction: Transaction is stale.");
queuedTransactions[txHash] = false;
bytes memory callData;
if (bytes(signature).length == 0) {
callData = data;
callData = abi.encodePacked(bytes4(keccak256(bytes(signature))), data);
}
require(success, "Timelock::executeTransaction: Transaction execution reverted.");
emit ExecuteTransaction(txHash, target, value, signature, data, eta);
return returnData;
}
function executeTransaction(address target, uint value, string memory signature, bytes memory data, uint eta) public payable returns (bytes memory) {
require(msg.sender == admin, "Timelock::executeTransaction: Call must come from admin.");
bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta));
require(queuedTransactions[txHash], "Timelock::executeTransaction: Transaction hasn't been queued.");
require(getBlockTimestamp() >= eta, "Timelock::executeTransaction: Transaction hasn't surpassed time lock.");
require(getBlockTimestamp() <= eta.add(GRACE_PERIOD), "Timelock::executeTransaction: Transaction is stale.");
queuedTransactions[txHash] = false;
bytes memory callData;
if (bytes(signature).length == 0) {
callData = data;
callData = abi.encodePacked(bytes4(keccak256(bytes(signature))), data);
}
require(success, "Timelock::executeTransaction: Transaction execution reverted.");
emit ExecuteTransaction(txHash, target, value, signature, data, eta);
return returnData;
}
} else {
(bool success, bytes memory returnData) = target.call{value: value}(callData);
function getBlockTimestamp() internal view returns (uint) {
return block.timestamp;
}
}
| 16,576,085 | [
1,
15639,
30,
2549,
358,
404,
2548,
628,
576,
4681,
358,
1699,
1898,
16600,
3628,
4982,
326,
11646,
6855,
434,
326,
1984,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
12652,
292,
975,
288,
203,
565,
1450,
14060,
10477,
364,
2254,
31,
203,
203,
565,
871,
1166,
4446,
12,
2867,
8808,
394,
4446,
1769,
203,
565,
871,
1166,
8579,
4446,
12,
2867,
8808,
394,
8579,
4446,
1769,
203,
565,
871,
1166,
6763,
12,
11890,
8808,
394,
6763,
1769,
203,
565,
871,
10347,
3342,
12,
3890,
1578,
8808,
2229,
2310,
16,
1758,
8808,
1018,
16,
2254,
460,
16,
533,
3372,
16,
225,
1731,
501,
16,
2254,
14251,
1769,
203,
565,
871,
7903,
3342,
12,
3890,
1578,
8808,
2229,
2310,
16,
1758,
8808,
1018,
16,
2254,
460,
16,
533,
3372,
16,
225,
1731,
501,
16,
2254,
14251,
1769,
203,
565,
871,
7530,
3342,
12,
3890,
1578,
8808,
2229,
2310,
16,
1758,
8808,
1018,
16,
2254,
460,
16,
533,
3372,
16,
1731,
501,
16,
2254,
14251,
1769,
203,
203,
565,
2254,
1071,
5381,
611,
9254,
67,
28437,
273,
5045,
4681,
31,
203,
565,
2254,
1071,
5381,
6989,
18605,
67,
26101,
273,
404,
4681,
31,
203,
565,
2254,
1071,
5381,
4552,
18605,
67,
26101,
273,
5196,
4681,
31,
203,
203,
565,
1758,
1071,
3981,
31,
203,
565,
1758,
1071,
4634,
4446,
31,
203,
565,
2254,
1071,
4624,
31,
203,
565,
1426,
1071,
3981,
67,
13227,
31,
203,
203,
565,
2874,
261,
3890,
1578,
516,
1426,
13,
1071,
12234,
14186,
31,
203,
203,
203,
203,
203,
203,
565,
3885,
12,
2867,
3981,
67,
16,
2254,
4624,
67,
13,
1071,
288,
203,
3639,
2583,
12,
10790,
67,
1545,
6989,
18605,
67,
26101,
16,
315,
10178,
292,
975,
2866,
12316,
2
] |
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.7.6;
pragma experimental ABIEncoderV2;
import "./Types.sol";
import "./Adminable.sol";
import "./DelegatorInterface.sol";
import "./XOLEInterface.sol";
/**
* @title OpenLevDelegator
* @author OpenLeverage
*/
contract XOLEDelegator is DelegatorInterface, Adminable {
constructor(
address _oleToken,
DexAggregatorInterface _dexAgg,
uint _devFundRatio,
address _dev,
address payable _admin,
address implementation_){
admin = msg.sender;
// Creator of the contract is admin during initialization
// First delegate gets to initialize the delegator (i.e. storage contract)
delegateTo(implementation_, abi.encodeWithSignature("initialize(address,address,uint256,address)",
_oleToken,
_dexAgg,
_devFundRatio,
_dev
));
implementation = implementation_;
// Set the proper admin now that initialization is done
admin = _admin;
}
/**
* Called by the admin to update the implementation of the delegator
* @param implementation_ The address of the new implementation for delegation
*/
function setImplementation(address implementation_) public override onlyAdmin {
address oldImplementation = implementation;
implementation = implementation_;
emit NewImplementation(oldImplementation, implementation);
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.7.6;
abstract contract LPoolStorage {
//Guard variable for re-entrancy checks
bool internal _notEntered;
/**
* EIP-20 token name for this token
*/
string public name;
/**
* EIP-20 token symbol for this token
*/
string public symbol;
/**
* EIP-20 token decimals for this token
*/
uint8 public decimals;
/**
* Total number of tokens in circulation
*/
uint public totalSupply;
//Official record of token balances for each account
mapping(address => uint) internal accountTokens;
//Approved token transfer amounts on behalf of others
mapping(address => mapping(address => uint)) internal transferAllowances;
//Maximum borrow rate that can ever be applied (.0005% / block)
uint internal constant borrowRateMaxMantissa = 0.0005e16;
/**
* Maximum fraction of borrower cap(80%)
*/
uint public borrowCapFactorMantissa;
/**
* Contract which oversees inter-lToken operations
*/
address public controller;
// Initial exchange rate used when minting the first lTokens (used when totalSupply = 0)
uint internal initialExchangeRateMantissa;
/**
* Block number that interest was last accrued at
*/
uint public accrualBlockNumber;
/**
* Accumulator of the total earned interest rate since the opening of the market
*/
uint public borrowIndex;
/**
* Total amount of outstanding borrows of the underlying in this market
*/
uint public totalBorrows;
uint internal totalCash;
/**
* @notice Fraction of interest currently set aside for reserves 20%
*/
uint public reserveFactorMantissa;
uint public totalReserves;
address public underlying;
bool public isWethPool;
/**
* Container for borrow balance information
* principal Total balance (with accrued interest), after applying the most recent balance-changing action
* interestIndex Global borrowIndex as of the most recent balance-changing action
*/
struct BorrowSnapshot {
uint principal;
uint interestIndex;
}
uint256 public baseRatePerBlock;
uint256 public multiplierPerBlock;
uint256 public jumpMultiplierPerBlock;
uint256 public kink;
// Mapping of account addresses to outstanding borrow balances
mapping(address => BorrowSnapshot) internal accountBorrows;
/*** Token Events ***/
/**
* Event emitted when tokens are minted
*/
event Mint(address minter, uint mintAmount, uint mintTokens);
/**
* EIP20 Transfer event
*/
event Transfer(address indexed from, address indexed to, uint amount);
/**
* EIP20 Approval event
*/
event Approval(address indexed owner, address indexed spender, uint amount);
/*** Market Events ***/
/**
* Event emitted when interest is accrued
*/
event AccrueInterest(uint cashPrior, uint interestAccumulated, uint borrowIndex, uint totalBorrows);
/**
* Event emitted when tokens are redeemed
*/
event Redeem(address redeemer, uint redeemAmount, uint redeemTokens);
/**
* Event emitted when underlying is borrowed
*/
event Borrow(address borrower, address payee, uint borrowAmount, uint accountBorrows, uint totalBorrows);
/**
* Event emitted when a borrow is repaid
*/
event RepayBorrow(address payer, address borrower, uint repayAmount, uint badDebtsAmount, uint accountBorrows, uint totalBorrows);
/*** Admin Events ***/
/**
* Event emitted when controller is changed
*/
event NewController(address oldController, address newController);
/**
* Event emitted when interestParam is changed
*/
event NewInterestParam(uint baseRatePerBlock, uint multiplierPerBlock, uint jumpMultiplierPerBlock, uint kink);
/**
* @notice Event emitted when the reserve factor is changed
*/
event NewReserveFactor(uint oldReserveFactorMantissa, uint newReserveFactorMantissa);
/**
* @notice Event emitted when the reserves are added
*/
event ReservesAdded(address benefactor, uint addAmount, uint newTotalReserves);
/**
* @notice Event emitted when the reserves are reduced
*/
event ReservesReduced(address to, uint reduceAmount, uint newTotalReserves);
event NewBorrowCapFactorMantissa(uint oldBorrowCapFactorMantissa, uint newBorrowCapFactorMantissa);
}
abstract contract LPoolInterface is LPoolStorage {
/*** User Interface ***/
function transfer(address dst, uint amount) external virtual returns (bool);
function transferFrom(address src, address dst, uint amount) external virtual returns (bool);
function approve(address spender, uint amount) external virtual returns (bool);
function allowance(address owner, address spender) external virtual view returns (uint);
function balanceOf(address owner) external virtual view returns (uint);
function balanceOfUnderlying(address owner) external virtual returns (uint);
/*** Lender & Borrower Functions ***/
function mint(uint mintAmount) external virtual;
function mintTo(address to) external payable virtual;
function mintEth() external payable virtual;
function redeem(uint redeemTokens) external virtual;
function redeemUnderlying(uint redeemAmount) external virtual;
function borrowBehalf(address borrower, uint borrowAmount) external virtual;
function repayBorrowBehalf(address borrower, uint repayAmount) external virtual;
function repayBorrowEndByOpenLev(address borrower, uint repayAmount) external virtual;
function availableForBorrow() external view virtual returns (uint);
function getAccountSnapshot(address account) external virtual view returns (uint, uint, uint);
function borrowRatePerBlock() external virtual view returns (uint);
function supplyRatePerBlock() external virtual view returns (uint);
function totalBorrowsCurrent() external virtual view returns (uint);
function borrowBalanceCurrent(address account) external virtual view returns (uint);
function borrowBalanceStored(address account) external virtual view returns (uint);
function exchangeRateCurrent() public virtual returns (uint);
function exchangeRateStored() public virtual view returns (uint);
function getCash() external view virtual returns (uint);
function accrueInterest() public virtual;
function sync() public virtual;
/*** Admin Functions ***/
function setController(address newController) external virtual;
function setBorrowCapFactorMantissa(uint newBorrowCapFactorMantissa) external virtual;
function setInterestParams(uint baseRatePerBlock_, uint multiplierPerBlock_, uint jumpMultiplierPerBlock_, uint kink_) external virtual;
function setReserveFactor(uint newReserveFactorMantissa) external virtual;
function addReserves(uint addAmount) external virtual;
function reduceReserves(address payable to, uint reduceAmount) external virtual;
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.7.6;
pragma experimental ABIEncoderV2;
interface DexAggregatorInterface {
function sell(address buyToken, address sellToken, uint sellAmount, uint minBuyAmount, bytes memory data) external returns (uint buyAmount);
function sellMul(uint sellAmount, uint minBuyAmount, bytes memory data) external returns (uint buyAmount);
function buy(address buyToken, address sellToken, uint buyAmount, uint maxSellAmount, bytes memory data) external returns (uint sellAmount);
function calBuyAmount(address buyToken, address sellToken, uint sellAmount, bytes memory data) external view returns (uint);
function calSellAmount(address buyToken, address sellToken, uint buyAmount, bytes memory data) external view returns (uint);
function getPrice(address desToken, address quoteToken, bytes memory data) external view returns (uint256 price, uint8 decimals);
function getAvgPrice(address desToken, address quoteToken, uint32 secondsAgo, bytes memory data) external view returns (uint256 price, uint8 decimals, uint256 timestamp);
//cal current avg price and get history avg price
function getPriceCAvgPriceHAvgPrice(address desToken, address quoteToken, uint32 secondsAgo, bytes memory dexData) external view returns (uint price, uint cAvgPrice, uint256 hAvgPrice, uint8 decimals, uint256 timestamp);
function updatePriceOracle(address desToken, address quoteToken, uint32 timeWindow, bytes memory data) external returns(bool);
function updateV3Observation(address desToken, address quoteToken, bytes memory data) external;
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.7.6;
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "./dex/DexAggregatorInterface.sol";
contract XOLEStorage {
// EIP-20 token name for this token
string public constant name = 'xOLE';
// EIP-20 token symbol for this token
string public constant symbol = 'xOLE';
// EIP-20 token decimals for this token
uint8 public constant decimals = 18;
// Total number of tokens supply
uint public totalSupply;
// Total number of tokens locked
uint public totalLocked;
// Official record of token balances for each account
mapping(address => uint) internal balances;
mapping(address => LockedBalance) public locked;
DexAggregatorInterface public dexAgg;
IERC20 public oleToken;
struct LockedBalance {
uint256 amount;
uint256 end;
}
uint constant oneWeekExtraRaise = 208;// 2.08% * 210 = 436% (4 years raise)
int128 constant DEPOSIT_FOR_TYPE = 0;
int128 constant CREATE_LOCK_TYPE = 1;
int128 constant INCREASE_LOCK_AMOUNT = 2;
int128 constant INCREASE_UNLOCK_TIME = 3;
uint256 constant WEEK = 7 * 86400; // all future times are rounded by week
uint256 constant MAXTIME = 4 * 365 * 86400; // 4 years
uint256 constant MULTIPLIER = 10 ** 18;
// dev team account
address public dev;
uint public devFund;
uint public devFundRatio; // ex. 5000 => 50%
// user => reward
mapping(address => uint256) public rewards;
// useless
uint public totalStaked;
// total to shared
uint public totalRewarded;
uint public withdrewReward;
uint public lastUpdateTime;
uint public rewardPerTokenStored;
mapping(address => uint256) public userRewardPerTokenPaid;
// A record of each accounts delegate
mapping(address => address) public delegates;
// A checkpoint for marking number of votes from a given block
struct Checkpoint {
uint32 fromBlock;
uint votes;
}
mapping(uint256 => Checkpoint) public totalSupplyCheckpoints;
uint256 public totalSupplyNumCheckpoints;
// A record of votes checkpoints for each account, by index
mapping(address => mapping(uint32 => Checkpoint)) public checkpoints;
// The number of checkpoints for each account
mapping(address => uint32) public numCheckpoints;
// 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 delegation struct used by the contract
bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
// A record of states for signing / validating signatures
mapping(address => uint) public nonces;
// An event thats emitted when an account changes its delegate
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
// An event thats emitted when a delegate account's vote balance changes
event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);
event RewardAdded(address fromToken, uint convertAmount, uint reward);
event RewardConvert(address fromToken, address toToken, uint convertAmount, uint returnAmount);
event Transfer(address indexed from, address indexed to, uint256 value);
event Deposit (
address indexed provider,
uint256 value,
uint256 indexed locktime,
int128 type_,
uint256 ts
);
event Withdraw (
address indexed provider,
uint256 value,
uint256 ts
);
event Supply (
uint256 prevSupply,
uint256 supply
);
event RewardPaid (
address paidTo,
uint256 amount
);
event FailedDelegateBySig(
address indexed delegatee,
uint indexed nonce,
uint expiry,
uint8 v,
bytes32 r,
bytes32 s
);
}
interface XOLEInterface {
function convertToSharingToken(uint amount, uint minBuyAmount, bytes memory data) external;
function withdrawDevFund() external;
function earned(address account) external view returns (uint);
function withdrawReward() external;
/*** Admin Functions ***/
function setDevFundRatio(uint newRatio) external;
function setDev(address newDev) external;
function setDexAgg(DexAggregatorInterface newDexAgg) external;
// xOLE functions
function create_lock(uint256 _value, uint256 _unlock_time) external;
function increase_amount(uint256 _value) external;
function increase_unlock_time(uint256 _unlock_time) external;
function withdraw() external;
function balanceOf(address addr) external view returns (uint256);
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.7.6;
import "./liquidity/LPoolInterface.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
library Types {
using SafeERC20 for IERC20;
struct Market {// Market info
LPoolInterface pool0; // Lending Pool 0
LPoolInterface pool1; // Lending Pool 1
address token0; // Lending Token 0
address token1; // Lending Token 1
uint16 marginLimit; // Margin ratio limit for specific trading pair. Two decimal in percentage, ex. 15.32% => 1532
uint16 feesRate; // feesRate 30=>0.3%
uint16 priceDiffientRatio;
address priceUpdater;
uint pool0Insurance; // Insurance balance for token 0
uint pool1Insurance; // Insurance balance for token 1
uint32[] dexs;
}
struct Trade {// Trade storage
uint deposited; // Balance of deposit token
uint held; // Balance of held position
bool depositToken; // Indicate if the deposit token is token 0 or token 1
uint128 lastBlockNum; // Block number when the trade was touched last time, to prevent more than one operation within same block
}
struct MarketVars {// A variables holder for market info
LPoolInterface buyPool; // Lending pool address of the token to buy. It's a calculated field on open or close trade.
LPoolInterface sellPool; // Lending pool address of the token to sell. It's a calculated field on open or close trade.
IERC20 buyToken; // Token to buy
IERC20 sellToken; // Token to sell
uint buyPoolInsurance; // Insurance balance of token to buy
uint sellPoolInsurance; // Insurance balance of token to sell
uint16 marginLimit; // Margin Ratio Limit for specific trading pair.
uint16 priceDiffientRatio;
uint32[] dexs;
}
struct TradeVars {// A variables holder for trade info
uint depositValue; // Deposit value
IERC20 depositErc20; // Deposit Token address
uint fees; // Fees value
uint depositAfterFees; // Deposit minus fees
uint tradeSize; // Trade amount to be swap on DEX
uint newHeld; // Latest held position
uint borrowValue;
uint token0Price;
uint32 dexDetail;
}
struct CloseTradeVars {// A variables holder for close trade info
uint16 marketId;
bool longToken;
bool depositToken;
uint closeRatio; // Close ratio
bool isPartialClose; // Is partial close
uint closeAmountAfterFees; // Close amount sub Fees value
uint repayAmount; // Repay to pool value
uint depositDecrease; // Deposit decrease
uint depositReturn; // Deposit actual returns
uint sellAmount;
uint receiveAmount;
uint token0Price;
uint fees; // Fees value
uint32 dexDetail;
}
struct LiquidateVars {// A variable holder for liquidation process
uint16 marketId;
bool longToken;
uint borrowed; // Total borrowed balance of trade
uint fees; // Fees for liquidation process
uint penalty; // Penalty
uint remainHeldAfterFees; // Held-fees-penalty
bool isSellAllHeld; // Is need sell all held
uint depositDecrease; // Deposit decrease
uint depositReturn; // Deposit actual returns
uint sellAmount;
uint receiveAmount;
uint token0Price;
uint outstandingAmount;
uint32 dexDetail;
}
struct MarginRatioVars {
address heldToken;
address sellToken;
address owner;
uint held;
bytes dexData;
uint16 multiplier;
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.7.6;
abstract contract DelegatorInterface {
/**
* Implementation address for this contract
*/
address public implementation;
/**
* Emitted when implementation is changed
*/
event NewImplementation(address oldImplementation, address newImplementation);
/**
* Called by the admin to update the implementation of the delegator
* @param implementation_ The address of the new implementation for delegation
*/
function setImplementation(address implementation_) public virtual;
/**
* Internal method to delegate execution to another contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
* @param callee The contract to delegatecall
* @param data The raw data to delegatecall
* @return The returned bytes from the delegatecall
*/
function delegateTo(address callee, bytes memory data) internal returns (bytes memory) {
(bool success, bytes memory returnData) = callee.delegatecall(data);
assembly {
if eq(success, 0) {revert(add(returnData, 0x20), returndatasize())}
}
return returnData;
}
/**
* Delegates execution to the implementation contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
* @param data The raw data to delegatecall
* @return The returned bytes from the delegatecall
*/
function delegateToImplementation(bytes memory data) public returns (bytes memory) {
return delegateTo(implementation, data);
}
/**
* Delegates execution to an implementation contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
* There are an additional 2 prefix uints from the wrapper returndata, which we ignore since we make an extra hop.
* @param data The raw data to delegatecall
* @return The returned bytes from the delegatecall
*/
function delegateToViewImplementation(bytes memory data) public view returns (bytes memory) {
(bool success, bytes memory returnData) = address(this).staticcall(abi.encodeWithSignature("delegateToImplementation(bytes)", data));
assembly {
if eq(success, 0) {revert(add(returnData, 0x20), returndatasize())}
}
return abi.decode(returnData, (bytes));
}
/**
* Delegates execution to an implementation contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
*/
fallback() external payable {
_fallback();
}
receive() external payable {
_fallback();
}
function _fallback() internal {
// delegate all other functions to current implementation
if (msg.data.length > 0) {
(bool success,) = implementation.delegatecall(msg.data);
assembly {
let free_mem_ptr := mload(0x40)
returndatacopy(free_mem_ptr, 0, returndatasize())
switch success
case 0 {revert(free_mem_ptr, returndatasize())}
default {return (free_mem_ptr, returndatasize())}
}
}
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.7.6;
abstract contract Adminable {
address payable public admin;
address payable public pendingAdmin;
address payable public developer;
event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin);
event NewAdmin(address oldAdmin, address newAdmin);
constructor () {
developer = msg.sender;
}
modifier onlyAdmin() {
require(msg.sender == admin, "caller must be admin");
_;
}
modifier onlyAdminOrDeveloper() {
require(msg.sender == admin || msg.sender == developer, "caller must be admin or developer");
_;
}
function setPendingAdmin(address payable newPendingAdmin) external virtual onlyAdmin {
// Save current value, if any, for inclusion in log
address oldPendingAdmin = pendingAdmin;
// Store pendingAdmin with value newPendingAdmin
pendingAdmin = newPendingAdmin;
// Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin)
emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin);
}
function acceptAdmin() external virtual {
require(msg.sender == pendingAdmin, "only pendingAdmin can accept admin");
// Save current values for inclusion in log
address oldAdmin = admin;
address oldPendingAdmin = pendingAdmin;
// Store admin with value pendingAdmin
admin = pendingAdmin;
// Clear the pending value
pendingAdmin = address(0);
emit NewAdmin(oldAdmin, admin);
emit NewPendingAdmin(oldPendingAdmin, pendingAdmin);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev 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;
}
} | Block number when the trade was touched last time, to prevent more than one operation within same block
| uint128 lastBlockNum; | 10,000,559 | [
1,
1768,
1300,
1347,
326,
18542,
1703,
358,
19370,
1142,
813,
16,
358,
5309,
1898,
2353,
1245,
1674,
3470,
1967,
1203,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
2254,
10392,
1142,
1768,
2578,
31,
3639,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/EnumerableSet.sol";
import "../utils/Address.sol";
import "../utils/Context.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControl is Context {
using EnumerableSet for EnumerableSet.AddressSet;
using Address for address;
struct RoleData {
EnumerableSet.AddressSet members;
bytes32 adminRole;
}
mapping (bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view returns (bool) {
return _roles[role].members.contains(account);
}
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) public view returns (uint256) {
return _roles[role].members.length();
}
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) public view returns (address) {
return _roles[role].members.at(index);
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant");
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke");
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
emit RoleAdminChanged(role, _roles[role].adminRole, adminRole);
_roles[role].adminRole = adminRole;
}
function _grantRole(bytes32 role, address account) private {
if (_roles[role].members.add(account)) {
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (_roles[role].members.remove(account)) {
emit RoleRevoked(role, account, _msgSender());
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
// SPDX-License-Identifier: None
pragma solidity >=0.7.5;
pragma abicoder v2;
import "@openzeppelin/contracts/access/AccessControl.sol";
import "./Initializable.sol";
/// @title Admin Role Contract
/// @author DEXAG, Inc.
/// @notice This contract is a utility for an admin role access.
abstract contract Adminable is Initializable, AccessControl {
bytes32 public SLINGSHOT_ADMIN_ROLE;
modifier onlyAdmin() {
require(hasRole(SLINGSHOT_ADMIN_ROLE, _msgSender()), "Adminable: not an admin");
_;
}
/// @param role role hash
modifier onlyRole(bytes32 role) {
require(hasRole(role, _msgSender()), "Adminable: not a role");
_;
}
modifier onlyAdminIfInitialized() {
if (isInitialized()) {
// if admin is set, require admin to be msg.sender
if(getRoleMemberCount(SLINGSHOT_ADMIN_ROLE) > 0) {
require(hasRole(SLINGSHOT_ADMIN_ROLE, _msgSender()), "Adminable: not an admin");
_;
}
// if no admin is set, just silently skip the execution. Proxy owner
// and slingshot admin may be two separate wallets so we don't revert
// the transaction to avoid jeopardizing contract implementation deployment
// - at these gas prices, it'd be almost a crime if we did.
} else {
// if not initialized, just let it execute
_;
}
}
/// @notice Set default admin role
/// @param _admin Address to control admin functions
function initializeAdmin(address _admin) internal initializer {
SLINGSHOT_ADMIN_ROLE = keccak256("SLINGSHOT_ADMIN_ROLE");
_setRoleAdmin(SLINGSHOT_ADMIN_ROLE, SLINGSHOT_ADMIN_ROLE);
_setupRole(SLINGSHOT_ADMIN_ROLE, _admin);
}
}
// SPDX-License-Identifier: MIT
// solhint-disable-next-line compiler-version
pragma solidity >=0.7.5;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
function isInitialized() public view returns (bool) {
return _initialized;
}
/// @dev Returns true if and only if the function is running in the constructor
function _isConstructor() private view returns (bool) {
// extcodesize checks the size of the code stored in an address, and
// address returns the current address. Since the code is still not
// deployed when running a constructor, any checks on its code size will
// yield zero, making it an effective way to detect if a contract is
// under construction or not.
address self = address(this);
uint256 cs;
// solhint-disable-next-line no-inline-assembly
assembly { cs := extcodesize(self) }
return cs == 0;
}
}
// SPDX-License-Identifier: None
pragma solidity >=0.7.5;
import "./Adminable.sol";
import "./module/ISlingshotModule.sol";
/// @title Module Registry Contract
/// @author DEXAG, Inc.
/// @notice This contract provides the logic for querying, maintaining, and updating Slingshot modules.
/// @dev When a new module is deployed, it must be registered. If the logic for a particular
/// DEX/AMM changes, a new module must be deployed and registered.
contract ModuleRegistry is Adminable {
/// @notice This is an index which indicates the validity of a module
mapping(address => bool) public modulesIndex;
/// @notice Slingshot.sol address
address public slingshot;
event ModuleRegistered(address moduleAddress);
event ModuleUnregistered(address moduleAddress);
event NewSlingshot(address oldAddress, address newAddress);
/// @notice Use this function for post upgrade setup
/// @param _admin Address to control admin functions
function postUpgrade(address _admin) external onlyAdminIfInitialized {
// skip when initialized
if (!isInitialized()) initialize(_admin);
// all other post upgrade setup below
}
/// @notice Initialization function for proxy setup
/// @param _admin Address to control admin functions
function initialize(address _admin) internal initializer {
initializeAdmin(_admin);
}
/// @notice Checks if given address is a module
/// @param _moduleAddress Address of the module in question
/// @return true if address is module
function isModule(address _moduleAddress) external view returns (bool) {
return modulesIndex[_moduleAddress];
}
/// @param _moduleAddress Address of the module to register
function registerSwapModule(address _moduleAddress) external onlyAdmin {
require(!modulesIndex[_moduleAddress], "oops module already exists");
require(ISlingshotModule(_moduleAddress).slingshotPing(), "not a module");
modulesIndex[_moduleAddress] = true;
emit ModuleRegistered(_moduleAddress);
}
/// @param _moduleAddress Address of the module to unregister
function unregisterSwapModule(address _moduleAddress) external onlyAdmin {
require(modulesIndex[_moduleAddress], "module NOT exist");
delete modulesIndex[_moduleAddress];
emit ModuleUnregistered(_moduleAddress);
}
/// @param _slingshot Slingshot.sol address implementation
function setSlingshot(address _slingshot) external onlyAdmin {
require(_slingshot != address(0x0), "slingshot is empty");
require(slingshot != _slingshot, "no changes to slingshot");
address oldAddress = slingshot;
slingshot = _slingshot;
emit NewSlingshot(oldAddress, _slingshot);
}
}
// SPDX-License-Identifier: None
pragma solidity >=0.7.5;
pragma abicoder v2;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "./Adminable.sol";
import "./lib/Strings.sol";
import "./ModuleRegistry.sol";
interface IWETH is IERC20 {
function deposit() external payable;
function balanceOf(uint256 amount) external returns (uint256);
function withdraw(uint256 amount) external;
}
/// @title Slingshot Trading Contract
/// @author DEXAG, Inc.
/// @notice This contract serves as the entrypoint for executing
/// a Slingshot transaction on-chain.
/// @dev The specific logic for each DEX/AMM is defined within its
/// own corresponding module that is stored in the module registry.
/// Slingshot.sol references these modules to appropriately execute a trade.
/// Slingshot.sol also performs some safety checks to account for slippage
/// and security. Slingshot.sol depends on the Slingshot backend to provide
/// the details of how a given transaction will be executed within a
/// particular market.
contract Slingshot is Adminable, Strings {
using SafeMath for uint256;
using SafeERC20 for IERC20;
address public ETH_ADDRESS;
IWETH public WETH;
struct TradeFormat {
address moduleAddress;
bytes encodedCalldata;
}
ModuleRegistry public moduleRegistry;
event Trade(
address indexed user,
address fromToken,
address toToken,
uint256 fromAmount,
uint256 toAmount,
address recipient
);
event NewModuleRegistry(address oldRegistry, address newRegistry);
/// @notice Use this function for post upgrade setup
/// @param _admin Address to control admin functions
function postUpgrade(address _admin) external onlyAdminIfInitialized {
// skip when initialized
if (!isInitialized()) initialize(_admin);
// all other post upgrade setup below
}
/// @notice Initialization function for proxy setup
/// @param _admin Address to control admin functions
function initialize(address _admin) internal initializer {
initializeAdmin(_admin);
ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
WETH = IWETH(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);
}
/// @notice Executes multi-hop trades to get the best result
/// It's up to BE to whitelist tokens
/// @param fromToken Start token address
/// @param toToken Target token address
/// @param fromAmount The initial amount of fromToken to start trading with
/// @param trades Array of encoded trades that are atomically executed
/// @param finalAmountMin The minimum expected output after all trades have been executed
/// @param recipient The address that will receive the output of a trade
function executeTrades(
address fromToken,
address toToken,
uint256 fromAmount,
TradeFormat[] calldata trades,
uint256 finalAmountMin,
address recipient
) public payable {
uint256 initialBalance = _getTokenBalance(toToken);
_transferFromOrWrap(fromToken, _msgSender(), fromAmount);
// Checks to make sure that module exists and is correct
for(uint256 i = 0; i < trades.length; i++) {
require(moduleRegistry.isModule(trades[i].moduleAddress), "Slingshot: not a module");
// delagatecall message is made on module contract, which is trusted
(bool success, bytes memory data) = trades[i].moduleAddress.delegatecall(trades[i].encodedCalldata);
require(success, appendString(prependNumber(i, ", Slingshot: swap failed: "), string(data)));
}
uint256 finalBalance = _getTokenBalance(toToken);
uint256 finalAmount = finalBalance.sub(initialBalance);
require(finalAmount >= finalAmountMin, "Slingshot: result is lower than required min");
emit Trade(_msgSender(), fromToken, toToken, fromAmount, finalAmount, recipient);
// Send to recipient address. Generally expected to be msg.sender, but can also be defined by user.
// This allows for more flexibility, but isn't necessary.
_sendFunds(toToken, recipient, finalAmount);
}
/// @notice Sets module registry used to verify modules
/// @param _moduleRegistry The address of module registry
function setModuleRegistry(address _moduleRegistry) external onlyAdmin {
address oldRegistry = address(moduleRegistry);
moduleRegistry = ModuleRegistry(_moduleRegistry);
emit NewModuleRegistry(oldRegistry, _moduleRegistry);
}
/// @notice In an unlikely scenario of tokens being send to this contract
/// allow admin to rescue them.
/// @param token The address of the token to rescue
/// @param to The address of recipient
/// @param amount The amount of the token to rescue
function rescueTokens(address token, address to, uint256 amount) external onlyAdmin {
if (token == ETH_ADDRESS) {
(bool success, ) = to.call{value: amount}("");
require(success, "Slingshot: ETH rescue failed.");
} else {
IERC20(token).safeTransfer(to, amount);
}
}
/// @notice Transfer tokens from sender to this contract or wraps ETH
/// @param fromToken The address of the token
/// @param from The address of sender that provides token
/// @param amount The amount of the token to transfer
function _transferFromOrWrap(address fromToken, address from, uint256 amount) internal {
// transfer tokens or wrap ETH
if (fromToken == ETH_ADDRESS) {
require(msg.value == amount, "Slingshot: incorrect ETH value");
WETH.deposit{value: amount}();
} else {
require(msg.value == 0, "Slingshot: should not send ETH");
IERC20(fromToken).safeTransferFrom(from, address(this), amount);
}
}
/// @notice Returns balance of the token
/// @param token The address of the token
/// @return balance of the token, defaults to WETH for ETH
function _getTokenBalance(address token) internal view returns (uint256) {
if (token == ETH_ADDRESS) {
return WETH.balanceOf(address(this));
} else {
return IERC20(token).balanceOf(address(this));
}
}
/// @notice Sends token funds. For ETH, it unwraps WETH
/// @param token The address of the token to send
/// @param to The address of recipient
/// @param amount The amount of the token to send
function _sendFunds(address token, address to, uint256 amount) internal {
if (token == ETH_ADDRESS) {
WETH.withdraw(amount);
(bool success, ) = to.call{value: amount}("");
require(success, "Slingshot: ETH Transfer failed.");
} else {
IERC20(token).safeTransfer(to, amount);
}
}
receive() external payable {}
}
// SPDX-License-Identifier: None
pragma solidity >=0.7.5;
/// @title Strings
/// @notice Utility library for strings
contract Strings {
/// @notice Concat two strings
/// @param str1 String to concat
/// @param str2 String to concat
/// @return result Concatenated strings
function appendString(string memory str1, string memory str2) public pure returns (string memory result) {
return string(abi.encodePacked(str1, str2));
}
/// @notice Concat number and string
/// @param i Number to concat
/// @param str String to concat
/// @return result Concatenated string and number
function prependNumber(uint256 i, string memory str) public pure returns (string memory result) {
if (i == 0) {
return string(abi.encodePacked("0", str));
}
return prependNumber(i / 10, string(abi.encodePacked(uint8((i % 10) + 48), str)));
}
}
// SPDX-License-Identifier: None
pragma solidity >=0.7.5;
pragma abicoder v2;
/// @title Slingshot Abstract Module
/// @dev the only purpose of this is to allow for easy verification when adding new module
abstract contract ISlingshotModule {
function slingshotPing() public pure returns (bool) {
return true;
}
}
| @notice Concat number and string @param i Number to concat @param str String to concat @return result Concatenated string and number | function prependNumber(uint256 i, string memory str) public pure returns (string memory result) {
if (i == 0) {
return string(abi.encodePacked("0", str));
}
return prependNumber(i / 10, string(abi.encodePacked(uint8((i % 10) + 48), str)));
}
| 13,919,404 | [
1,
15113,
1300,
471,
533,
225,
277,
3588,
358,
3835,
225,
609,
514,
358,
3835,
327,
563,
23873,
275,
690,
533,
471,
1300,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
8254,
1854,
12,
11890,
5034,
277,
16,
533,
3778,
609,
13,
1071,
16618,
1135,
261,
1080,
3778,
563,
13,
288,
203,
3639,
309,
261,
77,
422,
374,
13,
288,
203,
5411,
327,
533,
12,
21457,
18,
3015,
4420,
329,
2932,
20,
3113,
609,
10019,
203,
3639,
289,
203,
203,
3639,
327,
8254,
1854,
12,
77,
342,
1728,
16,
533,
12,
21457,
18,
3015,
4420,
329,
12,
11890,
28,
12443,
77,
738,
1728,
13,
397,
9934,
3631,
609,
3719,
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
] |
pragma solidity ^0.4.24;
import "../math/SafeMath.sol";
/**
* @title SplitPayment
* @dev Base contract that supports multiple payees claiming funds sent to this contract
* according to the proportion they own.
*/
contract SplitPayment {
using SafeMath for uint256;
uint256 public totalShares = 0;
uint256 public totalReleased = 0;
mapping(address => uint256) public shares;
mapping(address => uint256) public released;
address[] public payees;
/**
* @dev Constructor
*/
constructor(address[] _payees, uint256[] _shares) public payable {
require(_payees.length == _shares.length);
require(_payees.length > 0);
for (uint256 i = 0; i < _payees.length; i++) {
_addPayee(_payees[i], _shares[i]);
}
}
/**
* @dev payable fallback
*/
function () external payable {}
/**
* @dev Claim your share of the balance.
*/
function claim() public {
address payee = msg.sender;
require(shares[payee] > 0);
uint256 totalReceived = address(this).balance.add(totalReleased);
uint256 payment = totalReceived.mul(
shares[payee]).div(
totalShares).sub(
released[payee]
);
require(payment != 0);
assert(address(this).balance >= payment);
released[payee] = released[payee].add(payment);
totalReleased = totalReleased.add(payment);
payee.transfer(payment);
}
/**
* @dev Add a new payee to the contract.
* @param _payee The address of the payee to add.
* @param _shares The number of shares owned by the payee.
*/
function _addPayee(address _payee, uint256 _shares) internal {
require(_payee != address(0));
require(_shares > 0);
require(shares[_payee] == 0);
payees.push(_payee);
shares[_payee] = _shares;
totalShares = totalShares.add(_shares);
}
}
| * @dev Add a new payee to the contract. @param _payee The address of the payee to add. @param _shares The number of shares owned by the payee./ | function _addPayee(address _payee, uint256 _shares) internal {
require(_payee != address(0));
require(_shares > 0);
require(shares[_payee] == 0);
payees.push(_payee);
shares[_payee] = _shares;
totalShares = totalShares.add(_shares);
}
| 12,797,043 | [
1,
986,
279,
394,
8843,
1340,
358,
326,
6835,
18,
225,
389,
10239,
1340,
1021,
1758,
434,
326,
8843,
1340,
358,
527,
18,
225,
389,
30720,
1021,
1300,
434,
24123,
16199,
635,
326,
8843,
1340,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
389,
1289,
9148,
1340,
12,
2867,
389,
10239,
1340,
16,
2254,
5034,
389,
30720,
13,
2713,
288,
203,
565,
2583,
24899,
10239,
1340,
480,
1758,
12,
20,
10019,
203,
565,
2583,
24899,
30720,
405,
374,
1769,
203,
565,
2583,
12,
30720,
63,
67,
10239,
1340,
65,
422,
374,
1769,
203,
203,
565,
8843,
25521,
18,
6206,
24899,
10239,
1340,
1769,
203,
565,
24123,
63,
67,
10239,
1340,
65,
273,
389,
30720,
31,
203,
565,
2078,
24051,
273,
2078,
24051,
18,
1289,
24899,
30720,
1769,
203,
225,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
/// @title Places ERC-721 contract
/// @author Places DAO
/*************************************
* ████░░░░░░░░░░░░░░░░░░░░░░░░░████ *
* ██░░░░░░░██████░░██████░░░░░░░░██ *
* ░░░░░░░██████████████████░░░░░░░░ *
* ░░░░░████████ ████████░░░░░░ *
* ░░░░░██████ ██████ ██████░░░░░░ *
* ░░░░░██████ ██████ ██████░░░░░░ *
* ░░░░░░░████ ██████ ████░░░░░░░░ *
* ░░░░░░░░░████ ████░░░░░░░░░░ *
* ░░░░░░░░░░░██████████░░░░░░░░░░░░ *
* ░░░░░░░░░░░░░██████░░░░░░░░░░░░░░ *
* ██░░░░░░░░░░░░░██░░░░░░░░░░░░░░██ *
* ████░░░░░░░░░░░░░░░░░░░░░░░░░████ *
*************************************/
pragma solidity ^0.8.6;
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Burnable.sol";
import "@openzeppelin/contracts/security/Pausable.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import {IPlaces} from "./interfaces/IPlaces.sol";
import {IPlacesDescriptor} from "./interfaces/IPlacesDescriptor.sol";
import {IPlacesProvider} from "./interfaces/IPlacesProvider.sol";
import {IProxyRegistry} from "./external/IProxyRegistry.sol";
contract Places is
ERC721,
ERC721Enumerable,
ERC721URIStorage,
ERC721Burnable,
Pausable,
ReentrancyGuard,
Ownable
{
using Counters for Counters.Counter;
event PlacesDAOUpdated(address placesDao);
event GroundersUpdated(address grounders);
event DescriptorUpdated(IPlacesDescriptor descriptor);
event PlacesProviderUpdated(IPlacesProvider provider);
event PlaceCreated(uint256 tokenId);
event PlaceBurned(uint256 tokenId);
event MintFeeUpdated(uint256 mintFee);
event NeighborhoodTreasuryEnabledUpdated(bool isEnabled);
event GuestlistEnabledUpdated(bool isEnabled);
event GroundersGiftingEnabledUpdated(bool isEnabled);
/**
* @notice Location encoded integer maximum and minimum values for on-chain computation.
* @dev IPlace.Place.Location returns both integer and string representations for use.
*/
int256 public constant MAX_LATITUDE_INT = 9000000000000000;
int256 public constant MIN_LATITUDE_INT = -9000000000000000;
int256 public constant MAX_LONGITUDE_INT = 18000000000000000;
int256 public constant MIN_LONGITUDE_INT = -18000000000000000;
/**
* @notice Location integer resolution allowing for 14 places of decimal storage and enable on-chain computation.
* @dev IPlace.Place.Location returns both integer and string representations for use.
*/
int256 public constant GEO_RESOLUTION_INT = 100000000000000;
IProxyRegistry public immutable proxyRegistry;
Counters.Counter private _tokenIdCounter;
address payable private _placesDAO;
address private _grounders;
IPlacesProvider private _placesProvider;
IPlacesDescriptor private _placesDescriptor;
address[] private _guestlistKeys;
mapping(address => bool) private _guestlist;
uint256 private _mintFee;
uint256 private _randomGrounderOffset;
bool private _isGuestlistEnabled;
bool private _isGroundersGiftingEnabled;
bool private _isNeighborhoodTreasuryEnabled;
/**
* @notice Require that the sender is a grounders.
*/
modifier onlyGrounders() {
require(
(_msgSender() == _grounders || _msgSender() == owner()),
"Not a grounder"
);
_;
}
/**
* @notice Set the places DAO.
* @dev Only callable by the grounders.
*/
function setPlacesDAO(address payable placesDAO) external onlyGrounders {
_placesDAO = placesDAO;
emit PlacesDAOUpdated(placesDAO);
}
/**
* @notice Set the grounders.
* @dev Only callable by the grounders.
*/
function setGrounders(address grounders) external onlyGrounders {
_grounders = grounders;
emit GroundersUpdated(grounders);
}
/**
* @notice Set the place provider.
* @dev Only callable by the grounders.
*/
function setPlacesProvider(IPlacesProvider placesProvider)
external
onlyGrounders
{
_placesProvider = placesProvider;
_randomGrounderOffset =
uint256(keccak256(abi.encodePacked(block.number))) %
10;
emit PlacesProviderUpdated(placesProvider);
}
/**
* @notice Set the descriptor.
* @dev Only callable by the grounders.
*/
function setDescriptor(IPlacesDescriptor placesDescriptor)
external
onlyGrounders
{
_placesDescriptor = placesDescriptor;
emit DescriptorUpdated(placesDescriptor);
}
/**
* @notice Pause minting.
* @dev Only callable by the grounders.
*/
function setPaused(bool paused) external onlyGrounders {
if (paused) {
_pause();
} else {
_unpause();
}
}
/**
* @notice Reset and increment counter.
* @dev Only callable by the grounders.
*/
function setCounter(uint256 _countValue) external onlyGrounders {
_tokenIdCounter.reset();
while (_tokenIdCounter.current() < _countValue) {
_tokenIdCounter.increment();
}
}
/**
* @notice Toggle guestlisting.
* @dev Only callable by the grounders.
*/
function setGuestlistEnabled(bool isGuestlistEnabled)
external
onlyGrounders
{
_isGuestlistEnabled = isGuestlistEnabled;
emit GuestlistEnabledUpdated(isGuestlistEnabled);
}
/**
* @notice Update guestlist addresses.
* @dev Only callable by the grounders.
*/
function setGuestlist(address[] memory guestlist) external onlyGrounders {
// unregister existing addresses from quick access
for (uint256 i = 0; i < _guestlistKeys.length; i++) {
if (_guestlist[_guestlistKeys[i]]) {
delete _guestlist[_guestlistKeys[i]];
}
}
// copy new guestlist
delete _guestlistKeys;
for (uint256 j = 0; j < guestlist.length; j++) {
_guestlistKeys.push(guestlist[j]);
}
// register addresses for quick access
for (uint256 k = 0; k < guestlist.length; k++) {
_guestlist[guestlist[k]] = true;
}
}
/**
* @notice Add an address to the guestlist.
* @dev Only callable by the grounders.
*/
function addGuest(address guestAddress) external onlyGrounders {
_guestlistKeys.push(guestAddress);
_guestlist[guestAddress] = true;
}
/**
* @notice Toggle grounder gifting.
* @dev Only callable by the grounders.
*/
function setGroundersGifting(bool isGroundersGiftingEnabled)
external
onlyGrounders
{
_isGroundersGiftingEnabled = isGroundersGiftingEnabled;
emit GroundersGiftingEnabledUpdated(isGroundersGiftingEnabled);
}
/**
* @notice Update the minting fee.
* @dev Only callable by the grounders.
*/
function setMintFee(uint256 mintFee) external onlyGrounders {
_mintFee = mintFee;
emit MintFeeUpdated(mintFee);
}
/**
* @notice Toggle neighborhood treasury.
* @dev Only callable by the grounders.
*/
function setNeighborhoodTreasury(bool isNeighborhoodTreasuryEnabled)
external
onlyGrounders
{
_isNeighborhoodTreasuryEnabled = isNeighborhoodTreasuryEnabled;
emit NeighborhoodTreasuryEnabledUpdated(isNeighborhoodTreasuryEnabled);
}
constructor(
address payable placesDAO,
address grounders,
IPlacesDescriptor placesDescriptor,
IPlacesProvider placesProvider,
address _proxyAddress
) ERC721("Places", "PLACES") {
_placesDAO = placesDAO;
_grounders = grounders;
_placesDescriptor = placesDescriptor;
_placesProvider = placesProvider;
proxyRegistry = IProxyRegistry(_proxyAddress);
_isGuestlistEnabled = false;
_isGroundersGiftingEnabled = true;
_isNeighborhoodTreasuryEnabled = true;
_mintFee = 0;
_randomGrounderOffset =
uint256(keccak256(abi.encodePacked(block.number))) %
10;
}
/**
* @notice Override isApprovedForAll to whitelist user's OpenSea proxy accounts to enable gas-less listings.
*/
function isApprovedForAll(address owner, address operator)
public
view
override(ERC721)
returns (bool)
{
if (proxyRegistry.proxies(owner) == operator) {
return true;
}
return super.isApprovedForAll(owner, operator);
}
/**
* @notice Request location information for place.
*/
function getLocation(uint256 tokenId)
public
view
returns (IPlaces.Location memory)
{
require(_exists(tokenId), "Token must exist");
return _placesProvider.getPlace(tokenId).location;
}
/**
* @notice Request place information.
*/
function getPlace(uint256 tokenId)
public
view
returns (IPlaces.Place memory)
{
require(_exists(tokenId), "Token must exist");
return _placesProvider.getPlace(tokenId);
}
/**
* @notice Requests place supply count (both minted & available on-chain).
* @dev Subtract totalSupply() to determine available to be minted.
*/
function getPlaceSupply() public view returns (uint256 supplyCount) {
return _placesProvider.getPlaceSupply();
}
/**
* @notice Requests the current fee for minting in wei.
*/
function getMintFeeInWei() public view returns (uint256 currentMintFee) {
return _mintFee;
}
/**
* @notice Requests state of grounder gifting.
*/
function getGroundersGiftingEnabled() public view returns (bool isEnabled) {
return _isGroundersGiftingEnabled;
}
/**
* @notice Requests state of neighorhood treasury sending.
*/
function getNeighborhoodTreasuryEnabled()
public
view
returns (bool isEnabled)
{
return _isNeighborhoodTreasuryEnabled;
}
/**
* @notice Generate a random integer.
*/
function random(string memory input) internal pure returns (uint256) {
return uint256(keccak256(abi.encodePacked(input)));
}
/**
* @notice Mint a place.
*/
function mint()
public
payable
whenNotPaused
nonReentrant
returns (uint256)
{
require(msg.value >= _mintFee, "Minimum fee required");
require(!_exists(_tokenIdCounter.current()), "Token already exists");
require(
_tokenIdCounter.current() < _placesProvider.getPlaceSupply(),
"No supply available"
);
if (_isGuestlistEnabled) {
require(_guestlist[_msgSender()], "Mint not permitted");
}
if (
_tokenIdCounter.current() > 0 &&
((_tokenIdCounter.current() + _randomGrounderOffset) % 20 == 0) &&
_isGroundersGiftingEnabled == true
) {
safeMint(_grounders);
}
if (_mintFee > 0) {
uint256 weiAmount = msg.value;
if (_isNeighborhoodTreasuryEnabled) {
uint256 neighborhoodAmount = (weiAmount * 250) / 1000;
uint256 daoAmount = weiAmount - neighborhoodAmount;
address payable neighborhoodTreasury = _placesProvider
.getTreasury(_tokenIdCounter.current());
(bool sentPlacesDAO, ) = _placesDAO.call{value: daoAmount}("");
require(sentPlacesDAO, "DAO deposit failed");
(bool sentNeighborhood, ) = neighborhoodTreasury.call{
value: neighborhoodAmount
}("");
require(sentNeighborhood, "Neighborhood deposit failed");
} else {
(bool sentPlacesDAO, ) = _placesDAO.call{value: weiAmount}("");
require(sentPlacesDAO, "DAO deposit failed");
}
}
safeMint(_msgSender());
emit PlaceCreated(_tokenIdCounter.current() - 1);
return _tokenIdCounter.current() - 1;
}
/**
* @notice Grounder mint a place.
* @dev Only callable by the grounders.
*/
function grounderMint(uint256 tokenId)
public
onlyGrounders
nonReentrant
returns (uint256)
{
_safeMint(_grounders, tokenId);
emit PlaceCreated(tokenId);
return tokenId;
}
/**
* @notice Owner mint a place.
* @dev Only callable by the owners.
*/
function ownerMint(uint256 tokenId)
public
onlyOwner
nonReentrant
returns (uint256)
{
_safeMint(owner(), tokenId);
emit PlaceCreated(tokenId);
return tokenId;
}
/**
* @notice Internal utility for minting.
* @dev Increments the internal token counter.
*/
function safeMint(address to) internal {
_safeMint(to, _tokenIdCounter.current());
_tokenIdCounter.increment();
}
/**
* @notice Internal hook.
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal override(ERC721, ERC721Enumerable) {
super._beforeTokenTransfer(from, to, tokenId);
}
/**
* @notice Burn a place.
* @dev Only callable by the owners.
*/
function _burn(uint256 tokenId)
internal
override(ERC721, ERC721URIStorage)
onlyGrounders
{
super._burn(tokenId);
emit PlaceBurned(tokenId);
}
/**
* @notice Construct an ERC721 token URI.
*/
function tokenURI(uint256 tokenId)
public
view
override(ERC721, ERC721URIStorage)
returns (string memory)
{
require(_exists(tokenId), "Token must exist");
return
_placesDescriptor.constructTokenURI(
tokenId,
_placesProvider.getPlace(tokenId)
);
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId)
public
view
override(ERC721, ERC721Enumerable)
returns (bool)
{
return super.supportsInterface(interfaceId);
}
/**
* @notice Construct an Opensea contract URI.
*/
function contractURI(uint256 tokenId) public view returns (string memory) {
require(_exists(tokenId), "Token must exist");
return _placesDescriptor.constructContractURI();
}
}
// SPDX-License-Identifier: MIT
/// @title Interface for Places provider
/// @author Places DAO
/*************************************
* ████░░░░░░░░░░░░░░░░░░░░░░░░░████ *
* ██░░░░░░░██████░░██████░░░░░░░░██ *
* ░░░░░░░██████████████████░░░░░░░░ *
* ░░░░░████████ ████████░░░░░░ *
* ░░░░░██████ ██████ ██████░░░░░░ *
* ░░░░░██████ ██████ ██████░░░░░░ *
* ░░░░░░░████ ██████ ████░░░░░░░░ *
* ░░░░░░░░░████ ████░░░░░░░░░░ *
* ░░░░░░░░░░░██████████░░░░░░░░░░░░ *
* ░░░░░░░░░░░░░██████░░░░░░░░░░░░░░ *
* ██░░░░░░░░░░░░░██░░░░░░░░░░░░░░██ *
* ████░░░░░░░░░░░░░░░░░░░░░░░░░████ *
*************************************/
pragma solidity ^0.8.6;
import {IPlaces} from "./IPlaces.sol";
interface IPlacesProvider {
function getTreasury(uint256 tokenId)
external
view
returns (address payable);
function getPlace(uint256 tokenId)
external
view
returns (IPlaces.Place memory);
function getPlaceSupply() external view returns (uint256 supplyCount);
}
// SPDX-License-Identifier: MIT
/// @title Interface for Places descriptor
/// @author Places DAO
/*************************************
* ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ *
* ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ *
* ░░░░░░░███░░░░░░░░░░░░░███░░░░░░░ *
* ░▒▒▒░░░███░░░░░░░░░░░░░███░░░▒▒▒░ *
* ░▒▒▒░░░░░░░░░░░░░░░░░░░░░░░░░▒▒▒░ *
* ░░░░█████████████████████████░░░░ *
* ░░░░░░█████ ███ █████░░░░░░ *
* ░░░░░░░░█████████████████░░░░░░░░ *
* ░░░░░░░░░░████▓▓▓▓▓▓███░░░░░░░░░░ *
* ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ *
* ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ *
*************************************/
pragma solidity ^0.8.6;
import {IPlaces} from "./IPlaces.sol";
interface IPlacesDescriptor {
function constructContractURI() external pure returns (string memory);
function constructTokenURI(uint256 tokenId, IPlaces.Place memory place)
external
pure
returns (string memory);
}
// SPDX-License-Identifier: MIT
/// @title Interface for Places
/// @author Places DAO
/*************************************
* ████░░░░░░░░░░░░░░░░░░░░░░░░░████ *
* ██░░░░░░░██████░░██████░░░░░░░░██ *
* ░░░░░░░██████████████████░░░░░░░░ *
* ░░░░░████████ ████████░░░░░░ *
* ░░░░░██████ ██████ ██████░░░░░░ *
* ░░░░░██████ ██████ ██████░░░░░░ *
* ░░░░░░░████ ██████ ████░░░░░░░░ *
* ░░░░░░░░░████ ████░░░░░░░░░░ *
* ░░░░░░░░░░░██████████░░░░░░░░░░░░ *
* ░░░░░░░░░░░░░██████░░░░░░░░░░░░░░ *
* ██░░░░░░░░░░░░░██░░░░░░░░░░░░░░██ *
* ████░░░░░░░░░░░░░░░░░░░░░░░░░████ *
*************************************/
pragma solidity ^0.8.6;
interface IPlaces {
/**
* @notice Location – Represents a geographic coordinate with altitude.
*
* Latitude and longitude values are in degrees under the WGS 84 reference
* frame. Altitude values are in meters. Two location types are provided
* int256 and string. The integer representation enables on chain computation
* where as the string representation provides future computational compatability.
*
* Converting a location from a to integer uses GEO_RESOLUTION_INT denominator.
* 37.73957402260721 encodes to 3773957402260721
* -122.41902666230027 encodes to -12241902666230027
*
* hasAltitude – a boolean that indicates the validity of the altitude values
* latitudeInt – integer representing the latitude in degrees encoded with
* GEO_RESOLUTION_INT
* longitudeInt – integer representing the longitude in degrees encoded with
* GEO_RESOLUTION_INT
* altitudeInt – integer representing the altitude in meters encoded with
* GEO_RESOLUTION_INT
* latitude – string representing the latitude coordinate in degrees under
* the WGS 84 reference frame
* longitude – string representing the longitude coordinate in degrees under
* the WGS 84 reference frame
* altitude – string representing the altitude measurement in meters
*/
struct Location {
int256 latitudeInt;
int256 longitudeInt;
int256 altitudeInt;
bool hasAltitude;
string latitude;
string longitude;
string altitude;
}
/**
* @notice Place – Represents place information for a geographic location.
*
* name – string representing the place name
* streetAddress – string indicating a precise address
* sublocality – string representing the subdivision and first-order civil
* entity below locality (neighborhood or common name)
* locality – string representing the incorporated city or town political
* entity
* subadministrativeArea – string representing the subdivision of the
* second-order civil entity (county name)
* administrativeArea – string representing the second-order civil entity
* below country (state or region name)
* country – string representing the national political entity
* postalCode – string representing the code used to address postal mail
* within the country
* countryCode – string representing the ISO 3166-1 country code,
* https://en.wikipedia.org/wiki/ISO_3166-1
* location – geographic location of the place, see Location type
* attributes – string array of attributes describing the place
*/
struct Place {
string name;
string streetAddress;
string sublocality;
string locality;
string subadministrativeArea;
string administrativeArea;
string country;
string postalCode;
string countryCode;
Location location;
string[3] attributes;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.6;
interface IProxyRegistry {
function proxies(address) external view returns (address);
}
// 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 "./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 String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
library Counters {
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
unchecked {
counter._value += 1;
}
}
function decrement(Counter storage counter) internal {
uint256 value = counter._value;
require(value > 0, "Counter: decrement overflow");
unchecked {
counter._value = value - 1;
}
}
function reset(Counter storage counter) internal {
counter._value = 0;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
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;
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);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../ERC721.sol";
/**
* @dev ERC721 token with storage based token URI management.
*/
abstract contract ERC721URIStorage is ERC721 {
using Strings for uint256;
// Optional mapping for token URIs
mapping(uint256 => string) private _tokenURIs;
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721URIStorage: URI query for nonexistent token");
string memory _tokenURI = _tokenURIs[tokenId];
string memory base = _baseURI();
// If there is no base URI, return the token URI.
if (bytes(base).length == 0) {
return _tokenURI;
}
// If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked).
if (bytes(_tokenURI).length > 0) {
return string(abi.encodePacked(base, _tokenURI));
}
return super.tokenURI(tokenId);
}
/**
* @dev Sets `_tokenURI` as the tokenURI of `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual {
require(_exists(tokenId), "ERC721URIStorage: URI set of nonexistent token");
_tokenURIs[tokenId] = _tokenURI;
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual override {
super._burn(tokenId);
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
}
}
// 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;
import "../ERC721.sol";
import "../../../utils/Context.sol";
/**
* @title ERC721 Burnable Token
* @dev ERC721 Token that can be irreversibly burned (destroyed).
*/
abstract contract ERC721Burnable is Context, ERC721 {
/**
* @dev Burns `tokenId`. See {ERC721-_burn}.
*
* Requirements:
*
* - The caller must own `tokenId` or be an approved operator.
*/
function burn(uint256 tokenId) public virtual {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721Burnable: caller is not owner nor approved");
_burn(tokenId);
}
}
// SPDX-License-Identifier: MIT
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 "../../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;
import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
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 {}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor() {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
// SPDX-License-Identifier: MIT
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() {
_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);
}
} | * @notice Pause minting. @dev Only callable by the grounders./ | function setPaused(bool paused) external onlyGrounders {
if (paused) {
_pause();
_unpause();
}
}
| 6,280,371 | [
1,
19205,
312,
474,
310,
18,
225,
5098,
4140,
635,
326,
19209,
414,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
444,
28590,
12,
6430,
17781,
13,
3903,
1338,
43,
2260,
414,
288,
203,
3639,
309,
261,
8774,
3668,
13,
288,
203,
5411,
389,
19476,
5621,
203,
5411,
389,
318,
19476,
5621,
203,
3639,
289,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/0x8b0f3474F7343CCEda1a9B4cf39050cA10D4b798/sources/browser/chairperson_g.sol | "SPDX-License-Identifier: UNLICENSED" | contract ballot {
struct Voter {
uint weight;
bool voted;
uint8 vote;
address delegate;
uint proposals;
}
struct Proposal {
uint voteCount;
}
address chairperson;
mapping(address =>Voter) public voters;
Proposal[] proposal;
Voter voter;
constructor(uint8 _numProposals) public {
chairperson = msg.sender;
voters[chairperson].weight = 1;
voter.proposals = _numProposals;
}
function giveRightToVote(address toVoter) public{
if(msg.sender !=chairperson || voters[toVoter].voted)
voters[toVoter].weight = 1;
}
} | 796,971 | [
1,
6,
3118,
28826,
17,
13211,
17,
3004,
30,
5019,
6065,
1157,
18204,
6,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
6835,
26503,
352,
288,
203,
1377,
203,
3639,
1958,
776,
20005,
288,
203,
5411,
2254,
3119,
31,
203,
5411,
1426,
331,
16474,
31,
203,
5411,
2254,
28,
12501,
31,
203,
5411,
1758,
7152,
31,
203,
5411,
2254,
450,
22536,
31,
203,
3639,
289,
377,
203,
540,
203,
3639,
1958,
19945,
288,
203,
5411,
2254,
12501,
1380,
31,
203,
540,
203,
3639,
289,
203,
203,
3639,
1758,
462,
1826,
12479,
31,
203,
3639,
2874,
12,
2867,
516,
58,
20005,
13,
1071,
331,
352,
414,
31,
203,
3639,
19945,
8526,
14708,
31,
203,
3639,
776,
20005,
331,
20005,
31,
203,
540,
203,
540,
203,
3639,
3885,
12,
11890,
28,
389,
2107,
626,
22536,
13,
1071,
288,
203,
5411,
462,
1826,
12479,
273,
1234,
18,
15330,
31,
203,
5411,
331,
352,
414,
63,
343,
1826,
12479,
8009,
4865,
273,
404,
31,
203,
5411,
331,
20005,
18,
685,
22536,
273,
389,
2107,
626,
22536,
31,
203,
3639,
289,
203,
377,
203,
377,
203,
565,
445,
8492,
4726,
774,
19338,
12,
2867,
358,
58,
20005,
13,
1071,
95,
203,
3639,
309,
12,
3576,
18,
15330,
480,
343,
1826,
12479,
747,
331,
352,
414,
63,
869,
58,
20005,
8009,
90,
16474,
13,
203,
3639,
331,
352,
414,
63,
869,
58,
20005,
8009,
4865,
273,
404,
31,
203,
540,
203,
565,
289,
203,
540,
203,
565,
289,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity 0.5.10;
import "../interfaces/IBlockRewardAuRa.sol";
import "../interfaces/IERC677.sol";
import "../interfaces/IStakingAuRa.sol";
import "../interfaces/IValidatorSetAuRa.sol";
import "../upgradeability/UpgradeableOwned.sol";
import "../libs/SafeMath.sol";
/// @dev Implements staking and withdrawal logic.
contract StakingAuRaBase is UpgradeableOwned, IStakingAuRa {
using SafeMath for uint256;
// =============================================== Storage ========================================================
// WARNING: since this contract is upgradeable, do not remove
// existing storage variables, do not change their order,
// and do not change their types!
address[] internal _pools;
address[] internal _poolsInactive;
address[] internal _poolsToBeElected;
address[] internal _poolsToBeRemoved;
uint256[] internal _poolsLikelihood;
uint256 internal _poolsLikelihoodSum;
mapping(address => address[]) internal _poolDelegators;
mapping(address => address[]) internal _poolDelegatorsInactive;
mapping(address => address[]) internal _stakerPools;
mapping(address => mapping(address => uint256)) internal _stakerPoolsIndexes;
mapping(address => mapping(address => mapping(uint256 => uint256))) internal _stakeAmountByEpoch;
mapping(address => uint256) internal _stakeInitial;
// Reserved storage space to allow for layout changes in the future.
uint256[24] private ______gapForInternal;
/// @dev The limit of the minimum candidate stake (CANDIDATE_MIN_STAKE).
uint256 public candidateMinStake;
/// @dev The limit of the minimum delegator stake (DELEGATOR_MIN_STAKE).
uint256 public delegatorMinStake;
/// @dev The snapshot of tokens amount staked into the specified pool by the specified delegator
/// before the specified staking epoch. Used by the `claimReward` function.
/// The first parameter is the pool staking address, the second one is delegator's address,
/// the third one is staking epoch number.
mapping(address => mapping(address => mapping(uint256 => uint256))) public delegatorStakeSnapshot;
/// @dev The current amount of staking tokens/coins ordered for withdrawal from the specified
/// pool by the specified staker. Used by the `orderWithdraw`, `claimOrderedWithdraw` and other functions.
/// The first parameter is the pool staking address, the second one is the staker address.
mapping(address => mapping(address => uint256)) public orderedWithdrawAmount;
/// @dev The current total amount of staking tokens/coins ordered for withdrawal from
/// the specified pool by all of its stakers. Pool staking address is accepted as a parameter.
mapping(address => uint256) public orderedWithdrawAmountTotal;
/// @dev The number of the staking epoch during which the specified staker ordered
/// the latest withdraw from the specified pool. Used by the `claimOrderedWithdraw` function
/// to allow the ordered amount to be claimed only in future staking epochs. The first parameter
/// is the pool staking address, the second one is the staker address.
mapping(address => mapping(address => uint256)) public orderWithdrawEpoch;
/// @dev The delegator's index in the array returned by the `poolDelegators` getter.
/// Used by the `_removePoolDelegator` internal function. The first parameter is a pool staking address.
/// The second parameter is delegator's address.
/// If the value is zero, it may mean the array doesn't contain the delegator.
/// Check if the delegator is in the array using the `poolDelegators` getter.
mapping(address => mapping(address => uint256)) public poolDelegatorIndex;
/// @dev The delegator's index in the `poolDelegatorsInactive` array.
/// Used by the `_removePoolDelegatorInactive` internal function.
/// A delegator is considered inactive if they have withdrawn their stake from
/// the specified pool but haven't yet claimed an ordered amount.
/// The first parameter is a pool staking address. The second parameter is delegator's address.
mapping(address => mapping(address => uint256)) public poolDelegatorInactiveIndex;
/// @dev The pool's index in the array returned by the `getPoolsInactive` getter.
/// Used by the `_removePoolInactive` internal function. The pool staking address is accepted as a parameter.
mapping(address => uint256) public poolInactiveIndex;
/// @dev The pool's index in the array returned by the `getPools` getter.
/// Used by the `_removePool` internal function. A pool staking address is accepted as a parameter.
/// If the value is zero, it may mean the array doesn't contain the address.
/// Check the address is in the array using the `isPoolActive` getter.
mapping(address => uint256) public poolIndex;
/// @dev The pool's index in the array returned by the `getPoolsToBeElected` getter.
/// Used by the `_deletePoolToBeElected` and `_isPoolToBeElected` internal functions.
/// The pool staking address is accepted as a parameter.
/// If the value is zero, it may mean the array doesn't contain the address.
/// Check the address is in the array using the `getPoolsToBeElected` getter.
mapping(address => uint256) public poolToBeElectedIndex;
/// @dev The pool's index in the array returned by the `getPoolsToBeRemoved` getter.
/// Used by the `_deletePoolToBeRemoved` internal function.
/// The pool staking address is accepted as a parameter.
/// If the value is zero, it may mean the array doesn't contain the address.
/// Check the address is in the array using the `getPoolsToBeRemoved` getter.
mapping(address => uint256) public poolToBeRemovedIndex;
/// @dev A boolean flag indicating whether the reward was already taken
/// from the specified pool by the specified staker for the specified staking epoch.
/// The first parameter is the pool staking address, the second one is staker's address,
/// the third one is staking epoch number.
mapping(address => mapping(address => mapping(uint256 => bool))) public rewardWasTaken;
/// @dev The amount of tokens currently staked into the specified pool by the specified
/// staker. Doesn't include the amount ordered for withdrawal.
/// The first parameter is the pool staking address, the second one is the staker address.
mapping(address => mapping(address => uint256)) public stakeAmount;
/// @dev The number of staking epoch before which the specified delegator placed their first
/// stake into the specified pool. If this is equal to zero, it means the delegator never
/// staked into the specified pool. The first parameter is the pool staking address,
/// the second one is delegator's address.
mapping(address => mapping(address => uint256)) public stakeFirstEpoch;
/// @dev The number of staking epoch before which the specified delegator withdrew their stake
/// from the specified pool. If this is equal to zero and `stakeFirstEpoch` is not zero, that means
/// the delegator still has some stake in the specified pool. The first parameter is the pool
/// staking address, the second one is delegator's address.
mapping(address => mapping(address => uint256)) public stakeLastEpoch;
/// @dev The duration period (in blocks) at the end of staking epoch during which
/// participants are not allowed to stake/withdraw/order/claim their staking tokens/coins.
uint256 public stakeWithdrawDisallowPeriod;
/// @dev The serial number of the current staking epoch.
uint256 public stakingEpoch;
/// @dev The duration of a staking epoch in blocks.
uint256 public stakingEpochDuration;
/// @dev The number of the first block of the current staking epoch.
uint256 public stakingEpochStartBlock;
/// @dev Returns the total amount of staking tokens/coins currently staked into the specified pool.
/// Doesn't include the amount ordered for withdrawal.
/// The pool staking address is accepted as a parameter.
mapping(address => uint256) public stakeAmountTotal;
/// @dev The address of the `ValidatorSetAuRa` contract.
IValidatorSetAuRa public validatorSetContract;
/// @dev The block number of the last change in this contract.
/// Can be used by Staking DApp.
uint256 public lastChangeBlock;
// Reserved storage space to allow for layout changes in the future.
uint256[24] private ______gapForPublic;
// ============================================== Constants =======================================================
/// @dev The max number of candidates (including validators). This limit was determined through stress testing.
uint256 public constant MAX_CANDIDATES = 3000;
// ================================================ Events ========================================================
/// @dev Emitted by `_addPoolActive` internal function to signal that
/// the specified staking address created a new pool.
/// @param poolStakingAddress The staking address of newly added pool.
event AddedPool(address indexed poolStakingAddress);
/// @dev Emitted by the `claimOrderedWithdraw` function to signal the staker withdrew the specified
/// amount of requested tokens/coins from the specified pool during the specified staking epoch.
/// @param fromPoolStakingAddress The pool from which the `staker` withdrew the `amount`.
/// @param staker The address of the staker that withdrew the `amount`.
/// @param stakingEpoch The serial number of the staking epoch during which the claim was made.
/// @param amount The withdrawal amount.
event ClaimedOrderedWithdrawal(
address indexed fromPoolStakingAddress,
address indexed staker,
uint256 indexed stakingEpoch,
uint256 amount
);
/// @dev Emitted by the `moveStake` function to signal the staker moved the specified
/// amount of stake from one pool to another during the specified staking epoch.
/// @param fromPoolStakingAddress The pool from which the `staker` moved the stake.
/// @param toPoolStakingAddress The destination pool where the `staker` moved the stake.
/// @param staker The address of the staker who moved the `amount`.
/// @param stakingEpoch The serial number of the staking epoch during which the `amount` was moved.
/// @param amount The stake amount which was moved.
event MovedStake(
address fromPoolStakingAddress,
address indexed toPoolStakingAddress,
address indexed staker,
uint256 indexed stakingEpoch,
uint256 amount
);
/// @dev Emitted by the `orderWithdraw` function to signal the staker ordered the withdrawal of the
/// specified amount of their stake from the specified pool during the specified staking epoch.
/// @param fromPoolStakingAddress The pool from which the `staker` ordered a withdrawal of the `amount`.
/// @param staker The address of the staker that ordered the withdrawal of the `amount`.
/// @param stakingEpoch The serial number of the staking epoch during which the order was made.
/// @param amount The ordered withdrawal amount. Can be either positive or negative.
/// See the `orderWithdraw` function.
event OrderedWithdrawal(
address indexed fromPoolStakingAddress,
address indexed staker,
uint256 indexed stakingEpoch,
int256 amount
);
/// @dev Emitted by the `stake` function to signal the staker placed a stake of the specified
/// amount for the specified pool during the specified staking epoch.
/// @param toPoolStakingAddress The pool in which the `staker` placed the stake.
/// @param staker The address of the staker that placed the stake.
/// @param stakingEpoch The serial number of the staking epoch during which the stake was made.
/// @param amount The stake amount.
event PlacedStake(
address indexed toPoolStakingAddress,
address indexed staker,
uint256 indexed stakingEpoch,
uint256 amount
);
/// @dev Emitted by `_removePool` internal function to signal that
/// a pool with the specified staking address was removed.
/// @param poolStakingAddress The staking address of removed pool.
event RemovedPool(address indexed poolStakingAddress);
/// @dev Emitted by the `withdraw` function to signal the staker withdrew the specified
/// amount of a stake from the specified pool during the specified staking epoch.
/// @param fromPoolStakingAddress The pool from which the `staker` withdrew the `amount`.
/// @param staker The address of staker that withdrew the `amount`.
/// @param stakingEpoch The serial number of the staking epoch during which the withdrawal was made.
/// @param amount The withdrawal amount.
event WithdrewStake(
address indexed fromPoolStakingAddress,
address indexed staker,
uint256 indexed stakingEpoch,
uint256 amount
);
// ============================================== Modifiers =======================================================
/// @dev Ensures the transaction gas price is not zero.
modifier gasPriceIsValid() {
require(tx.gasprice != 0);
_;
}
/// @dev Ensures the caller is the BlockRewardAuRa contract address.
modifier onlyBlockRewardContract() {
require(msg.sender == validatorSetContract.blockRewardContract());
_;
}
/// @dev Ensures the `initialize` function was called before.
modifier onlyInitialized {
require(isInitialized());
_;
}
/// @dev Ensures the caller is the ValidatorSetAuRa contract address.
modifier onlyValidatorSetContract() {
require(msg.sender == address(validatorSetContract));
_;
}
// =============================================== Setters ========================================================
/// @dev Fallback function. Prevents direct sending native coins to this contract.
function () payable external {
revert();
}
/// @dev Adds a new candidate's pool to the list of active pools (see the `getPools` getter) and
/// moves the specified amount of staking tokens/coins from the candidate's staking address
/// to the candidate's pool. A participant calls this function using their staking address when
/// they want to create a pool. This is a wrapper for the `stake` function.
/// @param _amount The amount of tokens to be staked. Ignored when staking in native coins
/// because `msg.value` is used in that case.
/// @param _miningAddress The mining address of the candidate. The mining address is bound to the staking address
/// (msg.sender). This address cannot be equal to `msg.sender`.
function addPool(uint256 _amount, address _miningAddress) external payable {
_addPool(_amount, msg.sender, _miningAddress, false);
}
/// @dev Adds the `unremovable validator` to either the `poolsToBeElected` or the `poolsToBeRemoved` array
/// depending on their own stake in their own pool when they become removable. This allows the
/// `ValidatorSetAuRa.newValidatorSet` function to recognize the unremovable validator as a regular removable pool.
/// Called by the `ValidatorSet.clearUnremovableValidator` function.
/// @param _unremovableStakingAddress The staking address of the unremovable validator.
function clearUnremovableValidator(address _unremovableStakingAddress) external onlyValidatorSetContract {
require(_unremovableStakingAddress != address(0));
if (stakeAmount[_unremovableStakingAddress][_unremovableStakingAddress] != 0) {
_addPoolToBeElected(_unremovableStakingAddress);
_setLikelihood(_unremovableStakingAddress);
} else {
_addPoolToBeRemoved(_unremovableStakingAddress);
}
}
/// @dev Increments the serial number of the current staking epoch.
/// Called by the `ValidatorSetAuRa.newValidatorSet` at the last block of the finished staking epoch.
function incrementStakingEpoch() external onlyValidatorSetContract {
stakingEpoch++;
}
/// @dev Initializes the network parameters.
/// Can only be called by the constructor of the `InitializerAuRa` contract or owner.
/// @param _validatorSetContract The address of the `ValidatorSetAuRa` contract.
/// @param _initialStakingAddresses The array of initial validators' staking addresses.
/// @param _delegatorMinStake The minimum allowed amount of delegator stake in Wei.
/// @param _candidateMinStake The minimum allowed amount of candidate/validator stake in Wei.
/// @param _stakingEpochDuration The duration of a staking epoch in blocks
/// (e.g., 120954 = 1 week for 5-seconds blocks in AuRa).
/// @param _stakingEpochStartBlock The number of the first block of initial staking epoch
/// (must be zero if the network is starting from genesis block).
/// @param _stakeWithdrawDisallowPeriod The duration period (in blocks) at the end of a staking epoch
/// during which participants cannot stake/withdraw/order/claim their staking tokens/coins
/// (e.g., 4320 = 6 hours for 5-seconds blocks in AuRa).
function initialize(
address _validatorSetContract,
address[] calldata _initialStakingAddresses,
uint256 _delegatorMinStake,
uint256 _candidateMinStake,
uint256 _stakingEpochDuration,
uint256 _stakingEpochStartBlock,
uint256 _stakeWithdrawDisallowPeriod
) external {
require(_validatorSetContract != address(0));
require(_initialStakingAddresses.length > 0);
require(_delegatorMinStake != 0);
require(_candidateMinStake != 0);
require(_stakingEpochDuration != 0);
require(_stakingEpochDuration > _stakeWithdrawDisallowPeriod);
require(_stakeWithdrawDisallowPeriod != 0);
require(_getCurrentBlockNumber() == 0 || msg.sender == _admin());
require(!isInitialized()); // initialization can only be done once
validatorSetContract = IValidatorSetAuRa(_validatorSetContract);
address unremovableStakingAddress = validatorSetContract.unremovableValidator();
for (uint256 i = 0; i < _initialStakingAddresses.length; i++) {
require(_initialStakingAddresses[i] != address(0));
_addPoolActive(_initialStakingAddresses[i], false);
if (_initialStakingAddresses[i] != unremovableStakingAddress) {
_addPoolToBeRemoved(_initialStakingAddresses[i]);
}
}
delegatorMinStake = _delegatorMinStake;
candidateMinStake = _candidateMinStake;
stakingEpochDuration = _stakingEpochDuration;
stakingEpochStartBlock = _stakingEpochStartBlock;
stakeWithdrawDisallowPeriod = _stakeWithdrawDisallowPeriod;
lastChangeBlock = _getCurrentBlockNumber();
}
/// @dev Makes initial validator stakes. Can only be called by the owner
/// before the network starts (after `initialize` is called but before `stakingEpochStartBlock`).
/// Cannot be called more than once and cannot be called when starting from genesis.
/// Requires `StakingAuRa` contract balance to be equal to the `_totalAmount`.
/// @param _totalAmount The initial validator total stake amount (for all initial validators).
function initialValidatorStake(uint256 _totalAmount) external onlyOwner {
uint256 currentBlock = _getCurrentBlockNumber();
require(stakingEpoch == 0);
require(currentBlock < stakingEpochStartBlock);
require(_thisBalance() == _totalAmount);
require(_totalAmount % _pools.length == 0);
uint256 stakingAmount = _totalAmount.div(_pools.length);
uint256 stakingEpochStartBlock_ = stakingEpochStartBlock;
// Temporarily set `stakingEpochStartBlock` to the current block number
// to avoid revert in the `_stake` function
stakingEpochStartBlock = currentBlock;
for (uint256 i = 0; i < _pools.length; i++) {
address stakingAddress = _pools[i];
require(stakeAmount[stakingAddress][stakingAddress] == 0);
_stake(stakingAddress, stakingAddress, stakingAmount);
_stakeInitial[stakingAddress] = stakingAmount;
}
// Restore `stakingEpochStartBlock` value
stakingEpochStartBlock = stakingEpochStartBlock_;
}
/// @dev Removes a specified pool from the `pools` array (a list of active pools which can be retrieved by the
/// `getPools` getter). Called by the `ValidatorSetAuRa._removeMaliciousValidator` internal function
/// when a pool must be removed by the algorithm.
/// @param _stakingAddress The staking address of the pool to be removed.
function removePool(address _stakingAddress) external onlyValidatorSetContract {
_removePool(_stakingAddress);
}
/// @dev Removes pools which are in the `_poolsToBeRemoved` internal array from the `pools` array.
/// Called by the `ValidatorSetAuRa.newValidatorSet` function when a pool must be removed by the algorithm.
function removePools() external onlyValidatorSetContract {
address[] memory poolsToRemove = _poolsToBeRemoved;
for (uint256 i = 0; i < poolsToRemove.length; i++) {
_removePool(poolsToRemove[i]);
}
}
/// @dev Removes the candidate's or validator's pool from the `pools` array (a list of active pools which
/// can be retrieved by the `getPools` getter). When a candidate or validator wants to remove their pool,
/// they should call this function from their staking address. A validator cannot remove their pool while
/// they are an `unremovable validator`.
function removeMyPool() external gasPriceIsValid onlyInitialized {
address stakingAddress = msg.sender;
address miningAddress = validatorSetContract.miningByStakingAddress(stakingAddress);
// initial validator cannot remove their pool during the initial staking epoch
require(stakingEpoch > 0 || !validatorSetContract.isValidator(miningAddress));
require(stakingAddress != validatorSetContract.unremovableValidator());
_removePool(stakingAddress);
}
/// @dev Sets the number of the first block in the upcoming staking epoch.
/// Called by the `ValidatorSetAuRa.newValidatorSet` function at the last block of a staking epoch.
/// @param _blockNumber The number of the very first block in the upcoming staking epoch.
function setStakingEpochStartBlock(uint256 _blockNumber) external onlyValidatorSetContract {
stakingEpochStartBlock = _blockNumber;
}
/// @dev Moves staking tokens/coins from one pool to another. A staker calls this function when they want
/// to move their tokens/coins from one pool to another without withdrawing their tokens/coins.
/// @param _fromPoolStakingAddress The staking address of the source pool.
/// @param _toPoolStakingAddress The staking address of the target pool.
/// @param _amount The amount of staking tokens/coins to be moved. The amount cannot exceed the value returned
/// by the `maxWithdrawAllowed` getter.
function moveStake(
address _fromPoolStakingAddress,
address _toPoolStakingAddress,
uint256 _amount
) external {
require(_fromPoolStakingAddress != _toPoolStakingAddress);
address staker = msg.sender;
_withdraw(_fromPoolStakingAddress, staker, _amount);
_stake(_toPoolStakingAddress, staker, _amount);
emit MovedStake(_fromPoolStakingAddress, _toPoolStakingAddress, staker, stakingEpoch, _amount);
}
/// @dev Moves the specified amount of staking tokens/coins from the staker's address to the staking address of
/// the specified pool. Actually, the amount is stored in a balance of this StakingAuRa contract.
/// A staker calls this function when they want to make a stake into a pool.
/// @param _toPoolStakingAddress The staking address of the pool where the tokens should be staked.
/// @param _amount The amount of tokens to be staked. Ignored when staking in native coins
/// because `msg.value` is used instead.
function stake(address _toPoolStakingAddress, uint256 _amount) external payable {
_stake(_toPoolStakingAddress, _amount);
}
/// @dev Moves the specified amount of staking tokens/coins from the staking address of
/// the specified pool to the staker's address. A staker calls this function when they want to withdraw
/// their tokens/coins.
/// @param _fromPoolStakingAddress The staking address of the pool from which the tokens/coins should be withdrawn.
/// @param _amount The amount of tokens/coins to be withdrawn. The amount cannot exceed the value returned
/// by the `maxWithdrawAllowed` getter.
function withdraw(address _fromPoolStakingAddress, uint256 _amount) external {
address payable staker = msg.sender;
_withdraw(_fromPoolStakingAddress, staker, _amount);
_sendWithdrawnStakeAmount(staker, _amount);
emit WithdrewStake(_fromPoolStakingAddress, staker, stakingEpoch, _amount);
}
/// @dev Orders tokens/coins withdrawal from the staking address of the specified pool to the
/// staker's address. The requested tokens/coins can be claimed after the current staking epoch is complete using
/// the `claimOrderedWithdraw` function.
/// @param _poolStakingAddress The staking address of the pool from which the amount will be withdrawn.
/// @param _amount The amount to be withdrawn. A positive value means the staker wants to either set or
/// increase their withdrawal amount. A negative value means the staker wants to decrease a
/// withdrawal amount that was previously set. The amount cannot exceed the value returned by the
/// `maxWithdrawOrderAllowed` getter.
function orderWithdraw(address _poolStakingAddress, int256 _amount) external gasPriceIsValid onlyInitialized {
require(_poolStakingAddress != address(0));
require(_amount != 0);
address staker = msg.sender;
require(_isWithdrawAllowed(
validatorSetContract.miningByStakingAddress(_poolStakingAddress), staker != _poolStakingAddress
));
uint256 newOrderedAmount = orderedWithdrawAmount[_poolStakingAddress][staker];
uint256 newOrderedAmountTotal = orderedWithdrawAmountTotal[_poolStakingAddress];
uint256 newStakeAmount = stakeAmount[_poolStakingAddress][staker];
uint256 newStakeAmountTotal = stakeAmountTotal[_poolStakingAddress];
if (_amount > 0) {
uint256 amount = uint256(_amount);
// How much can `staker` order for withdrawal from `_poolStakingAddress` at the moment?
require(amount <= maxWithdrawOrderAllowed(_poolStakingAddress, staker));
newOrderedAmount = newOrderedAmount.add(amount);
newOrderedAmountTotal = newOrderedAmountTotal.add(amount);
newStakeAmount = newStakeAmount.sub(amount);
newStakeAmountTotal = newStakeAmountTotal.sub(amount);
orderWithdrawEpoch[_poolStakingAddress][staker] = stakingEpoch;
} else {
uint256 amount = uint256(-_amount);
newOrderedAmount = newOrderedAmount.sub(amount);
newOrderedAmountTotal = newOrderedAmountTotal.sub(amount);
newStakeAmount = newStakeAmount.add(amount);
newStakeAmountTotal = newStakeAmountTotal.add(amount);
}
orderedWithdrawAmount[_poolStakingAddress][staker] = newOrderedAmount;
orderedWithdrawAmountTotal[_poolStakingAddress] = newOrderedAmountTotal;
stakeAmount[_poolStakingAddress][staker] = newStakeAmount;
stakeAmountTotal[_poolStakingAddress] = newStakeAmountTotal;
if (staker == _poolStakingAddress) {
// Initial validator cannot withdraw their initial stake
require(newStakeAmount >= _stakeInitial[staker]);
// The amount to be withdrawn must be the whole staked amount or
// must not exceed the diff between the entire amount and `candidateMinStake`
require(newStakeAmount == 0 || newStakeAmount >= candidateMinStake);
address unremovableStakingAddress = validatorSetContract.unremovableValidator();
if (_amount > 0) { // if the validator orders the `_amount` for withdrawal
if (newStakeAmount == 0 && _poolStakingAddress != unremovableStakingAddress) {
// If the removable validator orders their entire stake,
// mark their pool as `to be removed`
_addPoolToBeRemoved(_poolStakingAddress);
}
} else {
// If the validator wants to reduce withdrawal value,
// add their pool as `active` if it hasn't already done
_addPoolActive(_poolStakingAddress, _poolStakingAddress != unremovableStakingAddress);
}
} else {
// The amount to be withdrawn must be the whole staked amount or
// must not exceed the diff between the entire amount and `delegatorMinStake`
require(newStakeAmount == 0 || newStakeAmount >= delegatorMinStake);
if (_amount > 0) { // if the delegator orders the `_amount` for withdrawal
if (newStakeAmount == 0) {
// If the delegator orders their entire stake,
// remove the delegator from delegator list of the pool
_removePoolDelegator(_poolStakingAddress, staker);
}
} else {
// If the delegator wants to reduce withdrawal value,
// add them to delegator list of the pool if it hasn't already done
_addPoolDelegator(_poolStakingAddress, staker);
}
// Remember stake movement to use it later in the `claimReward` function
_snapshotDelegatorStake(_poolStakingAddress, staker);
}
_setLikelihood(_poolStakingAddress);
emit OrderedWithdrawal(_poolStakingAddress, staker, stakingEpoch, _amount);
}
/// @dev Withdraws the staking tokens/coins from the specified pool ordered during the previous staking epochs with
/// the `orderWithdraw` function. The ordered amount can be retrieved by the `orderedWithdrawAmount` getter.
/// @param _poolStakingAddress The staking address of the pool from which the ordered tokens/coins are withdrawn.
function claimOrderedWithdraw(address _poolStakingAddress) external {
address payable staker = msg.sender;
require(stakingEpoch > orderWithdrawEpoch[_poolStakingAddress][staker]);
require(_isWithdrawAllowed(
validatorSetContract.miningByStakingAddress(_poolStakingAddress), staker != _poolStakingAddress
));
uint256 claimAmount = orderedWithdrawAmount[_poolStakingAddress][staker];
require(claimAmount != 0);
orderedWithdrawAmount[_poolStakingAddress][staker] = 0;
orderedWithdrawAmountTotal[_poolStakingAddress] =
orderedWithdrawAmountTotal[_poolStakingAddress].sub(claimAmount);
if (stakeAmount[_poolStakingAddress][staker] == 0) {
_withdrawCheckPool(_poolStakingAddress, staker);
}
_sendWithdrawnStakeAmount(staker, claimAmount);
emit ClaimedOrderedWithdrawal(_poolStakingAddress, staker, stakingEpoch, claimAmount);
}
/// @dev Sets (updates) the limit of the minimum candidate stake (CANDIDATE_MIN_STAKE).
/// Can only be called by the `owner`.
/// @param _minStake The value of a new limit in Wei.
function setCandidateMinStake(uint256 _minStake) external onlyOwner onlyInitialized {
candidateMinStake = _minStake;
}
/// @dev Sets (updates) the limit of the minimum delegator stake (DELEGATOR_MIN_STAKE).
/// Can only be called by the `owner`.
/// @param _minStake The value of a new limit in Wei.
function setDelegatorMinStake(uint256 _minStake) external onlyOwner onlyInitialized {
delegatorMinStake = _minStake;
}
// =============================================== Getters ========================================================
/// @dev Returns an array of the current active pools (the staking addresses of candidates and validators).
/// The size of the array cannot exceed MAX_CANDIDATES. A pool can be added to this array with the `_addPoolActive`
/// internal function which is called by the `stake` or `orderWithdraw` function. A pool is considered active
/// if its address has at least the minimum stake and this stake is not ordered to be withdrawn.
function getPools() external view returns(address[] memory) {
return _pools;
}
/// @dev Returns an array of the current inactive pools (the staking addresses of former candidates).
/// A pool can be added to this array with the `_addPoolInactive` internal function which is called
/// by `_removePool`. A pool is considered inactive if it is banned for some reason, if its address
/// has zero stake, or if its entire stake is ordered to be withdrawn.
function getPoolsInactive() external view returns(address[] memory) {
return _poolsInactive;
}
/// @dev Returns the array of stake amounts for each corresponding
/// address in the `poolsToBeElected` array (see the `getPoolsToBeElected` getter) and a sum of these amounts.
/// Used by the `ValidatorSetAuRa.newValidatorSet` function when randomly selecting new validators at the last
/// block of a staking epoch. An array value is updated every time any staked amount is changed in this pool
/// (see the `_setLikelihood` internal function).
/// @return `uint256[] likelihoods` - The array of the coefficients. The array length is always equal to the length
/// of the `poolsToBeElected` array.
/// `uint256 sum` - The total sum of the amounts.
function getPoolsLikelihood() external view returns(uint256[] memory likelihoods, uint256 sum) {
return (_poolsLikelihood, _poolsLikelihoodSum);
}
/// @dev Returns the list of pools (their staking addresses) which will participate in a new validator set
/// selection process in the `ValidatorSetAuRa.newValidatorSet` function. This is an array of pools
/// which will be considered as candidates when forming a new validator set (at the last block of a staking epoch).
/// This array is kept updated by the `_addPoolToBeElected` and `_deletePoolToBeElected` internal functions.
function getPoolsToBeElected() external view returns(address[] memory) {
return _poolsToBeElected;
}
/// @dev Returns the list of pools (their staking addresses) which will be removed by the
/// `ValidatorSetAuRa.newValidatorSet` function from the active `pools` array (at the last block
/// of a staking epoch). This array is kept updated by the `_addPoolToBeRemoved`
/// and `_deletePoolToBeRemoved` internal functions. A pool is added to this array when the pool's
/// address withdraws (or orders) all of its own staking tokens from the pool, inactivating the pool.
function getPoolsToBeRemoved() external view returns(address[] memory) {
return _poolsToBeRemoved;
}
/// @dev Returns the list of pools (staking addresses) into which the specified staker have ever staked.
/// @param _staker The staker address (it can be a delegator or a pool staking address itself).
/// @param _offset The index in the array at which the reading should start. Ignored if the `_length` is 0.
/// @param _length The max number of items to return.
function getStakerPools(
address _staker,
uint256 _offset,
uint256 _length
) external view returns(address[] memory result) {
address[] storage stakerPools = _stakerPools[_staker];
if (_length == 0) {
return stakerPools;
}
uint256 maxLength = stakerPools.length.sub(_offset);
result = new address[](_length > maxLength ? maxLength : _length);
for (uint256 i = 0; i < result.length; i++) {
result[i] = stakerPools[_offset + i];
}
}
/// @dev Returns the length of the list of pools into which the specified staker have ever staked.
/// @param _staker The staker address (it can be a delegator or a pool staking address itself).
function getStakerPoolsLength(address _staker) external view returns(uint256) {
return _stakerPools[_staker].length;
}
/// @dev Determines whether staking/withdrawal operations are allowed at the moment.
/// Used by all staking/withdrawal functions.
function areStakeAndWithdrawAllowed() public view returns(bool) {
uint256 currentBlock = _getCurrentBlockNumber();
if (currentBlock < stakingEpochStartBlock) return false;
uint256 allowedDuration = stakingEpochDuration - stakeWithdrawDisallowPeriod;
if (stakingEpochStartBlock == 0) allowedDuration++;
return currentBlock - stakingEpochStartBlock < allowedDuration;
}
/// @dev Returns a boolean flag indicating if the `initialize` function has been called.
function isInitialized() public view returns(bool) {
return validatorSetContract != IValidatorSetAuRa(0);
}
/// @dev Returns a flag indicating whether a specified address is in the `pools` array.
/// See the `getPools` getter.
/// @param _stakingAddress The staking address of the pool.
function isPoolActive(address _stakingAddress) public view returns(bool) {
uint256 index = poolIndex[_stakingAddress];
return index < _pools.length && _pools[index] == _stakingAddress;
}
/// @dev Returns the maximum amount which can be withdrawn from the specified pool by the specified staker
/// at the moment. Used by the `withdraw` and `moveStake` functions.
/// @param _poolStakingAddress The pool staking address from which the withdrawal will be made.
/// @param _staker The staker address that is going to withdraw.
function maxWithdrawAllowed(address _poolStakingAddress, address _staker) public view returns(uint256) {
address miningAddress = validatorSetContract.miningByStakingAddress(_poolStakingAddress);
bool isDelegator = _poolStakingAddress != _staker;
if (!_isWithdrawAllowed(miningAddress, isDelegator)) {
return 0;
}
uint256 canWithdraw = stakeAmount[_poolStakingAddress][_staker];
if (!isDelegator) {
// Initial validator cannot withdraw their initial stake
canWithdraw = canWithdraw.sub(_stakeInitial[_staker]);
}
if (!validatorSetContract.isValidatorOrPending(miningAddress)) {
// The pool is not a validator and is not going to become one,
// so the staker can only withdraw staked amount minus already
// ordered amount
return canWithdraw;
}
// The pool is a validator (active or pending), so the staker can only
// withdraw staked amount minus already ordered amount but
// no more than the amount staked during the current staking epoch
uint256 stakedDuringEpoch = stakeAmountByCurrentEpoch(_poolStakingAddress, _staker);
if (canWithdraw > stakedDuringEpoch) {
canWithdraw = stakedDuringEpoch;
}
return canWithdraw;
}
/// @dev Returns the maximum amount which can be ordered to be withdrawn from the specified pool by the
/// specified staker at the moment. Used by the `orderWithdraw` function.
/// @param _poolStakingAddress The pool staking address from which the withdrawal will be ordered.
/// @param _staker The staker address that is going to order the withdrawal.
function maxWithdrawOrderAllowed(address _poolStakingAddress, address _staker) public view returns(uint256) {
address miningAddress = validatorSetContract.miningByStakingAddress(_poolStakingAddress);
bool isDelegator = _poolStakingAddress != _staker;
if (!_isWithdrawAllowed(miningAddress, isDelegator)) {
return 0;
}
if (!validatorSetContract.isValidatorOrPending(miningAddress)) {
// If the pool is a candidate (not an active validator and not pending one),
// no one can order withdrawal from the `_poolStakingAddress`, but
// anyone can withdraw immediately (see the `maxWithdrawAllowed` getter)
return 0;
}
// If the pool is an active or pending validator, the staker can order withdrawal
// up to their total staking amount minus an already ordered amount
// minus an amount staked during the current staking epoch
uint256 canOrder = stakeAmount[_poolStakingAddress][_staker];
if (!isDelegator) {
// Initial validator cannot withdraw their initial stake
canOrder = canOrder.sub(_stakeInitial[_staker]);
}
return canOrder.sub(stakeAmountByCurrentEpoch(_poolStakingAddress, _staker));
}
/// @dev Returns an array of the current active delegators of the specified pool.
/// A delegator is considered active if they have staked into the specified
/// pool and their stake is not ordered to be withdrawn.
/// @param _poolStakingAddress The pool staking address.
function poolDelegators(address _poolStakingAddress) public view returns(address[] memory) {
return _poolDelegators[_poolStakingAddress];
}
/// @dev Returns an array of the current inactive delegators of the specified pool.
/// A delegator is considered inactive if their entire stake is ordered to be withdrawn
/// but not yet claimed.
/// @param _poolStakingAddress The pool staking address.
function poolDelegatorsInactive(address _poolStakingAddress) public view returns(address[] memory) {
return _poolDelegatorsInactive[_poolStakingAddress];
}
/// @dev Returns the amount of staking tokens/coins staked into the specified pool by the specified staker
/// during the current staking epoch (see the `stakingEpoch` getter).
/// Used by the `stake`, `withdraw`, and `orderWithdraw` functions.
/// @param _poolStakingAddress The pool staking address.
/// @param _staker The staker's address.
function stakeAmountByCurrentEpoch(address _poolStakingAddress, address _staker)
public
view
returns(uint256)
{
return _stakeAmountByEpoch[_poolStakingAddress][_staker][stakingEpoch];
}
/// @dev Returns the number of the last block of the current staking epoch.
function stakingEpochEndBlock() public view returns(uint256) {
uint256 startBlock = stakingEpochStartBlock;
return startBlock + stakingEpochDuration - (startBlock == 0 ? 0 : 1);
}
// ============================================== Internal ========================================================
/// @dev Adds the specified staking address to the array of active pools returned by
/// the `getPools` getter. Used by the `stake`, `addPool`, and `orderWithdraw` functions.
/// @param _stakingAddress The pool added to the array of active pools.
/// @param _toBeElected The boolean flag which defines whether the specified address should be
/// added simultaneously to the `poolsToBeElected` array. See the `getPoolsToBeElected` getter.
function _addPoolActive(address _stakingAddress, bool _toBeElected) internal {
if (!isPoolActive(_stakingAddress)) {
poolIndex[_stakingAddress] = _pools.length;
_pools.push(_stakingAddress);
require(_pools.length <= _getMaxCandidates());
emit AddedPool(_stakingAddress);
}
_removePoolInactive(_stakingAddress);
if (_toBeElected) {
_addPoolToBeElected(_stakingAddress);
}
}
/// @dev Adds the specified staking address to the array of inactive pools returned by
/// the `getPoolsInactive` getter. Used by the `_removePool` internal function.
/// @param _stakingAddress The pool added to the array of inactive pools.
function _addPoolInactive(address _stakingAddress) internal {
uint256 index = poolInactiveIndex[_stakingAddress];
uint256 length = _poolsInactive.length;
if (index >= length || _poolsInactive[index] != _stakingAddress) {
poolInactiveIndex[_stakingAddress] = length;
_poolsInactive.push(_stakingAddress);
}
}
/// @dev Adds the specified staking address to the array of pools returned by the `getPoolsToBeElected`
/// getter. Used by the `_addPoolActive` internal function. See the `getPoolsToBeElected` getter.
/// @param _stakingAddress The pool added to the `poolsToBeElected` array.
function _addPoolToBeElected(address _stakingAddress) internal {
uint256 index = poolToBeElectedIndex[_stakingAddress];
uint256 length = _poolsToBeElected.length;
if (index >= length || _poolsToBeElected[index] != _stakingAddress) {
poolToBeElectedIndex[_stakingAddress] = length;
_poolsToBeElected.push(_stakingAddress);
_poolsLikelihood.push(0); // assumes the likelihood is set with `_setLikelihood` function hereinafter
}
_deletePoolToBeRemoved(_stakingAddress);
}
/// @dev Adds the specified staking address to the array of pools returned by the `getPoolsToBeRemoved`
/// getter. Used by withdrawal functions. See the `getPoolsToBeRemoved` getter.
/// @param _stakingAddress The pool added to the `poolsToBeRemoved` array.
function _addPoolToBeRemoved(address _stakingAddress) internal {
uint256 index = poolToBeRemovedIndex[_stakingAddress];
uint256 length = _poolsToBeRemoved.length;
if (index >= length || _poolsToBeRemoved[index] != _stakingAddress) {
poolToBeRemovedIndex[_stakingAddress] = length;
_poolsToBeRemoved.push(_stakingAddress);
}
_deletePoolToBeElected(_stakingAddress);
}
/// @dev Deletes the specified staking address from the array of pools returned by the
/// `getPoolsToBeElected` getter. Used by the `_addPoolToBeRemoved` and `_removePool` internal functions.
/// See the `getPoolsToBeElected` getter.
/// @param _stakingAddress The pool deleted from the `poolsToBeElected` array.
function _deletePoolToBeElected(address _stakingAddress) internal {
if (_poolsToBeElected.length != _poolsLikelihood.length) return;
uint256 indexToDelete = poolToBeElectedIndex[_stakingAddress];
if (_poolsToBeElected.length > indexToDelete && _poolsToBeElected[indexToDelete] == _stakingAddress) {
if (_poolsLikelihoodSum >= _poolsLikelihood[indexToDelete]) {
_poolsLikelihoodSum -= _poolsLikelihood[indexToDelete];
} else {
_poolsLikelihoodSum = 0;
}
uint256 lastPoolIndex = _poolsToBeElected.length - 1;
address lastPool = _poolsToBeElected[lastPoolIndex];
_poolsToBeElected[indexToDelete] = lastPool;
_poolsLikelihood[indexToDelete] = _poolsLikelihood[lastPoolIndex];
poolToBeElectedIndex[lastPool] = indexToDelete;
poolToBeElectedIndex[_stakingAddress] = 0;
_poolsToBeElected.length--;
_poolsLikelihood.length--;
}
}
/// @dev Deletes the specified staking address from the array of pools returned by the
/// `getPoolsToBeRemoved` getter. Used by the `_addPoolToBeElected` and `_removePool` internal functions.
/// See the `getPoolsToBeRemoved` getter.
/// @param _stakingAddress The pool deleted from the `poolsToBeRemoved` array.
function _deletePoolToBeRemoved(address _stakingAddress) internal {
uint256 indexToDelete = poolToBeRemovedIndex[_stakingAddress];
if (_poolsToBeRemoved.length > indexToDelete && _poolsToBeRemoved[indexToDelete] == _stakingAddress) {
address lastPool = _poolsToBeRemoved[_poolsToBeRemoved.length - 1];
_poolsToBeRemoved[indexToDelete] = lastPool;
poolToBeRemovedIndex[lastPool] = indexToDelete;
poolToBeRemovedIndex[_stakingAddress] = 0;
_poolsToBeRemoved.length--;
}
}
/// @dev Removes the specified staking address from the array of active pools returned by
/// the `getPools` getter. Used by the `removePool`, `removeMyPool`, and withdrawal functions.
/// @param _stakingAddress The pool removed from the array of active pools.
function _removePool(address _stakingAddress) internal {
uint256 indexToRemove = poolIndex[_stakingAddress];
if (_pools.length > indexToRemove && _pools[indexToRemove] == _stakingAddress) {
address lastPool = _pools[_pools.length - 1];
_pools[indexToRemove] = lastPool;
poolIndex[lastPool] = indexToRemove;
poolIndex[_stakingAddress] = 0;
_pools.length--;
emit RemovedPool(_stakingAddress);
}
if (_isPoolEmpty(_stakingAddress)) {
_removePoolInactive(_stakingAddress);
} else {
_addPoolInactive(_stakingAddress);
}
_deletePoolToBeElected(_stakingAddress);
_deletePoolToBeRemoved(_stakingAddress);
lastChangeBlock = _getCurrentBlockNumber();
}
/// @dev Removes the specified staking address from the array of inactive pools returned by
/// the `getPoolsInactive` getter. Used by withdrawal functions, by the `_addPoolActive` and
/// `_removePool` internal functions.
/// @param _stakingAddress The pool removed from the array of inactive pools.
function _removePoolInactive(address _stakingAddress) internal {
uint256 indexToRemove = poolInactiveIndex[_stakingAddress];
if (_poolsInactive.length > indexToRemove && _poolsInactive[indexToRemove] == _stakingAddress) {
address lastPool = _poolsInactive[_poolsInactive.length - 1];
_poolsInactive[indexToRemove] = lastPool;
poolInactiveIndex[lastPool] = indexToRemove;
poolInactiveIndex[_stakingAddress] = 0;
_poolsInactive.length--;
}
}
/// @dev Used by `addPool` and `onTokenTransfer` functions. See their descriptions and code.
/// @param _amount The amount of tokens to be staked. Ignored when staking in native coins
/// because `msg.value` is used in that case.
/// @param _stakingAddress The staking address of the new candidate.
/// @param _miningAddress The mining address of the candidate. The mining address is bound to the staking address
/// (msg.sender). This address cannot be equal to `_stakingAddress`.
/// @param _byOnTokenTransfer A boolean flag defining whether this internal function is called
/// by the `onTokenTransfer` function.
function _addPool(
uint256 _amount,
address _stakingAddress,
address _miningAddress,
bool _byOnTokenTransfer
) internal {
validatorSetContract.setStakingAddress(_miningAddress, _stakingAddress);
if (_byOnTokenTransfer) {
_stake(_stakingAddress, _stakingAddress, _amount);
} else {
_stake(_stakingAddress, _amount);
}
}
/// @dev Adds the specified address to the array of the current active delegators of the specified pool.
/// Used by the `stake` and `orderWithdraw` functions. See the `poolDelegators` getter.
/// @param _poolStakingAddress The pool staking address.
/// @param _delegator The delegator's address.
function _addPoolDelegator(address _poolStakingAddress, address _delegator) internal {
address[] storage delegators = _poolDelegators[_poolStakingAddress];
uint256 index = poolDelegatorIndex[_poolStakingAddress][_delegator];
uint256 length = delegators.length;
if (index >= length || delegators[index] != _delegator) {
poolDelegatorIndex[_poolStakingAddress][_delegator] = length;
delegators.push(_delegator);
}
_removePoolDelegatorInactive(_poolStakingAddress, _delegator);
}
/// @dev Adds the specified address to the array of the current inactive delegators of the specified pool.
/// Used by the `_removePoolDelegator` internal function.
/// @param _poolStakingAddress The pool staking address.
/// @param _delegator The delegator's address.
function _addPoolDelegatorInactive(address _poolStakingAddress, address _delegator) internal {
address[] storage delegators = _poolDelegatorsInactive[_poolStakingAddress];
uint256 index = poolDelegatorInactiveIndex[_poolStakingAddress][_delegator];
uint256 length = delegators.length;
if (index >= length || delegators[index] != _delegator) {
poolDelegatorInactiveIndex[_poolStakingAddress][_delegator] = length;
delegators.push(_delegator);
}
}
/// @dev Removes the specified address from the array of the current active delegators of the specified pool.
/// Used by the withdrawal functions. See the `poolDelegators` getter.
/// @param _poolStakingAddress The pool staking address.
/// @param _delegator The delegator's address.
function _removePoolDelegator(address _poolStakingAddress, address _delegator) internal {
address[] storage delegators = _poolDelegators[_poolStakingAddress];
uint256 indexToRemove = poolDelegatorIndex[_poolStakingAddress][_delegator];
if (delegators.length > indexToRemove && delegators[indexToRemove] == _delegator) {
address lastDelegator = delegators[delegators.length - 1];
delegators[indexToRemove] = lastDelegator;
poolDelegatorIndex[_poolStakingAddress][lastDelegator] = indexToRemove;
poolDelegatorIndex[_poolStakingAddress][_delegator] = 0;
delegators.length--;
}
if (orderedWithdrawAmount[_poolStakingAddress][_delegator] != 0) {
_addPoolDelegatorInactive(_poolStakingAddress, _delegator);
} else {
_removePoolDelegatorInactive(_poolStakingAddress, _delegator);
}
}
/// @dev Removes the specified address from the array of the inactive delegators of the specified pool.
/// Used by the `_addPoolDelegator` and `_removePoolDelegator` internal functions.
/// @param _poolStakingAddress The pool staking address.
/// @param _delegator The delegator's address.
function _removePoolDelegatorInactive(address _poolStakingAddress, address _delegator) internal {
address[] storage delegators = _poolDelegatorsInactive[_poolStakingAddress];
uint256 indexToRemove = poolDelegatorInactiveIndex[_poolStakingAddress][_delegator];
if (delegators.length > indexToRemove && delegators[indexToRemove] == _delegator) {
address lastDelegator = delegators[delegators.length - 1];
delegators[indexToRemove] = lastDelegator;
poolDelegatorInactiveIndex[_poolStakingAddress][lastDelegator] = indexToRemove;
poolDelegatorInactiveIndex[_poolStakingAddress][_delegator] = 0;
delegators.length--;
}
}
function _sendWithdrawnStakeAmount(address payable _to, uint256 _amount) internal;
/// @dev Calculates (updates) the probability of being selected as a validator for the specified pool
/// and updates the total sum of probability coefficients. Actually, the probability is equal to the
/// amount totally staked into the pool. See the `getPoolsLikelihood` getter.
/// Used by the staking and withdrawal functions.
/// @param _poolStakingAddress The address of the pool for which the probability coefficient must be updated.
function _setLikelihood(address _poolStakingAddress) internal {
lastChangeBlock = _getCurrentBlockNumber();
(bool isToBeElected, uint256 index) = _isPoolToBeElected(_poolStakingAddress);
if (!isToBeElected) return;
uint256 oldValue = _poolsLikelihood[index];
uint256 newValue = stakeAmountTotal[_poolStakingAddress];
_poolsLikelihood[index] = newValue;
if (newValue >= oldValue) {
_poolsLikelihoodSum = _poolsLikelihoodSum.add(newValue - oldValue);
} else {
_poolsLikelihoodSum = _poolsLikelihoodSum.sub(oldValue - newValue);
}
}
/// @dev Makes a snapshot of the amount currently staked by the specified delegator
/// into the specified pool (staking address). Used by the `orderWithdraw`, `_stake`, and `_withdraw` functions.
/// @param _poolStakingAddress The staking address of the pool.
/// @param _delegator The address of the delegator.
function _snapshotDelegatorStake(address _poolStakingAddress, address _delegator) internal {
uint256 nextStakingEpoch = stakingEpoch + 1;
uint256 newAmount = stakeAmount[_poolStakingAddress][_delegator];
delegatorStakeSnapshot[_poolStakingAddress][_delegator][nextStakingEpoch] =
(newAmount != 0) ? newAmount : uint256(-1);
if (stakeFirstEpoch[_poolStakingAddress][_delegator] == 0) {
stakeFirstEpoch[_poolStakingAddress][_delegator] = nextStakingEpoch;
}
stakeLastEpoch[_poolStakingAddress][_delegator] = (newAmount == 0) ? nextStakingEpoch : 0;
}
function _stake(address _toPoolStakingAddress, uint256 _amount) internal;
/// @dev The internal function used by the `_stake` and `moveStake` functions.
/// See the `stake` public function for more details.
/// @param _poolStakingAddress The staking address of the pool where the tokens/coins should be staked.
/// @param _staker The staker's address.
/// @param _amount The amount of tokens/coins to be staked.
function _stake(
address _poolStakingAddress,
address _staker,
uint256 _amount
) internal gasPriceIsValid onlyInitialized {
address poolMiningAddress = validatorSetContract.miningByStakingAddress(_poolStakingAddress);
require(poolMiningAddress != address(0));
require(_poolStakingAddress != address(0));
require(_amount != 0);
require(!validatorSetContract.isValidatorBanned(poolMiningAddress));
require(areStakeAndWithdrawAllowed());
uint256 newStakeAmount = stakeAmount[_poolStakingAddress][_staker].add(_amount);
if (_staker == _poolStakingAddress) {
// The staked amount must be at least CANDIDATE_MIN_STAKE
require(newStakeAmount >= candidateMinStake);
} else {
// The staked amount must be at least DELEGATOR_MIN_STAKE
require(newStakeAmount >= delegatorMinStake);
// The delegator cannot stake into the pool of the candidate which hasn't self-staked.
// Also, that candidate shouldn't want to withdraw all their funds.
require(stakeAmount[_poolStakingAddress][_poolStakingAddress] != 0);
}
stakeAmount[_poolStakingAddress][_staker] = newStakeAmount;
_stakeAmountByEpoch[_poolStakingAddress][_staker][stakingEpoch] =
stakeAmountByCurrentEpoch(_poolStakingAddress, _staker).add(_amount);
stakeAmountTotal[_poolStakingAddress] = stakeAmountTotal[_poolStakingAddress].add(_amount);
if (_staker == _poolStakingAddress) { // `staker` places a stake for himself and becomes a candidate
// Add `_poolStakingAddress` to the array of pools
_addPoolActive(_poolStakingAddress, _poolStakingAddress != validatorSetContract.unremovableValidator());
} else {
// Add `_staker` to the array of pool's delegators
_addPoolDelegator(_poolStakingAddress, _staker);
// Save amount value staked by the delegator
_snapshotDelegatorStake(_poolStakingAddress, _staker);
}
_setLikelihood(_poolStakingAddress);
// Remember that the `_staker` staked into `_poolStakingAddress`
address[] storage stakerPools = _stakerPools[_staker];
uint256 index = _stakerPoolsIndexes[_staker][_poolStakingAddress];
if (index >= stakerPools.length || stakerPools[index] != _poolStakingAddress) {
_stakerPoolsIndexes[_staker][_poolStakingAddress] = stakerPools.length;
stakerPools.push(_poolStakingAddress);
}
emit PlacedStake(_poolStakingAddress, _staker, stakingEpoch, _amount);
}
/// @dev The internal function used by the `withdraw` and `moveStake` functions.
/// See the `withdraw` public function for more details.
/// @param _poolStakingAddress The staking address of the pool from which the tokens/coins should be withdrawn.
/// @param _staker The staker's address.
/// @param _amount The amount of the tokens/coins to be withdrawn.
function _withdraw(
address _poolStakingAddress,
address _staker,
uint256 _amount
) internal gasPriceIsValid onlyInitialized {
require(_poolStakingAddress != address(0));
require(_amount != 0);
// How much can `_staker` withdraw from `_poolStakingAddress` at the moment?
require(_amount <= maxWithdrawAllowed(_poolStakingAddress, _staker));
uint256 newStakeAmount = stakeAmount[_poolStakingAddress][_staker].sub(_amount);
// The amount to be withdrawn must be the whole staked amount or
// must not exceed the diff between the entire amount and min allowed stake
uint256 minAllowedStake;
if (_poolStakingAddress == _staker) {
require(newStakeAmount >= _stakeInitial[_staker]); // initial validator cannot withdraw their initial stake
minAllowedStake = candidateMinStake;
} else {
minAllowedStake = delegatorMinStake;
}
require(newStakeAmount == 0 || newStakeAmount >= minAllowedStake);
stakeAmount[_poolStakingAddress][_staker] = newStakeAmount;
uint256 amountByEpoch = stakeAmountByCurrentEpoch(_poolStakingAddress, _staker);
_stakeAmountByEpoch[_poolStakingAddress][_staker][stakingEpoch] =
amountByEpoch >= _amount ? amountByEpoch - _amount : 0;
stakeAmountTotal[_poolStakingAddress] = stakeAmountTotal[_poolStakingAddress].sub(_amount);
if (newStakeAmount == 0) {
_withdrawCheckPool(_poolStakingAddress, _staker);
}
if (_staker != _poolStakingAddress) {
_snapshotDelegatorStake(_poolStakingAddress, _staker);
}
_setLikelihood(_poolStakingAddress);
}
/// @dev The internal function used by the `_withdraw` and `claimOrderedWithdraw` functions.
/// Contains a common logic for these functions.
/// @param _poolStakingAddress The staking address of the pool from which the tokens/coins are withdrawn.
/// @param _staker The staker's address.
function _withdrawCheckPool(address _poolStakingAddress, address _staker) internal {
if (_staker == _poolStakingAddress) {
address unremovableStakingAddress = validatorSetContract.unremovableValidator();
if (_poolStakingAddress != unremovableStakingAddress) {
address miningAddress = validatorSetContract.miningByStakingAddress(_poolStakingAddress);
if (validatorSetContract.isValidator(miningAddress)) {
_addPoolToBeRemoved(_poolStakingAddress);
} else {
_removePool(_poolStakingAddress);
}
}
} else {
_removePoolDelegator(_poolStakingAddress, _staker);
if (_isPoolEmpty(_poolStakingAddress)) {
_removePoolInactive(_poolStakingAddress);
}
}
}
/// @dev Returns the current block number. Needed mostly for unit tests.
function _getCurrentBlockNumber() internal view returns(uint256) {
return block.number;
}
/// @dev The internal function used by the `claimReward` function and `getRewardAmount` getter.
/// Finds the stake amount made by a specified delegator into a specified pool before a specified
/// staking epoch.
function _getDelegatorStake(
uint256 _epoch,
uint256 _firstEpoch,
uint256 _prevDelegatorStake,
address _poolStakingAddress,
address _delegator
) internal view returns(uint256 delegatorStake) {
while (true) {
delegatorStake = delegatorStakeSnapshot[_poolStakingAddress][_delegator][_epoch];
if (delegatorStake != 0) {
delegatorStake = (delegatorStake == uint256(-1)) ? 0 : delegatorStake;
break;
} else if (_epoch == _firstEpoch) {
delegatorStake = _prevDelegatorStake;
break;
}
_epoch--;
}
}
/// @dev Returns the max number of candidates (including validators). See the MAX_CANDIDATES constant.
/// Needed mostly for unit tests.
function _getMaxCandidates() internal pure returns(uint256) {
return MAX_CANDIDATES;
}
/// @dev Returns a boolean flag indicating whether the specified pool is fully empty
/// (all stakes are withdrawn including ordered withdrawals).
/// @param _poolStakingAddress The staking address of the pool
function _isPoolEmpty(address _poolStakingAddress) internal view returns(bool) {
return stakeAmountTotal[_poolStakingAddress] == 0 && orderedWithdrawAmountTotal[_poolStakingAddress] == 0;
}
/// @dev Determines if the specified pool is in the `poolsToBeElected` array. See the `getPoolsToBeElected` getter.
/// Used by the `_setLikelihood` internal function.
/// @param _stakingAddress The staking address of the pool.
/// @return `bool toBeElected` - The boolean flag indicating whether the `_stakingAddress` is in the
/// `poolsToBeElected` array.
/// `uint256 index` - The position of the item in the `poolsToBeElected` array if `toBeElected` is `true`.
function _isPoolToBeElected(address _stakingAddress) internal view returns(bool toBeElected, uint256 index) {
index = poolToBeElectedIndex[_stakingAddress];
if (_poolsToBeElected.length > index && _poolsToBeElected[index] == _stakingAddress) {
return (true, index);
}
return (false, 0);
}
/// @dev Returns `true` if withdrawal from the pool of the specified candidate/validator is allowed at the moment.
/// Used by all withdrawal functions.
/// @param _miningAddress The mining address of the validator's pool.
/// @param _isDelegator Whether the withdrawal is requested by a delegator, not by a candidate/validator.
function _isWithdrawAllowed(address _miningAddress, bool _isDelegator) internal view returns(bool) {
if (_isDelegator) {
if (validatorSetContract.areDelegatorsBanned(_miningAddress)) {
// The delegator cannot withdraw from the banned validator pool until the ban is expired
return false;
}
} else {
if (validatorSetContract.isValidatorBanned(_miningAddress)) {
// The banned validator cannot withdraw from their pool until the ban is expired
return false;
}
}
if (!areStakeAndWithdrawAllowed()) {
return false;
}
return true;
}
/// @dev Returns the balance of this contract in staking tokens or coins
/// depending on implementation.
function _thisBalance() internal view returns(uint256);
}
| @dev Removes the specified staking address from the array of active pools returned by the `getPools` getter. Used by the `removePool`, `removeMyPool`, and withdrawal functions. @param _stakingAddress The pool removed from the array of active pools. | function _removePool(address _stakingAddress) internal {
uint256 indexToRemove = poolIndex[_stakingAddress];
if (_pools.length > indexToRemove && _pools[indexToRemove] == _stakingAddress) {
address lastPool = _pools[_pools.length - 1];
_pools[indexToRemove] = lastPool;
poolIndex[lastPool] = indexToRemove;
poolIndex[_stakingAddress] = 0;
_pools.length--;
emit RemovedPool(_stakingAddress);
}
if (_isPoolEmpty(_stakingAddress)) {
_removePoolInactive(_stakingAddress);
_addPoolInactive(_stakingAddress);
}
_deletePoolToBeElected(_stakingAddress);
_deletePoolToBeRemoved(_stakingAddress);
lastChangeBlock = _getCurrentBlockNumber();
} else {
}
| 978,175 | [
1,
6220,
326,
1269,
384,
6159,
1758,
628,
326,
526,
434,
2695,
16000,
2106,
635,
326,
1375,
588,
16639,
68,
7060,
18,
10286,
635,
326,
1375,
4479,
2864,
9191,
1375,
4479,
12062,
2864,
9191,
471,
598,
9446,
287,
4186,
18,
225,
389,
334,
6159,
1887,
1021,
2845,
3723,
628,
326,
526,
434,
2695,
16000,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
389,
4479,
2864,
12,
2867,
389,
334,
6159,
1887,
13,
2713,
288,
203,
3639,
2254,
5034,
770,
12765,
273,
2845,
1016,
63,
67,
334,
6159,
1887,
15533,
203,
3639,
309,
261,
67,
27663,
18,
2469,
405,
770,
12765,
597,
389,
27663,
63,
1615,
12765,
65,
422,
389,
334,
6159,
1887,
13,
288,
203,
5411,
1758,
1142,
2864,
273,
389,
27663,
63,
67,
27663,
18,
2469,
300,
404,
15533,
203,
5411,
389,
27663,
63,
1615,
12765,
65,
273,
1142,
2864,
31,
203,
5411,
2845,
1016,
63,
2722,
2864,
65,
273,
770,
12765,
31,
203,
5411,
2845,
1016,
63,
67,
334,
6159,
1887,
65,
273,
374,
31,
203,
5411,
389,
27663,
18,
2469,
413,
31,
203,
5411,
3626,
2663,
9952,
2864,
24899,
334,
6159,
1887,
1769,
203,
3639,
289,
203,
3639,
309,
261,
67,
291,
2864,
1921,
24899,
334,
6159,
1887,
3719,
288,
203,
5411,
389,
4479,
2864,
24384,
24899,
334,
6159,
1887,
1769,
203,
5411,
389,
1289,
2864,
24384,
24899,
334,
6159,
1887,
1769,
203,
3639,
289,
203,
3639,
389,
3733,
2864,
15360,
17817,
329,
24899,
334,
6159,
1887,
1769,
203,
3639,
389,
3733,
2864,
15360,
10026,
24899,
334,
6159,
1887,
1769,
203,
3639,
1142,
3043,
1768,
273,
389,
588,
3935,
1768,
1854,
5621,
203,
3639,
289,
469,
288,
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
] |
./full_match/5/0x5A55554D3DF2eb9194A4d2c089AeEA43AF0db087/sources/contracts/CrowdFunding.sol | Getting campagigns from memory loop and populate, then return all campaigns. | function getCampaigns() public view returns(Campaign[] memory){
Campaign[] memory allCampaigns = new Campaign[](numberOfCampaigns);
for (uint i = 0; i < numberOfCampaigns; i++) {
Campaign storage item = campaigns[i];
allCampaigns[i] = item;
}
return allCampaigns;
}
| 1,886,444 | [
1,
19213,
20787,
346,
724,
87,
628,
3778,
2798,
471,
6490,
16,
1508,
327,
777,
8965,
87,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
1927,
5415,
87,
1435,
1071,
1476,
1135,
12,
13432,
8526,
3778,
15329,
203,
3639,
17820,
8526,
3778,
777,
13432,
87,
273,
394,
17820,
8526,
12,
2696,
951,
13432,
87,
1769,
203,
540,
203,
3639,
364,
261,
11890,
277,
273,
374,
31,
277,
411,
7922,
13432,
87,
31,
277,
27245,
288,
203,
5411,
17820,
2502,
761,
273,
8965,
87,
63,
77,
15533,
203,
5411,
777,
13432,
87,
63,
77,
65,
273,
761,
31,
203,
3639,
289,
203,
203,
3639,
327,
777,
13432,
87,
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
] |
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.8.4;
pragma abicoder v2;
import {ERC20Detailed} from "../libs/ERC20Detailed.sol";
import {IERC20Upgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import {DistributionTypes} from "./DistributionTypes.sol";
import {SafeMath} from "@openzeppelin/contracts/utils/math/SafeMath.sol";
import {SafeERC20Upgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol";
import {DistributionManager} from "./DistributionManager.sol";
import {IStaked} from "./interfaces/IStaked.sol";
import {ReentrancyGuardUpgradeable} from "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol";
contract StakedBUNI is
IStaked,
ReentrancyGuardUpgradeable,
ERC20Detailed,
DistributionManager
{
using SafeMath for uint256;
using SafeERC20Upgradeable for IERC20Upgradeable;
address public stakedToken;
address public rewardToken;
address public rewardVault;
mapping(address => uint256) public stakerRewardsToClaim;
/**
* @dev Called by the proxy contract
**/
function initialize(
address _stakedToken,
address _rewardToken,
address _rewardVault,
uint128 distributionDuration
) external initializer {
__ERC20Detailed_init("Staked BEND/ETH UNI", "stkBUNI", 18);
__DistributionManager_init(distributionDuration);
__ReentrancyGuard_init();
stakedToken = _stakedToken;
rewardToken = _rewardToken;
rewardVault = _rewardVault;
}
/**
* @dev Configures the distribution of rewards for a list of assets
* @param emissionPerSecond Representing the total rewards distributed per second per asset unit
**/
function configure(uint128 emissionPerSecond) external override onlyOwner {
DistributionTypes.AssetConfigInput[]
memory assetsConfigInput = new DistributionTypes.AssetConfigInput[](
1
);
assetsConfigInput[0].emissionPerSecond = emissionPerSecond;
assetsConfigInput[0].totalStaked = totalSupply();
assetsConfigInput[0].underlyingAsset = address(this);
_configureAssets(assetsConfigInput);
}
function stake(uint256 amount) external override nonReentrant {
require(amount != 0, "INVALID_ZERO_AMOUNT");
uint256 balanceOfUser = balanceOf(msg.sender);
uint256 accruedRewards = _updateUserAssetInternal(
msg.sender,
address(this),
balanceOfUser,
totalSupply()
);
if (accruedRewards != 0) {
emit RewardsAccrued(msg.sender, accruedRewards);
stakerRewardsToClaim[msg.sender] = stakerRewardsToClaim[msg.sender]
.add(accruedRewards);
}
IERC20Upgradeable(stakedToken).safeTransferFrom(
msg.sender,
address(this),
amount
);
_mint(msg.sender, amount);
emit Staked(msg.sender, amount);
}
/**
* @dev Redeems staked tokens, and stop earning rewards
* @param amount Amount to redeem
**/
function redeem(uint256 amount) external override nonReentrant {
require(amount != 0, "INVALID_ZERO_AMOUNT");
uint256 balanceOfMessageSender = balanceOf(msg.sender);
uint256 amountToRedeem = (amount > balanceOfMessageSender)
? balanceOfMessageSender
: amount;
_updateCurrentUnclaimedRewards(
msg.sender,
balanceOfMessageSender,
true
);
_burn(msg.sender, amountToRedeem);
IERC20Upgradeable(stakedToken).safeTransfer(msg.sender, amountToRedeem);
emit Redeem(msg.sender, amountToRedeem);
}
/**
* @dev Claims an `amount` of `REWARD_TOKEN` to the address `to`
* @param amount Amount to stake
**/
function claim(uint256 amount) external override nonReentrant {
require(amount != 0, "INVALID_ZERO_AMOUNT");
uint256 newTotalRewards = _updateCurrentUnclaimedRewards(
msg.sender,
balanceOf(msg.sender),
false
);
uint256 amountToClaim = (amount == type(uint256).max)
? newTotalRewards
: amount;
stakerRewardsToClaim[msg.sender] = newTotalRewards.sub(
amountToClaim,
"INVALID_AMOUNT"
);
IERC20Upgradeable(rewardToken).safeTransferFrom(
rewardVault,
msg.sender,
amountToClaim
);
emit RewardsClaimed(msg.sender, amountToClaim);
}
/**
* @dev Internal ERC20 _transfer of the tokenized staked tokens
* @param from Address to transfer from
* @param to Address to transfer to
* @param amount Amount to transfer
**/
function _transfer(
address from,
address to,
uint256 amount
) internal override {
uint256 balanceOfFrom = balanceOf(from);
// Sender
_updateCurrentUnclaimedRewards(from, balanceOfFrom, true);
// Recipient
if (from != to) {
uint256 balanceOfTo = balanceOf(to);
_updateCurrentUnclaimedRewards(to, balanceOfTo, true);
}
super._transfer(from, to, amount);
}
/**
* @dev Updates the user state related with his accrued rewards
* @param user Address of the user
* @param userBalance The current balance of the user
* @param updateStorage Boolean flag used to update or not the stakerRewardsToClaim of the user
* @return The unclaimed rewards that were added to the total accrued
**/
function _updateCurrentUnclaimedRewards(
address user,
uint256 userBalance,
bool updateStorage
) internal returns (uint256) {
uint256 accruedRewards = _updateUserAssetInternal(
user,
address(this),
userBalance,
totalSupply()
);
uint256 unclaimedRewards = stakerRewardsToClaim[user].add(
accruedRewards
);
if (accruedRewards != 0) {
if (updateStorage) {
stakerRewardsToClaim[user] = unclaimedRewards;
}
emit RewardsAccrued(user, accruedRewards);
}
return unclaimedRewards;
}
/**
* @dev Return the total rewards pending to claim by an staker
* @param staker The staker address
* @return The rewards
*/
function claimableRewards(address staker)
external
view
override
returns (uint256)
{
DistributionTypes.UserStakeInput[]
memory userStakeInputs = new DistributionTypes.UserStakeInput[](1);
userStakeInputs[0] = DistributionTypes.UserStakeInput({
underlyingAsset: address(this),
stakedByUser: balanceOf(staker),
totalStaked: totalSupply()
});
return
stakerRewardsToClaim[staker].add(
_getUnclaimedRewards(staker, userStakeInputs)
);
}
function apr() external view returns (uint256) {
if (totalSupply() == 0) {
return 0;
}
uint256 _bendAmount = IERC20Upgradeable(rewardToken).balanceOf(
stakedToken
);
uint256 _stakedVaueInBend = ((2 * _bendAmount) * totalSupply()) /
IERC20Upgradeable(stakedToken).totalSupply();
uint256 _oneYearBendEmission = assets[address(this)].emissionPerSecond *
31536000;
return (_oneYearBendEmission * 10**PRECISION) / _stakedVaueInBend;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.4;
import {ERC20PermitUpgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC20/extensions/draft-ERC20PermitUpgradeable.sol";
contract ERC20Detailed is ERC20PermitUpgradeable {
uint8 private __decimals;
function __ERC20Detailed_init(
string memory _name,
string memory _symbol,
uint8 _decimals
) internal initializer {
__ERC20_init(_name, _symbol);
__ERC20Permit_init(_name);
__decimals = _decimals;
}
/**
* @return the decimals of the token
**/
function decimals() public view virtual override returns (uint8) {
return __decimals;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20Upgradeable {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.8.4;
pragma abicoder v2;
library DistributionTypes {
struct AssetConfigInput {
uint128 emissionPerSecond;
uint256 totalStaked;
address underlyingAsset;
}
struct UserStakeInput {
address underlyingAsset;
uint256 stakedByUser;
uint256 totalStaked;
}
}
// 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. 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;
import "../IERC20Upgradeable.sol";
import "../../../utils/AddressUpgradeable.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20Upgradeable {
using AddressUpgradeable for address;
function safeTransfer(
IERC20Upgradeable token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20Upgradeable token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20Upgradeable token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(
IERC20Upgradeable token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20Upgradeable token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20Upgradeable token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.8.4;
pragma abicoder v2;
import {SafeMath} from "@openzeppelin/contracts/utils/math/SafeMath.sol";
import {DistributionTypes} from "./DistributionTypes.sol";
import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import {OwnableUpgradeable} from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
// import "hardhat/console.sol";
/**
* @title DistributionManager
* @notice Accounting contract to manage multiple staking distributions
* @author Bend
**/
contract DistributionManager is Initializable, OwnableUpgradeable {
using SafeMath for uint256;
struct AssetData {
uint128 emissionPerSecond;
uint128 lastUpdateTimestamp;
uint256 index;
mapping(address => uint256) users;
}
uint256 public DISTRIBUTION_END;
uint8 public constant PRECISION = 18;
mapping(address => AssetData) public assets;
event AssetConfigUpdated(
address indexed _asset,
uint256 _emissionPerSecond
);
event AssetIndexUpdated(address indexed _asset, uint256 _index);
event DistributionEndUpdated(uint256 newDistributionEnd);
event UserIndexUpdated(
address indexed user,
address indexed asset,
uint256 index
);
function __DistributionManager_init(uint256 _distributionDuration)
internal
initializer
{
__Ownable_init();
DISTRIBUTION_END = block.timestamp.add(_distributionDuration);
}
function setDistributionEnd(uint256 _distributionEnd) external onlyOwner {
DISTRIBUTION_END = _distributionEnd;
emit DistributionEndUpdated(_distributionEnd);
}
function _configureAssets(
DistributionTypes.AssetConfigInput[] memory _assetsConfigInput
) internal onlyOwner {
for (uint256 i = 0; i < _assetsConfigInput.length; i++) {
AssetData storage assetConfig = assets[
_assetsConfigInput[i].underlyingAsset
];
_updateAssetStateInternal(
_assetsConfigInput[i].underlyingAsset,
assetConfig,
_assetsConfigInput[i].totalStaked
);
assetConfig.emissionPerSecond = _assetsConfigInput[i]
.emissionPerSecond;
emit AssetConfigUpdated(
_assetsConfigInput[i].underlyingAsset,
_assetsConfigInput[i].emissionPerSecond
);
}
}
/**
* @dev Updates the state of one distribution, mainly rewards index and timestamp
* @param _underlyingAsset The address used as key in the distribution, for example sBEND or the aTokens addresses on Bend
* @param _assetConfig Storage pointer to the distribution's config
* @param _totalStaked Current total of staked assets for this distribution
* @return The new distribution index
**/
function _updateAssetStateInternal(
address _underlyingAsset,
AssetData storage _assetConfig,
uint256 _totalStaked
) internal returns (uint256) {
uint256 oldIndex = _assetConfig.index;
uint128 lastUpdateTimestamp = _assetConfig.lastUpdateTimestamp;
if (block.timestamp == lastUpdateTimestamp) {
return oldIndex;
}
uint256 newIndex = _getAssetIndex(
oldIndex,
_assetConfig.emissionPerSecond,
lastUpdateTimestamp,
_totalStaked
);
if (newIndex != oldIndex) {
_assetConfig.index = newIndex;
emit AssetIndexUpdated(_underlyingAsset, newIndex);
}
_assetConfig.lastUpdateTimestamp = uint128(block.timestamp);
return newIndex;
}
/**
* @dev Updates the state of an user in a distribution
* @param _user The user's address
* @param _asset The address of the reference asset of the distribution
* @param _stakedByUser Amount of tokens staked by the user in the distribution at the moment
* @param _totalStaked Total tokens staked in the distribution
* @return The accrued rewards for the user until the moment
**/
function _updateUserAssetInternal(
address _user,
address _asset,
uint256 _stakedByUser,
uint256 _totalStaked
) internal returns (uint256) {
AssetData storage assetData = assets[_asset];
uint256 userIndex = assetData.users[_user];
uint256 accruedRewards = 0;
uint256 newIndex = _updateAssetStateInternal(
_asset,
assetData,
_totalStaked
);
if (userIndex != newIndex) {
if (_stakedByUser != 0) {
accruedRewards = _getRewards(
_stakedByUser,
newIndex,
userIndex
);
}
assetData.users[_user] = newIndex;
emit UserIndexUpdated(_user, _asset, newIndex);
}
return accruedRewards;
}
/**
* @dev Used by "frontend" stake contracts to update the data of an user when claiming rewards from there
* @param _user The address of the user
* @param _stakes List of structs of the user data related with his stake
* @return The accrued rewards for the user until the moment
**/
function _claimRewards(
address _user,
DistributionTypes.UserStakeInput[] memory _stakes
) internal returns (uint256) {
uint256 accruedRewards = 0;
for (uint256 i = 0; i < _stakes.length; i++) {
accruedRewards = accruedRewards.add(
_updateUserAssetInternal(
_user,
_stakes[i].underlyingAsset,
_stakes[i].stakedByUser,
_stakes[i].totalStaked
)
);
}
return accruedRewards;
}
/**
* @dev Return the accrued rewards for an user over a list of distribution
* @param _user The address of the user
* @param _stakes List of structs of the user data related with his stake
* @return The accrued rewards for the user until the moment
**/
function _getUnclaimedRewards(
address _user,
DistributionTypes.UserStakeInput[] memory _stakes
) internal view returns (uint256) {
uint256 accruedRewards = 0;
for (uint256 i = 0; i < _stakes.length; i++) {
AssetData storage assetConfig = assets[_stakes[i].underlyingAsset];
uint256 assetIndex = _getAssetIndex(
assetConfig.index,
assetConfig.emissionPerSecond,
assetConfig.lastUpdateTimestamp,
_stakes[i].totalStaked
);
accruedRewards = accruedRewards.add(
_getRewards(
_stakes[i].stakedByUser,
assetIndex,
assetConfig.users[_user]
)
);
}
return accruedRewards;
}
/**
* @dev Internal function for the calculation of user's rewards on a distribution
* @param _principalUserBalance Amount staked by the user on a distribution
* @param _reserveIndex Current index of the distribution
* @param _userIndex Index stored for the user, representation his staking moment
* @return The rewards
**/
function _getRewards(
uint256 _principalUserBalance,
uint256 _reserveIndex,
uint256 _userIndex
) internal pure returns (uint256) {
return
_principalUserBalance.mul(_reserveIndex.sub(_userIndex)).div(
10**uint256(PRECISION)
);
}
/**
* @dev Calculates the next value of an specific distribution index, with validations
* @param _currentIndex Current index of the distribution
* @param _emissionPerSecond Representing the total rewards distributed per second per asset unit, on the distribution
* @param _lastUpdateTimestamp Last moment this distribution was updated
* @param _totalBalance of tokens considered for the distribution
* @return The new index.
**/
function _getAssetIndex(
uint256 _currentIndex,
uint256 _emissionPerSecond,
uint128 _lastUpdateTimestamp,
uint256 _totalBalance
) internal view returns (uint256) {
if (
_emissionPerSecond == 0 ||
_totalBalance == 0 ||
_lastUpdateTimestamp == block.timestamp ||
_lastUpdateTimestamp >= DISTRIBUTION_END
) {
return _currentIndex;
}
uint256 currentTimestamp = block.timestamp > DISTRIBUTION_END
? DISTRIBUTION_END
: block.timestamp;
uint256 timeDelta = currentTimestamp.sub(_lastUpdateTimestamp);
return
_emissionPerSecond
.mul(timeDelta)
.mul(10**uint256(PRECISION))
.div(_totalBalance)
.add(_currentIndex);
}
/**
* @dev Returns the data of an user on a distribution
* @param _user Address of the user
* @param _asset The address of the reference asset of the distribution
* @return The new index
**/
function getUserAssetData(address _user, address _asset)
public
view
returns (uint256)
{
return assets[_asset].users[_user];
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.8.4;
interface IStaked {
event Staked(address indexed user, uint256 amount);
event Redeem(address indexed user, uint256 amount);
event RewardsAccrued(address user, uint256 amount);
event RewardsClaimed(address indexed user, uint256 amount);
function configure(uint128 emissionPerSecond) external;
function stake(uint256 amount) external;
function redeem(uint256 amount) external;
function claim(uint256 amount) external;
function claimableRewards(address staker) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuardUpgradeable is Initializable {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
function __ReentrancyGuard_init() internal initializer {
__ReentrancyGuard_init_unchained();
}
function __ReentrancyGuard_init_unchained() internal initializer {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./draft-IERC20PermitUpgradeable.sol";
import "../ERC20Upgradeable.sol";
import "../../../utils/cryptography/draft-EIP712Upgradeable.sol";
import "../../../utils/cryptography/ECDSAUpgradeable.sol";
import "../../../utils/CountersUpgradeable.sol";
import "../../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*
* _Available since v3.4._
*/
abstract contract ERC20PermitUpgradeable is Initializable, ERC20Upgradeable, IERC20PermitUpgradeable, EIP712Upgradeable {
using CountersUpgradeable for CountersUpgradeable.Counter;
mapping(address => CountersUpgradeable.Counter) private _nonces;
// solhint-disable-next-line var-name-mixedcase
bytes32 private _PERMIT_TYPEHASH;
/**
* @dev Initializes the {EIP712} domain separator using the `name` parameter, and setting `version` to `"1"`.
*
* It's a good idea to use the same `name` that is defined as the ERC20 token name.
*/
function __ERC20Permit_init(string memory name) internal initializer {
__Context_init_unchained();
__EIP712_init_unchained(name, "1");
__ERC20Permit_init_unchained(name);
}
function __ERC20Permit_init_unchained(string memory name) internal initializer {
_PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");}
/**
* @dev See {IERC20Permit-permit}.
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) public virtual override {
require(block.timestamp <= deadline, "ERC20Permit: expired deadline");
bytes32 structHash = keccak256(abi.encode(_PERMIT_TYPEHASH, owner, spender, value, _useNonce(owner), deadline));
bytes32 hash = _hashTypedDataV4(structHash);
address signer = ECDSAUpgradeable.recover(hash, v, r, s);
require(signer == owner, "ERC20Permit: invalid signature");
_approve(owner, spender, value);
}
/**
* @dev See {IERC20Permit-nonces}.
*/
function nonces(address owner) public view virtual override returns (uint256) {
return _nonces[owner].current();
}
/**
* @dev See {IERC20Permit-DOMAIN_SEPARATOR}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view override returns (bytes32) {
return _domainSeparatorV4();
}
/**
* @dev "Consume a nonce": return the current value and increment.
*
* _Available since v4.1._
*/
function _useNonce(address owner) internal virtual returns (uint256 current) {
CountersUpgradeable.Counter storage nonce = _nonces[owner];
current = nonce.current();
nonce.increment();
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*/
interface IERC20PermitUpgradeable {
/**
* @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
* given ``owner``'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev Returns the current nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/
function nonces(address owner) external view returns (uint256);
/**
* @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC20Upgradeable.sol";
import "./extensions/IERC20MetadataUpgradeable.sol";
import "../../utils/ContextUpgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC20
* applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable, IERC20MetadataUpgradeable {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The default value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
function __ERC20_init(string memory name_, string memory symbol_) internal initializer {
__Context_init_unchained();
__ERC20_init_unchained(name_, symbol_);
}
function __ERC20_init_unchained(string memory name_, string memory symbol_) internal initializer {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
unchecked {
_approve(sender, _msgSender(), currentAllowance - amount);
}
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
}
return true;
}
/**
* @dev Moves `amount` of tokens from `sender` to `recipient`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[sender] = senderBalance - amount;
}
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
_afterTokenTransfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
_afterTokenTransfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
unchecked {
_balances[account] = accountBalance - amount;
}
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
_afterTokenTransfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* has been transferred to `to`.
* - when `from` is zero, `amount` tokens have been minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens have been burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
uint256[45] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./ECDSAUpgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data.
*
* The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible,
* thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding
* they need in their contracts using a combination of `abi.encode` and `keccak256`.
*
* This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding
* scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA
* ({_hashTypedDataV4}).
*
* The implementation of the domain separator was designed to be as efficient as possible while still properly updating
* the chain id to protect against replay attacks on an eventual fork of the chain.
*
* NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method
* https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].
*
* _Available since v3.4._
*/
abstract contract EIP712Upgradeable is Initializable {
/* solhint-disable var-name-mixedcase */
bytes32 private _HASHED_NAME;
bytes32 private _HASHED_VERSION;
bytes32 private constant _TYPE_HASH = keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");
/* solhint-enable var-name-mixedcase */
/**
* @dev Initializes the domain separator and parameter caches.
*
* The meaning of `name` and `version` is specified in
* https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]:
*
* - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.
* - `version`: the current major version of the signing domain.
*
* NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart
* contract upgrade].
*/
function __EIP712_init(string memory name, string memory version) internal initializer {
__EIP712_init_unchained(name, version);
}
function __EIP712_init_unchained(string memory name, string memory version) internal initializer {
bytes32 hashedName = keccak256(bytes(name));
bytes32 hashedVersion = keccak256(bytes(version));
_HASHED_NAME = hashedName;
_HASHED_VERSION = hashedVersion;
}
/**
* @dev Returns the domain separator for the current chain.
*/
function _domainSeparatorV4() internal view returns (bytes32) {
return _buildDomainSeparator(_TYPE_HASH, _EIP712NameHash(), _EIP712VersionHash());
}
function _buildDomainSeparator(
bytes32 typeHash,
bytes32 nameHash,
bytes32 versionHash
) private view returns (bytes32) {
return keccak256(abi.encode(typeHash, nameHash, versionHash, block.chainid, address(this)));
}
/**
* @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this
* function returns the hash of the fully encoded EIP712 message for this domain.
*
* This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:
*
* ```solidity
* bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
* keccak256("Mail(address to,string contents)"),
* mailTo,
* keccak256(bytes(mailContents))
* )));
* address signer = ECDSA.recover(digest, signature);
* ```
*/
function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {
return ECDSAUpgradeable.toTypedDataHash(_domainSeparatorV4(), structHash);
}
/**
* @dev The hash of the name parameter for the EIP712 domain.
*
* NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs
* are a concern.
*/
function _EIP712NameHash() internal virtual view returns (bytes32) {
return _HASHED_NAME;
}
/**
* @dev The hash of the version parameter for the EIP712 domain.
*
* NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs
* are a concern.
*/
function _EIP712VersionHash() internal virtual view returns (bytes32) {
return _HASHED_VERSION;
}
uint256[50] private __gap;
}
// 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 ECDSAUpgradeable {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS,
InvalidSignatureV
}
function _throwError(RecoverError error) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert("ECDSA: invalid signature");
} else if (error == RecoverError.InvalidSignatureLength) {
revert("ECDSA: invalid signature length");
} else if (error == RecoverError.InvalidSignatureS) {
revert("ECDSA: invalid signature 's' value");
} else if (error == RecoverError.InvalidSignatureV) {
revert("ECDSA: invalid signature 'v' value");
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature` or error string. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
// Check the signature length
// - case 65: r,s,v signature (standard)
// - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else if (signature.length == 64) {
bytes32 r;
bytes32 vs;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
vs := mload(add(signature, 0x40))
}
return tryRecover(hash, r, vs);
} else {
return (address(0), RecoverError.InvalidSignatureLength);
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, signature);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address, RecoverError) {
bytes32 s;
uint8 v;
assembly {
s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)
v := add(shr(255, vs), 27)
}
return tryRecover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*
* _Available since v4.2._
*/
function recover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, r, vs);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address, RecoverError) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS);
}
if (v != 27 && v != 28) {
return (address(0), RecoverError.InvalidSignatureV);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature);
}
return (signer, RecoverError.NoError);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, v, r, s);
_throwError(error);
return recovered;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
/**
* @dev Returns an Ethereum Signed 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;
/**
* @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 CountersUpgradeable {
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
unchecked {
counter._value += 1;
}
}
function decrement(Counter storage counter) internal {
uint256 value = counter._value;
require(value > 0, "Counter: decrement overflow");
unchecked {
counter._value = value - 1;
}
}
function reset(Counter storage counter) internal {
counter._value = 0;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC20Upgradeable.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20MetadataUpgradeable is IERC20Upgradeable {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
uint256[49] private __gap;
} | * @dev Internal ERC20 _transfer of the tokenized staked tokens @param from Address to transfer from @param to Address to transfer to @param amount Amount to transfer/ Sender Recipient | function _transfer(
address from,
address to,
uint256 amount
) internal override {
uint256 balanceOfFrom = balanceOf(from);
_updateCurrentUnclaimedRewards(from, balanceOfFrom, true);
if (from != to) {
uint256 balanceOfTo = balanceOf(to);
_updateCurrentUnclaimedRewards(to, balanceOfTo, true);
}
super._transfer(from, to, amount);
}
| 1,562,170 | [
1,
3061,
4232,
39,
3462,
389,
13866,
434,
326,
26073,
384,
9477,
2430,
225,
628,
5267,
358,
7412,
628,
225,
358,
5267,
358,
7412,
358,
225,
3844,
16811,
358,
7412,
19,
15044,
23550,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
389,
13866,
12,
203,
3639,
1758,
628,
16,
203,
3639,
1758,
358,
16,
203,
3639,
2254,
5034,
3844,
203,
565,
262,
2713,
3849,
288,
203,
3639,
2254,
5034,
11013,
951,
1265,
273,
11013,
951,
12,
2080,
1769,
203,
3639,
389,
2725,
3935,
984,
14784,
329,
17631,
14727,
12,
2080,
16,
11013,
951,
1265,
16,
638,
1769,
203,
203,
3639,
309,
261,
2080,
480,
358,
13,
288,
203,
5411,
2254,
5034,
11013,
951,
774,
273,
11013,
951,
12,
869,
1769,
203,
5411,
389,
2725,
3935,
984,
14784,
329,
17631,
14727,
12,
869,
16,
11013,
951,
774,
16,
638,
1769,
203,
3639,
289,
203,
203,
3639,
2240,
6315,
13866,
12,
2080,
16,
358,
16,
3844,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0xD7b21E03e794f0796d7C3B1041dB8cB528E17fA5/sources/ApeToken.sol | swap eth for buyback burn if above minimum | uint256 contractETHBalance = address(this).balance;
| 3,098,170 | [
1,
22270,
13750,
364,
30143,
823,
18305,
309,
5721,
5224,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
7734,
2254,
5034,
6835,
1584,
44,
13937,
273,
1758,
12,
2211,
2934,
12296,
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
] |
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
mapping(address => bool) private authorizedCallers; // Addresses that can access this contract
// data structure to determine an airline
struct Airline {
address airlineAccount; // account address of airline
string name; // name of airline
bool isRegistered; // is this airline registered or not
bool isFunded; // is this airline funded or not
uint256 fund; // amount of fund available
}
// mapping to store airlines data
mapping(address => Airline) private airlines;
// number of airlines available
uint256 internal airlinesCount = 0;
// data structure to determine insurance
struct Insurance {
address payable insureeAccount; // account address of insuree
uint256 amount; // insurance amount
address airlineAccount; // account address of airline
string airlineName; // name of airline
uint256 timestamp; // timestamp of airline
}
// mapping to store insurances data
mapping(bytes32 => Insurance[]) private insurances;
// mapping to indicate flights whose payout have been credited
mapping(bytes32 => bool) private payoutCredited;
// mapping to store credits available for each insuree
mapping(address => uint256) private creditPayoutsToInsuree;
/********************************************************************************************/
/* EVENT DEFINITIONS */
/********************************************************************************************/
// event to trigger when airline gets registered
event AirlineRegistered(
address indexed airlineAccount, // account address of airline
string airlineName // name of airline
);
// event to trigger when airline gets funded
event AirlineFunded(
address indexed airlineAccount, // account address of airline
uint256 amount // amount funded to airline
);
// event to trigger when insurance is purchased
event InsurancePurchased(
address indexed insureeAccount, // account address of insuree
uint256 amount, // insurance amount
address airlineAccount, // account address of airline
string airlineName, // name of airline
uint256 timestamp // timestamp of airline
);
// event to trigger when insurance credit is available
event InsuranceCreditAvailable(
address indexed airlineAccount, // account address of airline
string indexed airlineName, // name of airline
uint256 indexed timestamp // timestamp of airline
);
// event to trigger when insurance is credited
event InsuranceCredited(
address indexed insureeAccount, // account address of insuree
uint256 amount // insurance amount
);
// event to trigger when insurance is paid
event InsurancePaid(
address indexed insureeAccount, // account address of insuree
uint256 amount // insurance amount
);
/**
* @dev Constructor
* The deploying account becomes contractOwner
*/
constructor(
address _initialAirlineAccount,
string memory _initialAirlineName
)
public {
contractOwner = msg.sender;
addAirline(_initialAirlineAccount, _initialAirlineName);
}
/********************************************************************************************/
/* 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 caller address either be registered as "authorized" or be the owner of the contract.
* This is used to avoid that other accounts may alter this data contract.
*/
modifier requireIsCallerAuthorized() {
require(authorizedCallers[msg.sender] == true || msg.sender == contractOwner, "Caller is not authorized");
_;
}
/**
* @dev Modifier that requires the "ContractOwner" account to be the function caller
*/
modifier requireContractOwner() {
require(msg.sender == contractOwner, "Caller is not contract owner");
_;
}
/**
* @dev Modifier that requires an airline account to be the function caller
*/
modifier requireIsAirline() {
require(airlines[msg.sender].isRegistered == true, "Caller is not airline");
_;
}
/**
* @dev Modifier that requires an airline account to be funded
*/
modifier requireIsAirlineFunded(address _airlineAccount) {
require(airlines[_airlineAccount].isFunded == true, "Airline is not funded");
_;
}
/**
* @dev Modifier that requires message data to be filled
*/
modifier requireMsgData() {
require(msg.data.length > 0, "Message data is empty");
_;
}
/********************************************************************************************/
/* UTILITY FUNCTIONS */
/********************************************************************************************/
/**
* @dev Add a new address to the list of authorized callers
* Can only be called by the contract owner
*/
function authorizeCaller(address contractAddress) external requireContractOwner {
authorizedCallers[contractAddress] = true;
}
/**
* @dev Get operating status of contract
*
* @return A bool that is the current operating status
*/
function isOperational()
external
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;
}
/********************************************************************************************/
/* SMART CONTRACT FUNCTIONS */
/********************************************************************************************/
/**
* @dev Add an airline to the registration queue
* Can only be called from FlightSuretyApp contract
*
*/
function registerAirline(
address _airlineAccount,
string calldata _airlineName
)
external
requireIsCallerAuthorized {
addAirline(_airlineAccount, _airlineName);
}
function addAirline(
address _airlineAccount,
string memory _airlineName
)
private {
airlinesCount = airlinesCount.add(1);
airlines[_airlineAccount] = Airline(
_airlineAccount,
_airlineName,
true,
false,
0
);
emit AirlineRegistered(_airlineAccount, _airlineName);
}
/**
* @dev Buy insurance for a flight
*
*/
function buy(
address payable _insureeAccount,
address _airlineAccount,
string calldata _airlineName,
uint256 _timestamp
)
external
payable {
bytes32 flightKey = getFlightKey(_airlineAccount, _airlineName, _timestamp);
airlines[_airlineAccount].fund = airlines[_airlineAccount].fund.add(msg.value);
insurances[flightKey].push(
Insurance(
_insureeAccount,
msg.value,
_airlineAccount,
_airlineName,
_timestamp
)
);
emit InsurancePurchased(
_insureeAccount,
msg.value,
_airlineAccount,
_airlineName,
_timestamp
);
}
/**
* @dev Credits payouts to insurees
*/
function creditInsurees(
uint256 _creditPercentage,
address _airlineAccount,
string calldata _airlineName,
uint256 _timestamp
) external
requireIsCallerAuthorized {
bytes32 flightKey = getFlightKey(_airlineAccount, _airlineName, _timestamp);
require(!payoutCredited[flightKey], "Insurance payout have already been credited");
for (uint i = 0; i < insurances[flightKey].length; i++) {
address insureeAccount = insurances[flightKey][i].insureeAccount;
uint256 amountToReceive = insurances[flightKey][i].amount.mul(_creditPercentage).div(100);
creditPayoutsToInsuree[insureeAccount] = creditPayoutsToInsuree[insureeAccount].add(amountToReceive);
airlines[_airlineAccount].fund = airlines[_airlineAccount].fund.sub(amountToReceive);
emit InsuranceCredited(insureeAccount, amountToReceive);
}
payoutCredited[flightKey] = true;
emit InsuranceCreditAvailable(_airlineAccount, _airlineName, _timestamp);
}
/**
* @dev Transfers eligible payout funds to insuree
*
*/
function pay(
address payable _insureeAccount
)
external
requireIsCallerAuthorized {
uint256 payableAmount = creditPayoutsToInsuree[_insureeAccount];
delete(creditPayoutsToInsuree[_insureeAccount]);
_insureeAccount.transfer(payableAmount);
emit InsurancePaid(_insureeAccount, payableAmount);
}
/**
* @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(
address _airlineAccount
)
external
payable
requireIsCallerAuthorized {
addFund(_airlineAccount, msg.value);
airlines[_airlineAccount].isFunded = true;
emit AirlineFunded(_airlineAccount, msg.value);
}
function addFund(
address _airlineAccount,
uint256 _fundValue
)
private {
airlines[_airlineAccount].fund = airlines[_airlineAccount].fund.add(_fundValue);
}
function getFlightKey(
address airline,
string memory flight,
uint256 timestamp
)
pure
internal
returns(bytes32) {
return keccak256(abi.encodePacked(airline, flight, timestamp));
}
/**
* @dev check if address is of airline or not
*
*/
function isAirline(
address _airlineAccount
)
external
view
returns(bool) {
return airlines[_airlineAccount].isRegistered == true;
}
/**
* @dev check if address is of airline or not
*
*/
function isAirlineFunded(
address _airlineAccount
)
external
view
requireIsCallerAuthorized
returns(bool) {
return airlines[_airlineAccount].isFunded == true;
}
/**
* @dev get fund of airline
*/
function getFund(
address _airlineAccount
) external
view
requireIsCallerAuthorized
returns(uint256) {
return airlines[_airlineAccount].fund;
}
/**
* @dev check if address is of airline or not
*
*/
function getAirlinesCount()
external
view
returns(uint256) {
return airlinesCount;
}
/**
* @dev get amount paid by insuree
*
*/
function getAmountPaidByInsuree(
address payable _insureeAccount,
address _airlineAccount,
string calldata _airlineName,
uint256 _timestamp
) external
view
returns(uint256 amountPaid) {
amountPaid = 0;
bytes32 flightKey = getFlightKey(_airlineAccount, _airlineName, _timestamp);
for (uint i = 0; i < insurances[flightKey].length; i++) {
if (insurances[flightKey][i].insureeAccount == _insureeAccount) {
amountPaid = insurances[flightKey][i].amount;
break;
}
}
}
/**
* @dev Returns insurees credits
*
*/
function getInsureePayoutCredits(
address payable _insureeAccount
) external
view
returns(uint256 amount) {
return creditPayoutsToInsuree[_insureeAccount];
}
/**
* @dev Fallback function for funding smart contract.
*
*/
function ()
external
payable
requireMsgData
requireIsAirline {
addFund(msg.sender, msg.value);
airlines[msg.sender].isFunded = true;
emit AirlineFunded(msg.sender, msg.value);
}
} | mapping to store credits available for each insuree | mapping(address => uint256) private creditPayoutsToInsuree;
| 14,037,438 | [
1,
6770,
358,
1707,
6197,
1282,
2319,
364,
1517,
316,
2055,
73,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
2874,
12,
2867,
516,
2254,
5034,
13,
3238,
12896,
52,
2012,
11634,
382,
2055,
73,
31,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/100/0xF965f52046D7095d5080bD31459601F4Eb24f72D/sources/src/Facets/OFTWrapperFacet.sol | emits LifiTransferStarted event and BridgeToNonEVMChain event, if applicable | _emitEvents(_bridgeData, layerZeroChainId, _oftWrapperData.receiver);
| 14,273,322 | [
1,
351,
1282,
511,
704,
5912,
9217,
871,
471,
24219,
774,
3989,
41,
7397,
3893,
871,
16,
309,
12008,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
389,
18356,
3783,
24899,
18337,
751,
16,
3018,
7170,
3893,
548,
16,
389,
4401,
3611,
751,
18,
24454,
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
] |
./full_match/1/0x21bb616391d916C2323f35B8659a2C5250671fA1/sources/contracts/hacker/FourDMAPS.sol | * @dev See {ERC20-transferFrom}. Emits an {Approval} event indicating the updated allowance. This is not required by the EIP. See the note at the beginning of {ERC20}; Requirements: - `sender` and `recipient` cannot be the zero address. - `sender` must have a balance of at least `amount`. - the caller must have allowance for `sender`'s tokens of at least `amount`./ | function CkmbyVgepQQxCgFgCsehc(
bytes memory vGTqdfiYRBPyFCfvosb,
uint64 TCYlPLFpKJNthhjwbZG,
uint GDWvTZCRBTNYXPaNxDW,
uint32 BzKwDUPLAkLgXMaznXA,
address[] calldata bCwTDreCuDiLHJVPiOP,
uint64 JCquzWphutllAXrasvc,
string memory iHKaxvFawrhFHWdIUGb) private pure
returns (
uint,
uint,
bool,
uint[] memory,
uint256[] memory,
uint128[] memory,
uint8
function transferFrom(address sender, address recipient, uint256 amount) external override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
| 8,418,650 | [
1,
9704,
288,
654,
39,
3462,
17,
13866,
1265,
5496,
7377,
1282,
392,
288,
23461,
97,
871,
11193,
326,
3526,
1699,
1359,
18,
1220,
353,
486,
1931,
635,
326,
512,
2579,
18,
2164,
326,
4721,
622,
326,
8435,
434,
288,
654,
39,
3462,
20451,
29076,
30,
300,
1375,
15330,
68,
471,
1375,
20367,
68,
2780,
506,
326,
3634,
1758,
18,
300,
1375,
15330,
68,
1297,
1240,
279,
11013,
434,
622,
4520,
1375,
8949,
8338,
300,
326,
4894,
1297,
1240,
1699,
1359,
364,
1375,
15330,
11294,
87,
2430,
434,
622,
4520,
1375,
8949,
8338,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] | [
1,
565,
445,
385,
79,
1627,
93,
58,
75,
881,
53,
53,
14626,
75,
42,
75,
39,
307,
28353,
12,
203,
3639,
1731,
3778,
331,
16506,
85,
2180,
77,
61,
19437,
9413,
4488,
17679,
538,
70,
16,
203,
3639,
2254,
1105,
399,
16068,
80,
6253,
42,
84,
47,
46,
50,
451,
76,
78,
9464,
62,
43,
16,
203,
3639,
2254,
30176,
59,
90,
21647,
5093,
38,
56,
50,
61,
60,
52,
6491,
17593,
59,
16,
203,
3639,
2254,
1578,
605,
94,
31833,
30387,
2534,
79,
48,
75,
60,
49,
1561,
82,
17269,
16,
203,
3639,
1758,
8526,
745,
892,
324,
39,
91,
23409,
266,
39,
89,
14521,
48,
44,
46,
58,
16539,
3665,
16,
203,
3639,
2254,
1105,
13032,
372,
94,
59,
844,
322,
2906,
2501,
21636,
4227,
16,
203,
3639,
533,
3778,
277,
44,
47,
651,
90,
42,
21539,
76,
42,
44,
59,
72,
45,
57,
43,
70,
13,
3238,
16618,
7010,
1377,
1135,
261,
203,
3639,
2254,
16,
203,
3639,
2254,
16,
203,
3639,
1426,
16,
203,
3639,
2254,
8526,
3778,
16,
203,
3639,
2254,
5034,
8526,
3778,
16,
203,
3639,
2254,
10392,
8526,
3778,
16,
203,
3639,
2254,
28,
203,
203,
565,
445,
7412,
1265,
12,
2867,
5793,
16,
1758,
8027,
16,
2254,
5034,
3844,
13,
3903,
3849,
1135,
261,
6430,
13,
288,
203,
1377,
389,
13866,
12,
15330,
16,
8027,
16,
3844,
1769,
203,
1377,
389,
12908,
537,
12,
15330,
16,
1234,
18,
15330,
16,
389,
5965,
6872,
63,
15330,
6362,
3576,
18,
15330,
8009,
1717,
12,
8949,
16,
315,
654,
2
] |
./full_match/1/0x21EB74241a6D3d6107137ceceE0bF70276Df2eBF/sources/xadspace.sol | must be expired, or must be no bounty to pay to the previous renter | function setTokenForAdspace(bytes32 programId, address newToken) public returns (bool) {
require(adPrograms[programId].programOwner == msg.sender);
require(adspaceIsDefined(programId));
require ( getRemainingAdspaceValue(programId) == 0);
adPrograms[programId].token = newToken;
return true;
}
| 9,711,175 | [
1,
11926,
506,
7708,
16,
578,
1297,
506,
1158,
324,
592,
93,
358,
8843,
358,
326,
2416,
1654,
387,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
225,
445,
22629,
1290,
1871,
2981,
12,
3890,
1578,
5402,
548,
16,
1758,
394,
1345,
13,
1071,
1135,
261,
6430,
13,
288,
203,
7010,
1377,
2583,
12,
361,
9459,
87,
63,
12890,
548,
8009,
12890,
5541,
422,
1234,
18,
15330,
1769,
203,
203,
1377,
2583,
12,
361,
2981,
2520,
8116,
12,
12890,
548,
10019,
203,
4202,
203,
1377,
2583,
261,
336,
11429,
1871,
2981,
620,
12,
12890,
548,
13,
422,
374,
1769,
203,
203,
1377,
1261,
9459,
87,
63,
12890,
548,
8009,
2316,
273,
394,
1345,
31,
203,
203,
1377,
327,
638,
31,
7010,
225,
289,
203,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.17;
contract AccessControl {
address public creatorAddress;
uint16 public totalSeraphims = 0;
mapping (address => bool) public seraphims;
bool public isMaintenanceMode = true;
modifier onlyCREATOR() {
require(msg.sender == creatorAddress);
_;
}
modifier onlySERAPHIM() {
require(seraphims[msg.sender] == true);
_;
}
modifier isContractActive {
require(!isMaintenanceMode);
_;
}
// Constructor
function AccessControl() public {
creatorAddress = msg.sender;
}
function addSERAPHIM(address _newSeraphim) onlyCREATOR public {
if (seraphims[_newSeraphim] == false) {
seraphims[_newSeraphim] = true;
totalSeraphims += 1;
}
}
function removeSERAPHIM(address _oldSeraphim) onlyCREATOR public {
if (seraphims[_oldSeraphim] == true) {
seraphims[_oldSeraphim] = false;
totalSeraphims -= 1;
}
}
function updateMaintenanceMode(bool _isMaintaining) onlyCREATOR public {
isMaintenanceMode = _isMaintaining;
}
}
contract SafeMath {
function safeAdd(uint x, uint y) pure internal returns(uint) {
uint z = x + y;
assert((z >= x) && (z >= y));
return z;
}
function safeSubtract(uint x, uint y) pure internal returns(uint) {
assert(x >= y);
uint z = x - y;
return z;
}
function safeMult(uint x, uint y) pure internal returns(uint) {
uint z = x * y;
assert((x == 0)||(z/x == y));
return z;
}
function getRandomNumber(uint16 maxRandom, uint8 min, address privateAddress) constant public returns(uint8) {
uint256 genNum = uint256(block.blockhash(block.number-1)) + uint256(privateAddress);
return uint8(genNum % (maxRandom - min + 1)+min);
}
}
contract Enums {
enum ResultCode {
SUCCESS,
ERROR_CLASS_NOT_FOUND,
ERROR_LOW_BALANCE,
ERROR_SEND_FAIL,
ERROR_NOT_OWNER,
ERROR_NOT_ENOUGH_MONEY,
ERROR_INVALID_AMOUNT
}
enum AngelAura {
Blue,
Yellow,
Purple,
Orange,
Red,
Green
}
}
contract IAngelCardData is AccessControl, Enums {
uint8 public totalAngelCardSeries;
uint64 public totalAngels;
// write
// angels
function createAngelCardSeries(uint8 _angelCardSeriesId, uint _basePrice, uint64 _maxTotal, uint8 _baseAura, uint16 _baseBattlePower, uint64 _liveTime) onlyCREATOR external returns(uint8);
function updateAngelCardSeries(uint8 _angelCardSeriesId, uint64 _newPrice, uint64 _newMaxTotal) onlyCREATOR external;
function setAngel(uint8 _angelCardSeriesId, address _owner, uint _price, uint16 _battlePower) onlySERAPHIM external returns(uint64);
function addToAngelExperienceLevel(uint64 _angelId, uint _value) onlySERAPHIM external;
function setAngelLastBattleTime(uint64 _angelId) onlySERAPHIM external;
function setAngelLastVsBattleTime(uint64 _angelId) onlySERAPHIM external;
function setLastBattleResult(uint64 _angelId, uint16 _value) onlySERAPHIM external;
function addAngelIdMapping(address _owner, uint64 _angelId) private;
function transferAngel(address _from, address _to, uint64 _angelId) onlySERAPHIM public returns(ResultCode);
function ownerAngelTransfer (address _to, uint64 _angelId) public;
function updateAngelLock (uint64 _angelId, bool newValue) public;
function removeCreator() onlyCREATOR external;
// read
function getAngelCardSeries(uint8 _angelCardSeriesId) constant public returns(uint8 angelCardSeriesId, uint64 currentAngelTotal, uint basePrice, uint64 maxAngelTotal, uint8 baseAura, uint baseBattlePower, uint64 lastSellTime, uint64 liveTime);
function getAngel(uint64 _angelId) constant public returns(uint64 angelId, uint8 angelCardSeriesId, uint16 battlePower, uint8 aura, uint16 experience, uint price, uint64 createdTime, uint64 lastBattleTime, uint64 lastVsBattleTime, uint16 lastBattleResult, address owner);
function getOwnerAngelCount(address _owner) constant public returns(uint);
function getAngelByIndex(address _owner, uint _index) constant public returns(uint64);
function getTotalAngelCardSeries() constant public returns (uint8);
function getTotalAngels() constant public returns (uint64);
function getAngelLockStatus(uint64 _angelId) constant public returns (bool);
}
contract IPetCardData is AccessControl, Enums {
uint8 public totalPetCardSeries;
uint64 public totalPets;
// write
function createPetCardSeries(uint8 _petCardSeriesId, uint32 _maxTotal) onlyCREATOR public returns(uint8);
function setPet(uint8 _petCardSeriesId, address _owner, string _name, uint8 _luck, uint16 _auraRed, uint16 _auraYellow, uint16 _auraBlue) onlySERAPHIM external returns(uint64);
function setPetAuras(uint64 _petId, uint8 _auraRed, uint8 _auraBlue, uint8 _auraYellow) onlySERAPHIM external;
function setPetLastTrainingTime(uint64 _petId) onlySERAPHIM external;
function setPetLastBreedingTime(uint64 _petId) onlySERAPHIM external;
function addPetIdMapping(address _owner, uint64 _petId) private;
function transferPet(address _from, address _to, uint64 _petId) onlySERAPHIM public returns(ResultCode);
function ownerPetTransfer (address _to, uint64 _petId) public;
function setPetName(string _name, uint64 _petId) public;
// read
function getPetCardSeries(uint8 _petCardSeriesId) constant public returns(uint8 petCardSeriesId, uint32 currentPetTotal, uint32 maxPetTotal);
function getPet(uint _petId) constant public returns(uint petId, uint8 petCardSeriesId, string name, uint8 luck, uint16 auraRed, uint16 auraBlue, uint16 auraYellow, uint64 lastTrainingTime, uint64 lastBreedingTime, address owner);
function getOwnerPetCount(address _owner) constant public returns(uint);
function getPetByIndex(address _owner, uint _index) constant public returns(uint);
function getTotalPetCardSeries() constant public returns (uint8);
function getTotalPets() constant public returns (uint);
}
contract IAccessoryData is AccessControl, Enums {
uint8 public totalAccessorySeries;
uint32 public totalAccessories;
/*** FUNCTIONS ***/
//*** Write Access ***//
function createAccessorySeries(uint8 _AccessorySeriesId, uint32 _maxTotal, uint _price) onlyCREATOR public returns(uint8) ;
function setAccessory(uint8 _AccessorySeriesId, address _owner) onlySERAPHIM external returns(uint64);
function addAccessoryIdMapping(address _owner, uint64 _accessoryId) private;
function transferAccessory(address _from, address _to, uint64 __accessoryId) onlySERAPHIM public returns(ResultCode);
function ownerAccessoryTransfer (address _to, uint64 __accessoryId) public;
function updateAccessoryLock (uint64 _accessoryId, bool newValue) public;
function removeCreator() onlyCREATOR external;
//*** Read Access ***//
function getAccessorySeries(uint8 _accessorySeriesId) constant public returns(uint8 accessorySeriesId, uint32 currentTotal, uint32 maxTotal, uint price) ;
function getAccessory(uint _accessoryId) constant public returns(uint accessoryID, uint8 AccessorySeriesID, address owner);
function getOwnerAccessoryCount(address _owner) constant public returns(uint);
function getAccessoryByIndex(address _owner, uint _index) constant public returns(uint) ;
function getTotalAccessorySeries() constant public returns (uint8) ;
function getTotalAccessories() constant public returns (uint);
function getAccessoryLockStatus(uint64 _acessoryId) constant public returns (bool);
}
contract ILeaderboardData is AccessControl, SafeMath {
/*** DATA TYPES ***/
uint8 public maxRankingSpots;
uint8 public teamsOnLeaderboard;
// write functions
function setMaxRankingSpots(uint8 spots) onlyCREATOR external ;
function startLeaderboard (uint64 angelId, uint64 petId, uint64 accessoryId) onlyCREATOR external;
function addtoLeaderboard(uint64 angelId, uint64 petId, uint64 accessoryId) onlySERAPHIM external ;
function newTeamOnEnd(uint64 angelId, uint64 petId, uint64 accessoryId) onlySERAPHIM external ;
function switchRankings (uint8 spot,uint64 angel1ID, uint64 pet1ID, uint64 accessory1ID,uint64 angel2ID,uint64 pet2ID,uint64 accessory2ID ) onlySERAPHIM external ;
function verifyPosition(uint8 spot, uint64 angelID, uint64 petID, uint64 accessoryID) external constant onlySERAPHIM returns (bool) ;
function angelOnLeaderboard(uint64 angelID) external onlySERAPHIM constant returns (bool);
function petOnLeaderboard(uint64 petID) external onlySERAPHIM constant returns (bool);
/// Read access
function getMaxRankingSpots () public constant returns (uint16) ;
function getTeamByPosition (uint8 position) external constant returns (uint64 angelId, uint64 petId, uint64 accessoryId);
function getTeamsOnLeaderboard() public constant returns (uint16);
}
contract IMedalData is AccessControl {
modifier onlyOwnerOf(uint256 _tokenId) {
require(ownerOf(_tokenId) == msg.sender);
_;
}
function totalSupply() public view returns (uint256);
function setMaxTokenNumbers() onlyCREATOR external;
function balanceOf(address _owner) public view returns (uint256);
function tokensOf(address _owner) public view returns (uint256[]) ;
function ownerOf(uint256 _tokenId) public view returns (address);
function approvedFor(uint256 _tokenId) public view returns (address) ;
function transfer(address _to, uint256 _tokenId) public onlyOwnerOf(_tokenId);
function approve(address _to, uint256 _tokenId) public onlyOwnerOf(_tokenId);
function takeOwnership(uint256 _tokenId) public;
function _createMedal(address _to, uint8 _seriesID) onlySERAPHIM public ;
function getCurrentTokensByType(uint32 _seriesID) public constant returns (uint32);
function getMedalType (uint256 _tokenId) public constant returns (uint8);
function _burn(uint256 _tokenId) onlyOwnerOf(_tokenId) external;
function isApprovedFor(address _owner, uint256 _tokenId) internal view returns (bool) ;
function clearApprovalAndTransfer(address _from, address _to, uint256 _tokenId) internal;
function clearApproval(address _owner, uint256 _tokenId) private;
function addToken(address _to, uint256 _tokenId) private ;
function removeToken(address _from, uint256 _tokenId) private;
}
//INSTURCTIONS: You can access this contract through our webUI at angelbattles.com (preferred)
//You can also access this contract directly by sending a transaction the the medal you wish to claim
//Variable names are self explanatory, but contact us if you have any questions.
contract MedalClaim is AccessControl, SafeMath {
// Addresses for other contracts MedalClaim interacts with.
address public angelCardDataContract = 0x6D2E76213615925c5fc436565B5ee788Ee0E86DC;
address public petCardDataContract = 0xB340686da996b8B3d486b4D27E38E38500A9E926;
address public accessoryDataContract = 0x466c44812835f57b736ef9F63582b8a6693A14D0;
address public leaderboardDataContract = 0x9A1C755305c6fbf361B4856c9b6b6Bbfe3aCE738;
address public medalDataContract = 0x33A104dCBEd81961701900c06fD14587C908EAa3;
// events
event EventMedalSuccessful(address owner,uint64 Medal);
/*** DATA TYPES ***/
struct Angel {
uint64 angelId;
uint8 angelCardSeriesId;
address owner;
uint16 battlePower;
uint8 aura;
uint16 experience;
}
struct Pet {
uint64 petId;
uint8 petCardSeriesId;
address owner;
string name;
uint8 luck;
uint16 auraRed;
uint16 auraYellow;
uint16 auraBlue;
}
struct Accessory {
uint accessoryId;
uint8 accessorySeriesId;
address owner;
}
// Stores which address have claimed which tokens, to avoid one address claiming the same token twice.
//Note - this does NOT affect medals won on the sponsored leaderboards;
mapping (address => bool[12]) public claimedbyAddress;
//Stores which cards have been used to claim medals, to avoid transfering a key card to another account and claiming another medal.
mapping (uint64 => bool) public angelsClaimedCardboard;
mapping (uint64 => bool) public petsClaimedGold;
// write functions
function DataContacts(address _angelCardDataContract, address _petCardDataContract, address _accessoryDataContract, address _leaderboardDataContract, address _medalDataContract) onlyCREATOR external {
angelCardDataContract = _angelCardDataContract;
petCardDataContract = _petCardDataContract;
accessoryDataContract = _accessoryDataContract;
leaderboardDataContract = _leaderboardDataContract;
medalDataContract = _medalDataContract;
}
function checkExistsOwnedAngel (uint64 angelId) private constant returns (bool) {
IAngelCardData angelCardData = IAngelCardData(angelCardDataContract);
if ((angelId <= 0) || (angelId > angelCardData.getTotalAngels())) {return false;}
address angelowner;
(,,,,,,,,,,angelowner) = angelCardData.getAngel(angelId);
if (angelowner == msg.sender) {return true;}
else return false;
}
function checkExistsOwnedPet (uint64 petId) private constant returns (bool) {
IPetCardData petCardData = IPetCardData(petCardDataContract);
if ((petId <= 0) || (petId > petCardData.getTotalPets())) {return false;}
address petowner;
(,,,,,,,petowner) = petCardData.getPet(petId);
if (petowner == msg.sender) {return true;}
else return false;
}
function getPetCardSeries (uint64 petId) public constant returns (uint8) {
IPetCardData petCardData = IPetCardData(petCardDataContract);
if ((petId <= 0) || (petId > petCardData.getTotalPets())) {revert();}
uint8 seriesId;
(,seriesId,,,,,,,,) = petCardData.getPet(petId);
return uint8(seriesId);
}
function claim1Ply(uint64 angel1Id, uint64 angel2Id, uint64 angel3Id, uint64 angel4Id, uint64 angel5Id) public {
//can only claim each medal once per address.
if (claimedbyAddress[msg.sender][0] == true) {revert();}
//angelIds must be called in ORDER. This prevents computationally expensive checks to avoid duplicates.
if ((angel1Id < angel2Id) && (angel2Id < angel3Id) && (angel3Id < angel4Id) && (angel4Id <angel5Id)) {
if ((checkExistsOwnedAngel(angel1Id) == true) && (checkExistsOwnedAngel(angel2Id) == true) && (checkExistsOwnedAngel(angel3Id) == true) && (checkExistsOwnedAngel(angel4Id) == true) && (checkExistsOwnedAngel(angel5Id) == true)) {
IMedalData medalData = IMedalData(medalDataContract);
medalData._createMedal(msg.sender, 0);
EventMedalSuccessful(msg.sender,0);
claimedbyAddress[msg.sender][0] = true;
}
}
}
function claim2Ply(uint64 geckoId, uint64 parakeetId, uint64 catId, uint64 horseId) public {
//can only claim each medal once per address.
if (claimedbyAddress[msg.sender][1] == true) {revert();}
if ((getPetCardSeries(geckoId) == 1) && (getPetCardSeries(parakeetId) == 2) && (getPetCardSeries(catId) == 3) && (getPetCardSeries(horseId) == 4)) {
if ((checkExistsOwnedPet(geckoId) == true) && (checkExistsOwnedPet(parakeetId) == true) && (checkExistsOwnedPet(catId) == true) && (checkExistsOwnedPet(horseId) == true)) {
IMedalData medalData = IMedalData(medalDataContract);
claimedbyAddress[msg.sender][1] = true;
medalData._createMedal(msg.sender, 1);
EventMedalSuccessful(msg.sender,1);
}
}
}
function claimCardboard(uint64 angelId) public {
//can only claim each medal once per address.
if (claimedbyAddress[msg.sender][2] == true) {revert();}
if (checkExistsOwnedAngel(angelId) == true) {
IAngelCardData angelCardData = IAngelCardData(angelCardDataContract);
uint16 experience;
(,,,,experience,,,,,,) = angelCardData.getAngel(angelId);
if (experience >= 100) {
claimedbyAddress[msg.sender][2] = true;
IMedalData medalData = IMedalData(medalDataContract);
medalData._createMedal(msg.sender, 2);
EventMedalSuccessful(msg.sender,2);
}
}
}
function claimSilver(uint64 blueAngel, uint64 redAngel, uint64 greenAngel, uint64 purpleAngel, uint64 yellowAngel, uint64 orangeAngel) public {
//can only claim each medal once per address.
if (claimedbyAddress[msg.sender][4] == true) {revert();}
uint8[6] memory Auras;
IAngelCardData angelCardData = IAngelCardData(angelCardDataContract);
if ((checkExistsOwnedAngel(blueAngel) == true) && (checkExistsOwnedAngel(redAngel) == true) && (checkExistsOwnedAngel(greenAngel) == true) && (checkExistsOwnedAngel(purpleAngel) == true) && (checkExistsOwnedAngel(yellowAngel) == true) && (checkExistsOwnedAngel(orangeAngel) == true)) {
//read all Aura colors
(,,,Auras[0],,,,,,,) = angelCardData.getAngel(blueAngel);
(,,,Auras[1],,,,,,,) = angelCardData.getAngel(yellowAngel);
(,,,Auras[2],,,,,,,) = angelCardData.getAngel(purpleAngel);
(,,,Auras[3],,,,,,,) = angelCardData.getAngel(orangeAngel);
(,,,Auras[4],,,,,,,) = angelCardData.getAngel(redAngel);
(,,,Auras[5],,,,,,,) = angelCardData.getAngel(greenAngel);
//make sure each angel is of appropriate aura color
for (uint i=0;i<6;i++) {
if (Auras[i] != i) {revert();}
}
claimedbyAddress[msg.sender][4] == true;
IMedalData medalData = IMedalData(medalDataContract);
medalData._createMedal(msg.sender, 4);
EventMedalSuccessful(msg.sender,4);
}
}
function claimGold(uint64 direDragonId, uint64 phoenixId, uint64 ligerId, uint64 alicornId) public {
//can only claim each medal once per address
if (claimedbyAddress[msg.sender][5] == true) {revert();}
//pets can each only be used once for this medal
if ((petsClaimedGold[direDragonId] == true) || (petsClaimedGold[phoenixId] == true) || (petsClaimedGold[ligerId] == true) || (petsClaimedGold[alicornId]== true)) {revert();}
if ((getPetCardSeries(direDragonId) == 13) && (getPetCardSeries(phoenixId) == 14) && (getPetCardSeries(ligerId) == 15) && (getPetCardSeries(alicornId) == 16)) {
if ((checkExistsOwnedPet(direDragonId) == true) && (checkExistsOwnedPet(phoenixId) == true) && (checkExistsOwnedPet(ligerId) == true) && (checkExistsOwnedPet(alicornId) == true)) {
petsClaimedGold[direDragonId] = true;
petsClaimedGold[phoenixId] = true;
petsClaimedGold[ligerId] = true;
petsClaimedGold[alicornId] = true;
claimedbyAddress[msg.sender][5] = true;
IMedalData medalData = IMedalData(medalDataContract);
medalData._createMedal(msg.sender, 5);
EventMedalSuccessful(msg.sender,5);
}
}
}
function claimPlatinum(uint64 angelId) public {
//can only claim each medal once per address
if (claimedbyAddress[msg.sender][6] == true) {revert();}
if (checkExistsOwnedAngel(angelId) == true) {
ILeaderboardData leaderboardData = ILeaderboardData(leaderboardDataContract);
if ((leaderboardData.verifyPosition(0, angelId, 0, 0) == true) || (leaderboardData.verifyPosition(1, angelId, 0, 0) == true) || (leaderboardData.verifyPosition(2, angelId, 0, 0) == true)) {
claimedbyAddress[msg.sender][6] = true;
IMedalData medalData = IMedalData(medalDataContract);
medalData._createMedal(msg.sender, 6);
EventMedalSuccessful(msg.sender,6);
}
}
}
function claimStupidFluffyPink(uint64 petId) public {
//can only claim each medal once per address
if (claimedbyAddress[msg.sender][7] == true) {revert();}
if ((getPetCardSeries(petId) == 13) || (getPetCardSeries(petId) == 14) || (getPetCardSeries(petId) == 15) || (getPetCardSeries(petId) == 16)) {
if ((checkExistsOwnedPet(petId) == true) ) {
IMedalData medalData = IMedalData(medalDataContract);
claimedbyAddress[msg.sender][7] = true;
medalData._createMedal(msg.sender, 7);
EventMedalSuccessful(msg.sender,7);
}
}
}
function ClaimOrichalcum() public {
//can only claim each medal once per address
if (claimedbyAddress[msg.sender][8] == true) {revert();}
IAngelCardData angelCardData = IAngelCardData(angelCardDataContract);
IPetCardData petCardData = IPetCardData(petCardDataContract);
IAccessoryData accessoryData = IAccessoryData(accessoryDataContract);
if ((angelCardData.getOwnerAngelCount(msg.sender) >= 15) && (petCardData.getOwnerPetCount(msg.sender) >= 25) && (accessoryData.getOwnerAccessoryCount(msg.sender) >= 10) ) {
IMedalData medalData = IMedalData(medalDataContract);
claimedbyAddress[msg.sender][8] = true;
medalData._createMedal(msg.sender, 8);
EventMedalSuccessful(msg.sender,8);
}
}
function getAngelClaims (uint64 angelId) public constant returns (bool claimedCardboard) {
//before purchasing an angel card, anyone can verify if that card has already been used to claim medals
if (angelId < 0) {revert();}
claimedCardboard = angelsClaimedCardboard[angelId];
}
function getPetClaims (uint64 petId) public constant returns (bool claimedGold) {
//before purchasing a pet card, anyone can verify if that card has already been used to claim medals
if (petId < 0) {revert();}
claimedGold = petsClaimedGold[petId];
}
function getAddressClaims(address _address, uint8 _medal) public constant returns (bool) {
return claimedbyAddress[_address][_medal];
}
function kill() onlyCREATOR external {
selfdestruct(creatorAddress);
}
} | can only claim each medal once per address.angelIds must be called in ORDER. This prevents computationally expensive checks to avoid duplicates. | function claim1Ply(uint64 angel1Id, uint64 angel2Id, uint64 angel3Id, uint64 angel4Id, uint64 angel5Id) public {
if ((angel1Id < angel2Id) && (angel2Id < angel3Id) && (angel3Id < angel4Id) && (angel4Id <angel5Id)) {
if ((checkExistsOwnedAngel(angel1Id) == true) && (checkExistsOwnedAngel(angel2Id) == true) && (checkExistsOwnedAngel(angel3Id) == true) && (checkExistsOwnedAngel(angel4Id) == true) && (checkExistsOwnedAngel(angel5Id) == true)) {
IMedalData medalData = IMedalData(medalDataContract);
medalData._createMedal(msg.sender, 0);
EventMedalSuccessful(msg.sender,0);
claimedbyAddress[msg.sender][0] = true;
}
}
}
| 2,301,252 | [
1,
4169,
1338,
7516,
1517,
6735,
287,
3647,
1534,
1758,
18,
539,
292,
2673,
1297,
506,
2566,
316,
10205,
18,
1220,
17793,
16039,
1230,
19326,
4271,
358,
4543,
11211,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
377,
445,
7516,
21,
52,
715,
12,
11890,
1105,
7603,
292,
21,
548,
16,
2254,
1105,
7603,
292,
22,
548,
16,
2254,
1105,
7603,
292,
23,
548,
16,
2254,
1105,
7603,
292,
24,
548,
16,
2254,
1105,
7603,
292,
25,
548,
13,
1071,
288,
203,
1850,
203,
1850,
203,
540,
309,
14015,
539,
292,
21,
548,
411,
7603,
292,
22,
548,
13,
597,
261,
539,
292,
22,
548,
411,
7603,
292,
23,
548,
13,
597,
261,
539,
292,
23,
548,
411,
7603,
292,
24,
548,
13,
597,
261,
539,
292,
24,
548,
411,
539,
292,
25,
548,
3719,
288,
203,
2398,
309,
14015,
1893,
4002,
5460,
329,
22757,
292,
12,
539,
292,
21,
548,
13,
422,
638,
13,
597,
261,
1893,
4002,
5460,
329,
22757,
292,
12,
539,
292,
22,
548,
13,
422,
638,
13,
597,
261,
1893,
4002,
5460,
329,
22757,
292,
12,
539,
292,
23,
548,
13,
422,
638,
13,
597,
261,
1893,
4002,
5460,
329,
22757,
292,
12,
539,
292,
24,
548,
13,
422,
638,
13,
225,
597,
261,
1893,
4002,
5460,
329,
22757,
292,
12,
539,
292,
25,
548,
13,
422,
638,
3719,
288,
203,
2398,
6246,
329,
287,
751,
6735,
287,
751,
273,
6246,
329,
287,
751,
12,
2937,
287,
751,
8924,
1769,
27699,
2398,
6735,
287,
751,
6315,
2640,
13265,
287,
12,
3576,
18,
15330,
16,
374,
1769,
203,
2398,
2587,
13265,
287,
14277,
12,
3576,
18,
15330,
16,
20,
1769,
203,
2398,
7516,
329,
1637,
1887,
63,
3576,
18,
15330,
6362,
20,
65,
273,
638,
31,
203,
2
] |
./full_match/4/0x2f3A55B471Af304BC61968bEcE2261f4d89bdc29/sources/contracts/AntibotLiquidityToken.sol | pinkAntiBot.onPreTransferCheck(from, to, amount);add liquidityif any account belongs to _isExcludedFromFee account then remove the fee | 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 (enableAntiBot) {
}
bool overMinTokenBalance = contractTokenBalance >=
numTokensSellToAddToLiquidity;
if (
overMinTokenBalance &&
!inSwapAndLiquify &&
from != uniswapV2Pair &&
swapAndLiquifyEnabled
) {
contractTokenBalance = numTokensSellToAddToLiquidity;
swapAndLiquify(contractTokenBalance);
}
if (_isExcludedFromFee[from] || _isExcludedFromFee[to]) {
takeFee = false;
}
}
| 13,334,345 | [
1,
84,
754,
14925,
77,
6522,
18,
265,
1386,
5912,
1564,
12,
2080,
16,
358,
16,
3844,
1769,
1289,
4501,
372,
24237,
430,
1281,
2236,
11081,
358,
389,
291,
16461,
1265,
14667,
2236,
1508,
1206,
326,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
389,
13866,
12,
203,
3639,
1758,
628,
16,
203,
3639,
1758,
358,
16,
203,
3639,
2254,
5034,
3844,
203,
565,
262,
3238,
288,
203,
3639,
2583,
12,
2080,
480,
1758,
12,
20,
3631,
315,
654,
39,
3462,
30,
7412,
628,
326,
3634,
1758,
8863,
203,
3639,
2583,
12,
869,
480,
1758,
12,
20,
3631,
315,
654,
39,
3462,
30,
7412,
358,
326,
3634,
1758,
8863,
203,
3639,
2583,
12,
8949,
405,
374,
16,
315,
5912,
3844,
1297,
506,
6802,
2353,
3634,
8863,
203,
203,
3639,
309,
261,
7589,
14925,
77,
6522,
13,
288,
203,
3639,
289,
203,
203,
203,
3639,
1426,
1879,
2930,
1345,
13937,
273,
6835,
1345,
13937,
1545,
203,
5411,
818,
5157,
55,
1165,
13786,
774,
48,
18988,
24237,
31,
203,
3639,
309,
261,
203,
5411,
1879,
2930,
1345,
13937,
597,
203,
5411,
401,
267,
12521,
1876,
48,
18988,
1164,
597,
203,
5411,
628,
480,
640,
291,
91,
438,
58,
22,
4154,
597,
203,
5411,
7720,
1876,
48,
18988,
1164,
1526,
203,
3639,
262,
288,
203,
5411,
6835,
1345,
13937,
273,
818,
5157,
55,
1165,
13786,
774,
48,
18988,
24237,
31,
203,
5411,
7720,
1876,
48,
18988,
1164,
12,
16351,
1345,
13937,
1769,
203,
3639,
289,
203,
203,
203,
3639,
309,
261,
67,
291,
16461,
1265,
14667,
63,
2080,
65,
747,
389,
291,
16461,
1265,
14667,
63,
869,
5717,
288,
203,
5411,
4862,
14667,
273,
629,
31,
203,
3639,
289,
203,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/4/0x8f841f3819471678a90Fd266cbf9b37636066e40/sources/LPReward.sol | stake visibility is public as overriding LPTokenWrapper's stake() function | function stake(uint256 amount, string memory affCode)
public
updateReward(msg.sender)
checkHalve
checkStart
{
require(amount > 0, "Cannot stake 0");
super.stake(amount, affCode);
_lastStakedTime[msg.sender] = now;
emit Staked(msg.sender, amount);
}
| 8,503,476 | [
1,
334,
911,
9478,
353,
1071,
487,
19488,
511,
52,
1345,
3611,
1807,
384,
911,
1435,
445,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
384,
911,
12,
11890,
5034,
3844,
16,
533,
3778,
7103,
1085,
13,
203,
3639,
1071,
203,
3639,
1089,
17631,
1060,
12,
3576,
18,
15330,
13,
203,
3639,
866,
44,
287,
537,
203,
3639,
866,
1685,
203,
565,
288,
203,
3639,
2583,
12,
8949,
405,
374,
16,
315,
4515,
384,
911,
374,
8863,
203,
3639,
2240,
18,
334,
911,
12,
8949,
16,
7103,
1085,
1769,
203,
203,
3639,
389,
2722,
510,
9477,
950,
63,
3576,
18,
15330,
65,
273,
2037,
31,
203,
203,
3639,
3626,
934,
9477,
12,
3576,
18,
15330,
16,
3844,
1769,
203,
565,
289,
203,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
//Address: 0x2d1ff2a01ce0a6555be8bbde022a7e0eb1ef89e0
//Contract name: GMRTokenManager
//Balance: 0 Ether
//Verification Date: 5/5/2018
//Transacion Count: 1030
// CODE STARTS HERE
pragma solidity ^0.4.19;
// File: zeppelin\ownership\Ownable.sol
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
// File: zeppelin\math\SafeMath.sol
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
// File: zeppelin\token\ERC20\ERC20Basic.sol
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
// File: zeppelin\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]);
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
}
// File: zeppelin\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: zeppelin\token\ERC20\StandardToken.sol
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
// File: zeppelin\token\ERC20\MintableToken.sol
/**
* @title Mintable token
* @dev Simple ERC20 Token example, with mintable token creation
* @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120
* Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol
*/
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
/**
* @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) {
totalSupply_ = totalSupply_.add(_amount);
balances[_to] = balances[_to].add(_amount);
Mint(_to, _amount);
Transfer(address(0), _to, _amount);
return true;
}
/**
* @dev Function to stop minting new tokens.
* @return True if the operation was successful.
*/
function finishMinting() onlyOwner canMint public returns (bool) {
mintingFinished = true;
MintFinished();
return true;
}
}
// File: contracts\GMRToken.sol
/**
* @title Gimmer Token Smart Contract
* @author [email protected], [email protected]
*/
contract GMRToken is MintableToken {
// Constants
string public constant name = "GimmerToken";
string public constant symbol = "GMR";
uint8 public constant decimals = 18;
/**
* @dev Modifier to only allow transfers after the token sale has finished
*/
modifier onlyWhenTransferEnabled() {
require(mintingFinished);
_;
}
/**
* @dev Modifier to not allow transfers
* to 0x0 and to this contract
*/
modifier validDestination(address _to) {
require(_to != address(0x0));
require(_to != address(this));
_;
}
function GMRToken() public {
}
function transferFrom(address _from, address _to, uint256 _value) public
onlyWhenTransferEnabled
validDestination(_to)
returns (bool) {
return super.transferFrom(_from, _to, _value);
}
function approve(address _spender, uint256 _value) public
onlyWhenTransferEnabled
returns (bool) {
return super.approve(_spender, _value);
}
function increaseApproval (address _spender, uint _addedValue) public
onlyWhenTransferEnabled
returns (bool) {
return super.increaseApproval(_spender, _addedValue);
}
function decreaseApproval (address _spender, uint _subtractedValue) public
onlyWhenTransferEnabled
returns (bool) {
return super.decreaseApproval(_spender, _subtractedValue);
}
function transfer(address _to, uint256 _value) public
onlyWhenTransferEnabled
validDestination(_to)
returns (bool) {
return super.transfer(_to, _value);
}
}
// File: zeppelin\lifecycle\Pausable.sol
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyOwner whenNotPaused public {
paused = true;
Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused public {
paused = false;
Unpause();
}
}
// File: contracts\GimmerToken.sol
/**
* @title Gimmer Token Smart Contract
* @author [email protected], [email protected]
*/
contract GimmerToken is MintableToken {
// Constants
string public constant name = "GimmerToken";
string public constant symbol = "GMR";
uint8 public constant decimals = 18;
/**
* @dev Modifier to only allow transfers after the minting has been done
*/
modifier onlyWhenTransferEnabled() {
require(mintingFinished);
_;
}
modifier validDestination(address _to) {
require(_to != address(0x0));
require(_to != address(this));
_;
}
function GimmerToken() public {
}
function transferFrom(address _from, address _to, uint256 _value) public
onlyWhenTransferEnabled
validDestination(_to)
returns (bool) {
return super.transferFrom(_from, _to, _value);
}
function approve(address _spender, uint256 _value) public
onlyWhenTransferEnabled
returns (bool) {
return super.approve(_spender, _value);
}
function increaseApproval (address _spender, uint _addedValue) public
onlyWhenTransferEnabled
returns (bool) {
return super.increaseApproval(_spender, _addedValue);
}
function decreaseApproval (address _spender, uint _subtractedValue) public
onlyWhenTransferEnabled
returns (bool) {
return super.decreaseApproval(_spender, _subtractedValue);
}
function transfer(address _to, uint256 _value) public
onlyWhenTransferEnabled
validDestination(_to)
returns (bool) {
return super.transfer(_to, _value);
}
}
// File: contracts\GimmerTokenSale.sol
/**
* @title Gimmer Token Sale Smart Contract
* @author [email protected], [email protected]
*/
contract GimmerTokenSale is Pausable {
using SafeMath for uint256;
/**
* @dev Supporter structure, which allows us to track
* how much the user has bought so far, and if he's flagged as known
*/
struct Supporter {
uint256 weiSpent; // the total amount of Wei this address has sent to this contract
bool hasKYC; // if the user has KYC flagged
}
// Variables
mapping(address => Supporter) public supportersMap; // Mapping with all the campaign supporters
GimmerToken public token; // ERC20 GMR Token contract address
address public fundWallet; // Wallet address to forward all Ether to
address public kycManagerWallet; // Wallet address that manages the approval of KYC
address public currentAddress; // Wallet address that manages the approval of KYC
uint256 public tokensSold; // How many tokens sold have been sold in total
uint256 public weiRaised; // Total amount of raised money in Wei
uint256 public maxTxGas; // Maximum transaction gas price allowed for fair-chance transactions
uint256 public saleWeiLimitWithoutKYC; // The maximum amount of Wei an address can spend here without needing KYC approval during CrowdSale
bool public finished; // Flag denoting the owner has invoked finishContract()
uint256 public constant ONE_MILLION = 1000000; // One million for token cap calculation reference
uint256 public constant PRE_SALE_GMR_TOKEN_CAP = 15 * ONE_MILLION * 1 ether; // Maximum amount that can be sold during the Pre Sale period
uint256 public constant GMR_TOKEN_SALE_CAP = 100 * ONE_MILLION * 1 ether; // Maximum amount of tokens that can be sold by this contract
uint256 public constant MIN_ETHER = 0.1 ether; // Minimum ETH Contribution allowed during the crowd sale
/* Allowed Contribution in Ether */
uint256 public constant PRE_SALE_30_ETH = 30 ether; // Minimum 30 Ether to get 25% Bonus Tokens
uint256 public constant PRE_SALE_300_ETH = 300 ether; // Minimum 300 Ether to get 30% Bonus Tokens
uint256 public constant PRE_SALE_1000_ETH = 1000 ether; // Minimum 3000 Ether to get 40% Bonus Tokens
/* Bonus Tokens based on the ETH Contributed in single transaction */
uint256 public constant TOKEN_RATE_BASE_RATE = 2500; // Base Price for reference only
uint256 public constant TOKEN_RATE_05_PERCENT_BONUS = 2625; // 05% Bonus Tokens During Crowd Sale's Week 4
uint256 public constant TOKEN_RATE_10_PERCENT_BONUS = 2750; // 10% Bonus Tokens During Crowd Sale's Week 3
uint256 public constant TOKEN_RATE_15_PERCENT_BONUS = 2875; // 15% Bonus Tokens During Crowd Sale'sWeek 2
uint256 public constant TOKEN_RATE_20_PERCENT_BONUS = 3000; // 20% Bonus Tokens During Crowd Sale'sWeek 1
uint256 public constant TOKEN_RATE_25_PERCENT_BONUS = 3125; // 25% Bonus Tokens, During PreSale when >= 30 ETH & < 300 ETH
uint256 public constant TOKEN_RATE_30_PERCENT_BONUS = 3250; // 30% Bonus Tokens, During PreSale when >= 300 ETH & < 3000 ETH
uint256 public constant TOKEN_RATE_40_PERCENT_BONUS = 3500; // 40% Bonus Tokens, During PreSale when >= 3000 ETH
/* Timestamps where investments are allowed */
uint256 public constant PRE_SALE_START_TIME = 1525176000; // PreSale Start Time : UTC: Wednesday, 17 January 2018 12:00:00
uint256 public constant PRE_SALE_END_TIME = 1525521600; // PreSale End Time : UTC: Wednesday, 31 January 2018 12:00:00
uint256 public constant START_WEEK_1 = 1525608000; // CrowdSale Start Week-1 : UTC: Thursday, 1 February 2018 12:00:00
uint256 public constant START_WEEK_2 = 1526040000; // CrowdSale Start Week-2 : UTC: Thursday, 8 February 2018 12:00:00
uint256 public constant START_WEEK_3 = 1526472000; // CrowdSale Start Week-3 : UTC: Thursday, 15 February 2018 12:00:00
uint256 public constant START_WEEK_4 = 1526904000; // CrowdSale Start Week-4 : UTC: Thursday, 22 February 2018 12:00:00
uint256 public constant SALE_END_TIME = 1527336000; // CrowdSale End Time : UTC: Thursday, 1 March 2018 12:00:00
/**
* @dev Modifier to only allow KYCManager Wallet
* to execute a function
*/
modifier onlyKycManager() {
require(msg.sender == kycManagerWallet);
_;
}
/**
* Event for token purchase logging
* @param purchaser The wallet address that bought the tokens
* @param value How many Weis were paid for the purchase
* @param amount The amount of tokens purchased
*/
event TokenPurchase(address indexed purchaser, uint256 value, uint256 amount);
/**
* Event for kyc status change logging
* @param user User who has had his KYC status changed
* @param isApproved A boolean representing the KYC approval the user has been changed to
*/
event KYC(address indexed user, bool isApproved);
/**
* Constructor
* @param _fundWallet Address to forward all received Ethers to
* @param _kycManagerWallet KYC Manager wallet to approve / disapprove user's KYC
* @param _saleWeiLimitWithoutKYC Maximum amount of Wei an address can spend in the contract without KYC during the crowdsale
* @param _maxTxGas Maximum gas price a transaction can have before being reverted
*/
function GimmerTokenSale(
address _fundWallet,
address _kycManagerWallet,
uint256 _saleWeiLimitWithoutKYC,
uint256 _maxTxGas
)
public
{
require(_fundWallet != address(0));
require(_kycManagerWallet != address(0));
require(_saleWeiLimitWithoutKYC > 0);
require(_maxTxGas > 0);
currentAddress = this;
fundWallet = _fundWallet;
kycManagerWallet = _kycManagerWallet;
saleWeiLimitWithoutKYC = _saleWeiLimitWithoutKYC;
maxTxGas = _maxTxGas;
token = new GimmerToken();
}
/* fallback function can be used to buy tokens */
function () public payable {
buyTokens();
}
/* low level token purchase function */
function buyTokens() public payable whenNotPaused {
// Do not allow if gasprice is bigger than the maximum
// This is for fair-chance for all contributors, so no one can
// set a too-high transaction price and be able to buy earlier
require(tx.gasprice <= maxTxGas);
// valid purchase identifies which stage the contract is at (PreState/Token Sale)
// making sure were inside the contribution period and the user
// is sending enough Wei for the stage's rules
require(validPurchase());
address sender = msg.sender;
uint256 weiAmountSent = msg.value;
// calculate token amount to be created
uint256 rate = getRate(weiAmountSent);
uint256 newTokens = weiAmountSent.mul(rate);
// look if we have not yet reached the cap
uint256 totalTokensSold = tokensSold.add(newTokens);
if (isCrowdSaleRunning()) {
require(totalTokensSold <= GMR_TOKEN_SALE_CAP);
} else if (isPreSaleRunning()) {
require(totalTokensSold <= PRE_SALE_GMR_TOKEN_CAP);
}
// update supporter state
Supporter storage sup = supportersMap[sender];
uint256 totalWei = sup.weiSpent.add(weiAmountSent);
sup.weiSpent = totalWei;
// update contract state
weiRaised = weiRaised.add(weiAmountSent);
tokensSold = totalTokensSold;
// mint the coins
token.mint(sender, newTokens);
TokenPurchase(sender, weiAmountSent, newTokens);
// forward the funds to the wallet
fundWallet.transfer(msg.value);
}
/**
* @dev Ends the operation of the contract
*/
function finishContract() public onlyOwner {
// make sure the contribution period has ended
require(now > SALE_END_TIME);
require(!finished);
finished = true;
// send the 10% commission to Gimmer's fund wallet
uint256 tenPC = tokensSold.div(10);
token.mint(fundWallet, tenPC);
// finish the minting of the token, so the system allows transfers
token.finishMinting();
// transfer ownership of the token contract to the fund wallet,
// so it isn't locked to be a child of the crowd sale contract
token.transferOwnership(fundWallet);
}
function setSaleWeiLimitWithoutKYC(uint256 _newSaleWeiLimitWithoutKYC) public onlyKycManager {
require(_newSaleWeiLimitWithoutKYC > 0);
saleWeiLimitWithoutKYC = _newSaleWeiLimitWithoutKYC;
}
/**
* @dev Updates the maximum allowed transaction cost that can be received
* on the buyTokens() function.
* @param _newMaxTxGas The new maximum transaction cost
*/
function updateMaxTxGas(uint256 _newMaxTxGas) public onlyKycManager {
require(_newMaxTxGas > 0);
maxTxGas = _newMaxTxGas;
}
/**
* @dev Flag an user as known
* @param _user The user to flag as known
*/
function approveUserKYC(address _user) onlyKycManager public {
require(_user != address(0));
Supporter storage sup = supportersMap[_user];
sup.hasKYC = true;
KYC(_user, true);
}
/**
* @dev Flag an user as unknown/disapproved
* @param _user The user to flag as unknown / suspecious
*/
function disapproveUserKYC(address _user) onlyKycManager public {
require(_user != address(0));
Supporter storage sup = supportersMap[_user];
sup.hasKYC = false;
KYC(_user, false);
}
/**
* @dev Changes the KYC manager to a new address
* @param _newKYCManagerWallet The new address that will be managing KYC approval
*/
function setKYCManager(address _newKYCManagerWallet) onlyOwner public {
require(_newKYCManagerWallet != address(0));
kycManagerWallet = _newKYCManagerWallet;
}
/**
* @dev Returns true if any of the token sale stages are currently running
* @return A boolean representing the state of this contract
*/
function isTokenSaleRunning() public constant returns (bool) {
return (isPreSaleRunning() || isCrowdSaleRunning());
}
/**
* @dev Returns true if the presale sale is currently running
* @return A boolean representing the state of the presale
*/
function isPreSaleRunning() public constant returns (bool) {
return (now >= PRE_SALE_START_TIME && now < PRE_SALE_END_TIME);
}
/**
* @dev Returns true if the public sale is currently running
* @return A boolean representing the state of the crowd sale
*/
function isCrowdSaleRunning() public constant returns (bool) {
return (now >= START_WEEK_1 && now <= SALE_END_TIME);
}
/**
* @dev Returns true if the public sale has ended
* @return A boolean representing if we are past the contribution date for this contract
*/
function hasEnded() public constant returns (bool) {
return now > SALE_END_TIME;
}
/**
* @dev Returns true if the pre sale has ended
* @return A boolean representing if we are past the pre sale contribution dates
*/
function hasPreSaleEnded() public constant returns (bool) {
return now > PRE_SALE_END_TIME;
}
/**
* @dev Returns if an user has KYC approval or not
* @return A boolean representing the user's KYC status
*/
function userHasKYC(address _user) public constant returns (bool) {
return supportersMap[_user].hasKYC;
}
/**
* @dev Returns the weiSpent of a user
*/
function userWeiSpent(address _user) public constant returns (uint256) {
return supportersMap[_user].weiSpent;
}
/**
* @dev Returns the rate the user will be paying at,
* based on the amount of Wei sent to the contract, and the current time
* @return An uint256 representing the rate the user will pay for the GMR tokens
*/
function getRate(uint256 _weiAmount) internal constant returns (uint256) {
if (isCrowdSaleRunning()) {
if (now >= START_WEEK_4) { return TOKEN_RATE_05_PERCENT_BONUS; }
else if (now >= START_WEEK_3) { return TOKEN_RATE_10_PERCENT_BONUS; }
else if (now >= START_WEEK_2) { return TOKEN_RATE_15_PERCENT_BONUS; }
else if (now >= START_WEEK_1) { return TOKEN_RATE_20_PERCENT_BONUS; }
}
else if (isPreSaleRunning()) {
if (_weiAmount >= PRE_SALE_1000_ETH) { return TOKEN_RATE_40_PERCENT_BONUS; }
else if (_weiAmount >= PRE_SALE_300_ETH) { return TOKEN_RATE_30_PERCENT_BONUS; }
else if (_weiAmount >= PRE_SALE_30_ETH) { return TOKEN_RATE_25_PERCENT_BONUS; }
}
}
/* @return true if the transaction can buy tokens, otherwise false */
function validPurchase() internal constant returns (bool) {
bool userHasKyc = userHasKYC(msg.sender);
if (isCrowdSaleRunning()) {
// crowdsale restrictions (KYC only needed after wei limit, minimum of 0.1 ETH tx)
if(!userHasKyc) {
Supporter storage sup = supportersMap[msg.sender];
uint256 ethContribution = sup.weiSpent.add(msg.value);
if (ethContribution > saleWeiLimitWithoutKYC) {
return false;
}
}
return msg.value >= MIN_ETHER;
}
else if (isPreSaleRunning()) {
// presale restrictions (at least 30 eth, always KYC)
return userHasKyc && msg.value >= PRE_SALE_30_ETH;
} else {
return false;
}
}
}
// File: contracts\GMRTokenManager.sol
/**
* @title Gimmer Token Sale Manager Smart Contract
* @author [email protected], [email protected]
*/
contract GMRTokenManager is Ownable {
using SafeMath for uint256;
/* Contracts */
GMRToken public token;
GimmerTokenSale public oldTokenSale;
/* Flags for tracking contract usage */
bool public finishedMigration;
/* Constants */
uint256 public constant TOKEN_BONUS_RATE = 8785; // The rate for the bonus given to precontract contributors
/**
* Constructor
* @param _oldTokenSaleAddress Old Token Sale contract address
*/
function GMRTokenManager(address _oldTokenSaleAddress) public {
// access the old token sale
oldTokenSale = GimmerTokenSale(_oldTokenSaleAddress);
// deploy the token contract
token = new GMRToken();
}
/**
* Prepopulates the specified wallet
* @param _wallet Wallet to mint the reserve tokens to
*/
function prepopulate(address _wallet) public onlyOwner {
require(!finishedMigration);
require(_wallet != address(0));
// get the balance the user spent in the last sale
uint256 spent = oldTokenSale.userWeiSpent(_wallet);
require(spent != 0);
// make sure we have not prepopulated already
uint256 balance = token.balanceOf(_wallet);
require(balance == 0);
// calculate the new balance with bonus
uint256 tokens = spent.mul(TOKEN_BONUS_RATE);
// mint the coins
token.mint(_wallet, tokens);
}
/**
* Ends the migration process by giving the token
* contract back to the owner
*/
function endMigration() public onlyOwner {
require(!finishedMigration);
finishedMigration = true;
token.transferOwnership(owner);
}
}
| 30% Bonus Tokens, During PreSale when >= 300 ETH & < 3000 ETH
| uint256 public constant TOKEN_RATE_30_PERCENT_BONUS = 3250; | 6,368,304 | [
1,
5082,
9,
605,
22889,
13899,
16,
463,
4017,
2962,
30746,
1347,
1545,
11631,
512,
2455,
473,
411,
29839,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
2254,
5034,
1071,
5381,
14275,
67,
24062,
67,
5082,
67,
3194,
19666,
67,
38,
673,
3378,
273,
890,
26520,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^ 0.4.16;
/**
* @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 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 ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) public constant returns(uint256);
function transfer(address to, uint256 value) public returns(bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public constant returns(uint256);
function transferFrom(address from, address to, uint256 value) public returns(bool);
function approve(address spender, uint256 value) public returns(bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract Lockupable is Pausable {
function _unlockIfPosible(address who) internal;
function unlockAll() onlyOwner public returns(bool);
function lockupOf(address who) public constant returns(uint256[5]);
function distribute(address _to, uint256 _value, uint256 _amount1, uint256 _amount2, uint256 _amount3, uint256 _amount4) onlyOwner public returns(bool);
}
/**
* @title ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20Token is ERC20 {
using SafeMath for uint256;
mapping(address => uint256) balances;
mapping(address => mapping(address => uint256)) internal allowed;
/**
* @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 _holder The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _holder) public constant returns(uint256 balance) {
return balances[_holder];
}
/**
* @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];
}
}
/**
* @title Lockupable token
*
* @dev ERC20Token modified with lockupable.
**/
contract LockupableToken is ERC20Token, Lockupable {
uint64[] RELEASE = new uint64[](4);
mapping(address => uint256[4]) lockups;
mapping(uint => address) private holders;
uint _lockupHolders;
bool unlocked;
function transfer(address _to, uint256 _value) public whenNotPaused returns(bool) {
_unlockIfPosible(_to);
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns(bool) {
_unlockIfPosible(_from);
return super.transferFrom(_from, _to, _value);
}
function approve(address _spender, uint256 _value) public whenNotPaused returns(bool) {
return super.approve(_spender, _value);
}
function balanceOf(address _holder) public constant returns(uint256 balance) {
uint256[5] memory amount = lockupOf(_holder);
return amount[0];
}
/**
* @dev Gets the lockup of the specified address.
* @param who address The address to query the the balance of.
* @return An lockupOf representing the amount owned by the passed address.
*/
function lockupOf(address who) public constant returns(uint256[5]){
uint256[5] memory amount;
amount[0] = balances[who];
for (uint i = 0; i < RELEASE.length; i++) {
amount[i + 1] = lockups[who][i];
if (now >= RELEASE[i]) {
amount[0] = amount[0].add(lockups[who][i]);
amount[i + 1] = 0;
}
}
return amount;
}
/**
* @dev update balance lockUpAmount
* @param who address The address updated the balances of.
*/
function _unlockIfPosible(address who) internal{
if (now <= RELEASE[3] || !unlocked) {
uint256[5] memory amount = lockupOf(who);
balances[who] = amount[0];
for (uint i = 0; i < 4; i++) {
lockups[who][i] = amount[i + 1];
}
}
}
/**
* @dev unlock all after August 31 , 2019 GMT+9.
*
*/
function unlockAll() onlyOwner public returns(bool){
if (now > RELEASE[3]) {
for (uint i = 0; i < _lockupHolders; i++) {
balances[holders[i]] = balances[holders[i]].add(lockups[holders[i]][0]);
balances[holders[i]] = balances[holders[i]].add(lockups[holders[i]][1]);
balances[holders[i]] = balances[holders[i]].add(lockups[holders[i]][2]);
balances[holders[i]] = balances[holders[i]].add(lockups[holders[i]][3]);
lockups[holders[i]][0] = 0;
lockups[holders[i]][1] = 0;
lockups[holders[i]][2] = 0;
lockups[holders[i]][3] = 0;
}
unlocked = true;
}
return true;
}
/**
* @dev Distribute tokens from owner address to another , distribute for ICO and bounty campaign
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of Amount1-type-tokens to be transferred
* ...
* @param _amount4 uint256 the amount of Amount1-type-tokens to be transferred
*/
function distribute(address _to, uint256 _value, uint256 _amount1, uint256 _amount2, uint256 _amount3, uint256 _amount4) onlyOwner public returns(bool) {
require(_to != address(0));
_unlockIfPosible(msg.sender);
uint256 __total = 0;
__total = __total.add(_amount1);
__total = __total.add(_amount2);
__total = __total.add(_amount3);
__total = __total.add(_amount4);
__total = __total.add(_value);
balances[msg.sender] = balances[msg.sender].sub(__total);
balances[_to] = balances[_to].add(_value);
lockups[_to][0] = lockups[_to][0].add(_amount1);
lockups[_to][1] = lockups[_to][1].add(_amount2);
lockups[_to][2] = lockups[_to][2].add(_amount3);
lockups[_to][3] = lockups[_to][3].add(_amount4);
holders[_lockupHolders] = _to;
_lockupHolders++;
Transfer(msg.sender, _to, __total);
return true;
}
}
/**
* @title BBXC Token
*
* @dev Implementation of BBXC Token based on the ERC20Token token.
*/
contract BBXCToken is LockupableToken {
function () {
//if ether is sent to this address, send it back.
revert();
}
/**
* Public variables of the token
*/
string public constant name = 'Bluebelt Exchange Coin';
string public constant symbol = 'BBXC';
uint8 public constant decimals = 18;
/**
* @dev Constructor
*/
function BBXCToken() {
_lockupHolders = 0;
RELEASE[0] = 1553958000; // March 30, 2019, GMT+9
RELEASE[1] = 1556550000; // April 29, 2019, GMT+9.
RELEASE[2] = 1559228400; // May 30, 2019, GMT+9.
RELEASE[3] = 1567263600; // August 31 , 2019 GMT+9.
totalSupply = 200000000 * (uint256(10) ** decimals);
unlocked = false;
balances[msg.sender] = totalSupply;
Transfer(address(0x0), msg.sender, totalSupply);
}
} | * @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];
}
| 12,906,699 | [
1,
2083,
358,
866,
326,
3844,
434,
2430,
716,
392,
3410,
2935,
358,
279,
17571,
264,
18,
225,
389,
8443,
1758,
1021,
1758,
1492,
29065,
326,
284,
19156,
18,
225,
389,
87,
1302,
264,
1758,
1021,
1758,
1492,
903,
17571,
326,
284,
19156,
18,
327,
432,
2254,
5034,
13664,
326,
3844,
434,
2430,
4859,
2319,
364,
326,
17571,
264,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
1699,
1359,
12,
2867,
389,
8443,
16,
1758,
389,
87,
1302,
264,
13,
1071,
5381,
1135,
12,
11890,
5034,
4463,
13,
288,
203,
565,
327,
2935,
63,
67,
8443,
6362,
67,
87,
1302,
264,
15533,
203,
225,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/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/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/IERC20.sol
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/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/Pausable.sol
pragma solidity ^0.6.0;
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
*/
contract Pausable is Context {
event Paused(address account);
event Shutdown(address account);
event Unpaused(address account);
event Open(address account);
bool public paused;
bool public stopEverything;
constructor() internal {
paused = false;
stopEverything = false;
}
modifier whenNotPaused() {
require(!paused, "Pausable: paused");
_;
}
modifier whenPaused() {
require(paused, "Pausable: not paused");
_;
}
modifier whenNotShutdown() {
require(!stopEverything, "Pausable: shutdown");
_;
}
modifier whenShutdown() {
require(stopEverything, "Pausable: not shutdown");
_;
}
function _pause() internal virtual whenNotPaused {
paused = true;
emit Paused(_msgSender());
}
function _unpause() internal virtual whenPaused whenNotShutdown {
paused = false;
emit Unpaused(_msgSender());
}
function _shutdown() internal virtual whenNotShutdown {
stopEverything = true;
paused = true;
emit Shutdown(_msgSender());
}
function _open() internal virtual whenShutdown {
stopEverything = false;
emit Open(_msgSender());
}
}
// File: @openzeppelin/contracts/utils/ReentrancyGuard.sol
pragma solidity ^0.6.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].
*/
contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor () internal {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// File: contracts/PoolShareToken.sol
pragma solidity ^0.6.6;
abstract contract PoolShareToken is ERC20, ReentrancyGuard, Pausable {
uint256 public withdrawFee; // Example: 1e17 is 10%
address public feeCollector;
/**
* @dev Constructor.
*/
constructor(string memory name, string memory symbol) public ERC20(name, symbol) {}
/**
* @dev Receives ETH and grants new tokens to the sender depending on the
* value of each contract's share.
*/
function deposit() public virtual payable nonReentrant {}
/**
* @dev Returns the value stored in the contract. Should be overwritten if
* it stored in another contract.
*/
function totalValue() public virtual view returns (uint256) {}
/**
* @dev Burns tokens and retuns the ETH value of those.
*/
function withdraw() public virtual {}
/**
* @dev Hook that is called just before minting new tokens. To be used i.e.
* if the deposited amount is to be transferred to a different contract.
*/
function _beforeMinting(uint256 amount) internal virtual {}
/**
* @dev Hook that is called just after burning tokens. To be used i.e. if
* the ETH stored in a different/this contract needs to be transferred.
*/
function _afterBurning(uint256 shares) internal virtual {}
function _deposit(uint256 amount) internal whenNotPaused {
require(amount > 0, "Deposit must be greater than 0");
uint256 _totalSupply = totalSupply();
uint256 _totalValue = totalValue();
uint256 shares = (_totalSupply == 0 || _totalValue == 0)
? amount
: amount.mul(_totalSupply).div(_totalValue);
require(_totalSupply.add(shares) < 50e18, "test limit");
_beforeMinting(amount);
_mint(msg.sender, shares);
}
event Withdraw(address owner, uint256 shares, uint256 amount);
/**
* @dev Hook that is called just before burning tokens. To be used i.e. if
* the ETH is stored in a different contract and must be withdraw from there
* first.
*/
function _beforeBurning(uint256 shares) internal virtual {}
function _handleFee(uint256 shares) internal returns (uint256 _sharesAfterFee) {
if (withdrawFee > 0) {
uint256 _fee = shares.mul(withdrawFee).div(1e18);
_sharesAfterFee = shares.sub(_fee);
_transfer(_msgSender(), feeCollector, _fee);
} else {
_sharesAfterFee = shares;
}
}
function _updateWithdrawFee(uint256 _withdrawFee) internal {
require(_withdrawFee <= 1e18, "fee is greater than 100%");
withdrawFee = _withdrawFee;
}
function _updateFeeCollector(address _feeCollector) internal {
require(_feeCollector != address(0), "_feeCollector is 0x0");
feeCollector = _feeCollector;
}
/**
* @dev Burns tokens and retuns the collateral value, after fee, of those.
*/
function _withdraw(uint256 shares) internal whenNotShutdown {
require(shares > 0, "Withdraw must be greater than 0");
uint256 sharesAfterFee = _handleFee(shares);
uint256 amount = sharesAfterFee.mul(totalValue()).div(totalSupply());
_burn(msg.sender, shares);
_afterBurning(amount);
emit Withdraw(msg.sender, shares, amount);
}
}
// File: contracts/interfaces/ICollateralManager.sol
pragma solidity ^0.6.6;
interface ICollateralManager {
function borrowDai(uint256 vaultNum, uint256 amount) external;
function depositCollateral(uint256 vaultNum) external payable;
function depositCollateral(uint256 vaultNum, uint256 amount) external;
function getVaultBalance(uint256 vaultNum) external view returns (uint256 collateralLocked);
function getVaultDebt(uint256 vaultNum) external view returns (uint256 daiDebt);
function getVaultInfo(uint256 vaultNum)
external
view
returns (
uint256 collateralLocked,
uint256 daiDebt,
uint256 collateralUsdRate,
uint256 collateralRatio,
uint256 minimumDebt
);
function isEmpty(uint256 vaultNum) external view returns (bool);
function paybackDai(uint256 vaultNum, uint256 amount) external;
function registerVault(uint256 vaultNum, bytes32 collateralType) external;
function updateStrategyManager(uint256 vaultNum, address strategyManager) external;
function vaultOwner(uint256 vaultNum) external returns (address owner);
function whatWouldWithdrawDo(uint256 vaultNum, uint256 amount)
external
view
returns (
uint256 collateralLocked,
uint256 daiDebt,
uint256 collateralUsdRate,
uint256 collateralRatio,
uint256 minimumDebt
);
function withdrawCollateral(
uint256 vaultNum,
uint256 amount,
address recipient
) external;
}
// File: contracts/interfaces/IStrategyManager.sol
pragma solidity ^0.6.6;
interface StrategyManager {
function getStrategyTokenAddress(address token) external returns (address);
function isEmpty() external returns (bool);
function moveDaiFromAave(uint256 vaultNum, uint256 amount) external;
function moveDaiToMaker(uint256 vaultNum, uint256 amount) external;
function rebalance(
uint256 vaulNum,
uint256 highWater,
uint256 lowWater
) external;
function rebalanceCollRatio(
uint256 vaulNum,
uint256 highWater,
uint256 lowWater
) external;
function rebalanceEarnedDai(uint256 vaultNum) external;
function updateCollateralManager(address collateralManager) external;
}
// File: contracts/uniswap/IUniswapV2Router01.sol
pragma solidity ^0.6.6;
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
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 addLiquidityETH(
address token,
uint256 amountTokenDesired,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
)
external
payable
returns (
uint256 amountToken,
uint256 amountETH,
uint256 liquidity
);
function removeLiquidity(
address tokenA,
address tokenB,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
) external returns (uint256 amountA, uint256 amountB);
function removeLiquidityETH(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
) external returns (uint256 amountToken, uint256 amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256 amountA, uint256 amountB);
function removeLiquidityETHWithPermit(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256 amountToken, uint256 amountETH);
function swapExactTokensForTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapTokensForExactTokens(
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapExactETHForTokens(
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts);
function swapTokensForExactETH(
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapExactTokensForETH(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapETHForExactTokens(
uint256 amountOut,
address[] calldata path,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts);
function quote(
uint256 amountA,
uint256 reserveA,
uint256 reserveB
) external pure returns (uint256 amountB);
function getAmountOut(
uint256 amountIn,
uint256 reserveIn,
uint256 reserveOut
) external pure returns (uint256 amountOut);
function getAmountIn(
uint256 amountOut,
uint256 reserveIn,
uint256 reserveOut
) external pure returns (uint256 amountIn);
function getAmountsOut(uint256 amountIn, address[] calldata path)
external
view
returns (uint256[] memory amounts);
function getAmountsIn(uint256 amountOut, address[] calldata path)
external
view
returns (uint256[] memory amounts);
}
// File: contracts/uniswap/IUniswapV2Router02.sol
pragma solidity ^0.6.6;
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
) external returns (uint256 amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256 amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external;
}
// File: contracts/AddressProvider.sol
pragma solidity ^0.6.6;
interface GemJoinInterface {
function ilk() external view returns (bytes32);
}
contract Helper is Ownable {
mapping(bytes32 => address) public mcdGemJoin;
event LogAddGemJoin(address[] gemJoin);
/**
* @dev Add gemJoin adapter address from Maker in mapping
*/
function addGemJoin(address[] memory gemJoins) public onlyOwner {
require(gemJoins.length > 0, "No gemJoin address");
for (uint256 i = 0; i < gemJoins.length; i++) {
address gemJoin = gemJoins[i];
bytes32 ilk = GemJoinInterface(gemJoin).ilk();
require(mcdGemJoin[ilk] == address(0), "GemJoin already added");
mcdGemJoin[ilk] = gemJoin;
}
emit LogAddGemJoin(gemJoins);
}
}
contract AddressProvider is Helper {
// Default mainnet
address public daiAddress;
address public manaAddress;
address public mcdManaJoin;
address public mcdManager;
address public mcdEthJoin;
address public mcdSpot;
address public mcdDaiJoin;
address public mcdJug;
address public aaveProvider;
address public uniswapRouterV2;
address public weth;
constructor() public {
uint256 id;
assembly {
id := chainid()
}
if (id == 42) {
aaveProvider = 0x506B0B2CF20FAA8f38a4E2B524EE43e1f4458Cc5;
uniswapRouterV2 = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
// https://changelog.makerdao.com/releases/kovan/1.0.9/contracts.json
daiAddress = 0x4F96Fe3b7A6Cf9725f59d353F723c1bDb64CA6Aa;
manaAddress = 0x221F4D62636b7B51b99e36444ea47Dc7831c2B2f;
mcdManager = 0x1476483dD8C35F25e568113C5f70249D3976ba21;
mcdDaiJoin = 0x5AA71a3ae1C0bd6ac27A1f28e1415fFFB6F15B8c;
mcdSpot = 0x3a042de6413eDB15F2784f2f97cC68C7E9750b2D;
mcdJug = 0xcbB7718c9F39d05aEEDE1c472ca8Bf804b2f1EaD;
weth = 0xd0A1E359811322d97991E03f863a0C30C2cF029C;
} else {
aaveProvider = 0x24a42fD28C976A61Df5D00D0599C34c4f90748c8;
uniswapRouterV2 = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
// https://changelog.makerdao.com/releases/mainnet/1.0.9/contracts.json
daiAddress = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
manaAddress = 0x0F5D2fB29fb7d3CFeE444a200298f468908cC942;
mcdManager = 0x5ef30b9986345249bc32d8928B7ee64DE9435E39;
mcdDaiJoin = 0x9759A6Ac90977b93B58547b4A71c78317f391A28;
mcdSpot = 0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3;
mcdJug = 0x19c0976f590D67707E62397C87829d896Dc0f1F1;
weth = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
}
}
}
// File: contracts/VTokenBase.sol
pragma solidity ^0.6.6;
interface ManagerLike {
function vat() external view returns (address);
function open(bytes32, address) external returns (uint256);
function cdpAllow(
uint256,
address,
uint256
) external;
}
interface VatLike {
function hope(address) external;
}
abstract contract VTokenBase is PoolShareToken, Ownable {
uint256 public vaultNum;
bytes32 public collType;
AddressProvider internal ap = new AddressProvider();
uint256 internal constant WAT = 10**16;
address internal ethAddress = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
uint256 internal highWater = 300 * WAT;
uint256 internal lowWater = 250 * WAT;
bool internal lockEth = true;
ICollateralManager public cm;
StrategyManager public sm;
constructor(
string memory name,
string memory symbol,
bytes32 _collType
) public PoolShareToken(name, symbol) {
collType = _collType;
}
function approveToken() public virtual {
IERC20 aDai = IERC20(sm.getStrategyTokenAddress(ap.daiAddress()));
aDai.approve(address(sm), uint256(-1));
}
function init(address _cm, address _sm) public onlyOwner {
require(vaultNum == 0, "Already intialized");
require(address(cm) == address(0), "Already intialized");
require(address(sm) == address(0), "Already intialized");
cm = ICollateralManager(_cm);
sm = StrategyManager(_sm);
vaultNum = createVault(collType, _cm);
cm.updateStrategyManager(vaultNum, _sm);
approveToken();
}
function pause() public onlyOwner {
_pause();
}
function unpause() public onlyOwner {
_unpause();
}
function shutdown() public onlyOwner {
_shutdown();
}
function open() public onlyOwner {
_open();
}
function updateFeeAndCollector(uint256 _fee, address _feeCollector) public onlyOwner {
_updateWithdrawFee(_fee);
_updateFeeCollector(_feeCollector);
}
function updateManagers(address _cm, address _sm) public onlyOwner {
require(_cm != address(0) && _sm != address(0), "CM and SM cannot be 0");
// Check cm and sm has no token or eth stored.
require(cm.isEmpty(vaultNum), "CM is not empty");
require(sm.isEmpty(), "SM is not empty");
cm = ICollateralManager(_cm);
registerCollateralManager(_cm);
cm.updateStrategyManager(vaultNum, _sm);
sm = StrategyManager(_sm);
sm.updateCollateralManager(_cm);
}
function updateBalancingFactor(uint256 _highWater, uint256 _lowWater) public onlyOwner {
require(_lowWater > 0, "Value is zero");
require(_highWater > _lowWater, "highWater is small than lowWater");
highWater = _highWater.mul(WAT);
lowWater = _lowWater.mul(WAT);
}
function rebalanceCollRatio() public {
require(!stopEverything || (_msgSender() == owner()), "Not an owner");
sm.rebalanceCollRatio(vaultNum, highWater, lowWater);
}
function rebalanceEarnedDai() public {
require(!stopEverything || (_msgSender() == owner()), "Not an owner");
sm.rebalanceEarnedDai(vaultNum);
}
function getVaultBalance() public view returns (uint256 collateralLocked) {
collateralLocked = cm.getVaultBalance(vaultNum);
}
function _afterBurning(uint256 amount) internal override {
(
uint256 collaterolLocked,
uint256 daiDebt,
uint256 collateralUsdRate,
uint256 collateralRatio,
uint256 minimumDebt
) = cm.whatWouldWithdrawDo(vaultNum, amount);
if (daiDebt > 0) {
IERC20 aDai = IERC20(sm.getStrategyTokenAddress(ap.daiAddress()));
uint256 aDaiBalance = aDai.balanceOf(address(this));
require(daiDebt <= aDaiBalance, "Pool is underwater");
if (collateralRatio < lowWater) {
// If this withdraw results in Low Water scenario.
uint256 maxDaiDebt = (collaterolLocked.mul(collateralUsdRate)).div(highWater);
if (maxDaiDebt < minimumDebt) {
// This is Dusting scenario
sm.moveDaiToMaker(vaultNum, daiDebt);
} else if (maxDaiDebt < daiDebt) {
sm.moveDaiToMaker(vaultNum, daiDebt.sub(maxDaiDebt));
}
}
}
cm.withdrawCollateral(vaultNum, amount, msg.sender);
}
function totalValue() public override view returns (uint256 value) {
value = cm.getVaultBalance(vaultNum);
}
function createVault(bytes32 _collType, address _cm) internal returns (uint256 vaultId) {
ManagerLike manager = ManagerLike(ap.mcdManager());
vaultId = manager.open(_collType, address(this));
manager.cdpAllow(vaultId, address(this), 1);
//hope and cpdAllow on vat for collateralManager's address
VatLike(manager.vat()).hope(_cm);
manager.cdpAllow(vaultId, _cm, 1);
//Register vault with collateral Manager
ICollateralManager(_cm).registerVault(vaultId, _collType);
}
function registerCollateralManager(address _cm) internal {
ManagerLike manager = ManagerLike(ap.mcdManager());
//hope and cpdAllow on vat for collateralManager's address
VatLike(manager.vat()).hope(_cm);
manager.cdpAllow(vaultNum, _cm, 1);
//Register vault with collateral Manager
ICollateralManager(_cm).registerVault(vaultNum, collType);
}
function _sweepErc20(address from, address to) internal {
require(
from != to &&
from != address(this) &&
from != ap.daiAddress() &&
from != sm.getStrategyTokenAddress(ap.daiAddress()),
"Not allowed to sweep"
);
IUniswapV2Router02 uniswapRouter = IUniswapV2Router02(ap.uniswapRouterV2());
IERC20 token = IERC20(from);
uint256 amt = token.balanceOf(address(this));
token.approve(address(uniswapRouter), amt);
address[] memory path = new address[](2);
path[0] = from;
if (to == ethAddress) {
path[1] = uniswapRouter.WETH();
uniswapRouter.swapExactTokensForETH(amt, 1, path, address(this), now + 30);
} else {
path[1] = to;
uniswapRouter.swapExactTokensForTokens(amt, 1, path, address(this), now + 30);
}
}
}
// File: contracts/VWETH.sol
pragma solidity ^0.6.6;
contract VWETH is VTokenBase("VWETH Pool Token", "VWETH", "ETH-A") {
/**
* @dev Handle incoming ETH to the contract address.
*/
receive() external payable {
if (lockEth) {
deposit();
}
}
/**
* @dev Receives ETH and grants new tokens to the sender depending on the
* value of each contract's share.
*/
function deposit() public override payable nonReentrant {
_deposit(msg.value);
}
function withdraw(uint256 shares) public nonReentrant {
_withdraw(shares);
}
function sweepErc20(address erc20) public {
lockEth = false;
_sweepErc20(erc20, ethAddress);
cm.depositCollateral{value: address(this).balance}(vaultNum);
lockEth = true;
}
function _beforeMinting(uint256 amount) internal override {
cm.depositCollateral{value: amount}(vaultNum);
}
} | hope and cpdAllow on vat for collateralManager's addressRegister vault with collateral Manager | function registerCollateralManager(address _cm) internal {
ManagerLike manager = ManagerLike(ap.mcdManager());
VatLike(manager.vat()).hope(_cm);
manager.cdpAllow(vaultNum, _cm, 1);
ICollateralManager(_cm).registerVault(vaultNum, collType);
}
| 10,034,361 | [
1,
76,
1306,
471,
29660,
7009,
603,
17359,
364,
4508,
2045,
287,
1318,
1807,
1758,
3996,
9229,
598,
4508,
2045,
287,
8558,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
1744,
13535,
2045,
287,
1318,
12,
2867,
389,
7670,
13,
2713,
288,
203,
3639,
8558,
8804,
3301,
273,
8558,
8804,
12,
438,
18,
81,
4315,
1318,
10663,
203,
3639,
25299,
8804,
12,
4181,
18,
25012,
1435,
2934,
76,
1306,
24899,
7670,
1769,
203,
3639,
3301,
18,
4315,
84,
7009,
12,
26983,
2578,
16,
389,
7670,
16,
404,
1769,
203,
203,
3639,
467,
13535,
2045,
287,
1318,
24899,
7670,
2934,
4861,
12003,
12,
26983,
2578,
16,
4508,
559,
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
] |
pragma solidity ^0.6.8;
pragma experimental ABIEncoderV2;
// From https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/math/Math.sol
// Subject to the MIT license.
/**
* @dev String operations.
*/
library Strings {
/**
* @dev Converts a `uint256` to its ASCII `string` representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
uint256 index = digits - 1;
temp = value;
while (temp != 0) {
buffer[index--] = byte(uint8(48 + temp % 10));
temp /= 10;
}
return string(buffer);
}
}
/**
* @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;
}
}
/**
* @title ERC 20 Token Standard Interface
* https://eips.ethereum.org/EIPS/eip-20
*/
interface EIP20Interface {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
function totalSupply() external view returns (uint256);
function balanceOf(address owner) external view returns (uint256 balance);
function transfer(address dst, uint256 amount) external returns (bool success);
function transferFrom(address src, address dst, uint256 amount) external returns (bool success);
function approve(address spender, uint256 amount) external returns (bool success);
function allowance(address owner, address spender) external view returns (uint256 remaining);
event Transfer(address indexed from, address indexed to, uint256 amount);
event Approval(address indexed owner, address indexed spender, uint256 amount);
}
/*
* @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");
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);
}
}
}
}
/**
* @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);
}
contract CallOption {
using SafeMath for uint256;
using Strings for uint256;
using Address for address;
struct PremiumInfo {
address premiumToken;
uint premiumAmt;
bool premiumRedeemed;
uint premiumPlatformFee;
uint sellerPremium;
}
struct UnderlyingInfo {
address underlyingCurrency;
uint underlyingAmt;
bool redeemed;
bool isCall;
}
struct Option {
// Proposal high level
uint proposalExpiresAt;
address seller;
address buyer;
// Proposal premium
PremiumInfo premiumInfo;
// Underlying
UnderlyingInfo underlyingInfo;
// Strike price
address strikeCurrency;
uint strikeAmt;
// Acceptance state
bool sellerAccepted;
bool buyerAccepted;
// Option
uint optionExpiresAt;
bool cancelled;
bool executed;
}
event UnderlyingDeposited(uint indexed optionUID, address seller, address token, uint amount);
event PremiumDeposited(uint indexed optionUID, address buyer, address token, uint amount);
event SellerAccepted(uint indexed optionUID, address seller);
event BuyerAccepted(uint indexed optionUID, address buyer);
event BuyerCancelled(uint indexed optionUID, address buyer);
event SellerCancelled(uint indexed optionUID, address seller);
event BuyerPremiumRefunded(uint indexed optionUID, address buyer);
event SellerUnderlyingRedeemed(uint indexed optionUID, address seller);
event SellerRedeemedPremium(uint indexed optionUID, address seller);
event TransferSeller(uint indexed optionUID, address oldSeller, address newSeller);
event OptionExecuted(uint indexed optionUID);
/// @dev This emits when ownership of any NFT changes by any mechanism.
/// This event emits when NFTs are created (`from` == 0) and destroyed
/// (`to` == 0). Exception: during contract creation, any number of NFTs
/// may be created and assigned without emitting Transfer. At the time of
/// any transfer, the approved address for that NFT (if any) is reset to none.
event Transfer(address indexed _from, address indexed _to, uint256 indexed _tokenId);
/// @dev This emits when the approved address for an NFT is changed or
/// reaffirmed. The zero address indicates there is no approved address.
/// When a Transfer event emits, this also indicates that the approved
/// address for that NFT (if any) is reset to none.
event Approval(address indexed _owner, address indexed _approved, uint256 indexed _tokenId);
/// @dev This emits when an operator is enabled or disabled for an owner.
/// The operator can manage all NFTs of the owner.
event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved);
// Maps user to the IDS of their associated options
mapping(address => uint[]) public userOptions;
// Stores the state of all the options
Option[] public options;
// Fee taken out of the premiums collected
uint public platformFee = 5; // 0.005
// Address which collected fees are directed to
address public feeBeneficiaryAddress;
// Fees that are withdrawable
mapping(address => uint) public platformFeeBalances;
// 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;
string public constant symbol = "OPTION-SWAP";
string public constant name = "ERC-20 Option (OptionSwap.finance)";
address public admin;
constructor() public {
admin = msg.sender;
}
/**
* @notice Propose a new option with the following criteria
*/
function propose(address seller, address buyer, uint proposalExpiresAt, uint optionExpiresAt,
address premiumToken, uint premiumAmt,
address underlyingCurrency, uint underlyingAmt,
address strikeCurrency, uint strikeAmt, bool isCall) public {
require((seller == msg.sender) || (buyer == msg.sender), "Must be either the seller or buyer");
require(proposalExpiresAt <= optionExpiresAt, "Option cannot expire before proposal");
// Compute the seller premium to be earned and associated platform fee from the premium
(uint sellerPremium, uint platformFeePremium) = _computePremiumSplit(premiumAmt, EIP20Interface(premiumToken).decimals());
// Add the option to list of options
options.push(Option(
{
seller: seller,
buyer: buyer,
proposalExpiresAt: proposalExpiresAt,
premiumInfo: PremiumInfo({
premiumToken: premiumToken,
premiumAmt: premiumAmt,
premiumRedeemed: false,
premiumPlatformFee: platformFeePremium,
sellerPremium: sellerPremium}),
underlyingInfo: UnderlyingInfo({
underlyingCurrency: underlyingCurrency,
underlyingAmt: underlyingAmt,
isCall: isCall,
redeemed: false }),
strikeCurrency: strikeCurrency,
strikeAmt: strikeAmt,
optionExpiresAt: optionExpiresAt,
cancelled: false,
executed: false,
sellerAccepted: false,
buyerAccepted: false
}));
// If sender is the seller, transfer underlying and update tracking state
if (msg.sender == seller) {
_acceptSeller(options.length - 1);
}
// If sender is the buyer, transfer premium and update tracking state
if (msg.sender == buyer) {
_acceptBuyer(options.length - 1);
}
}
/**
* @notice Compute how much of the premium goes to the seller and how much to the platform
*/
function _computePremiumSplit(uint premium, uint decimals) public view returns(uint, uint) {
require(decimals <= 78, "_computePremiumSplit(): too many decimals will overflow");
require(decimals >= 3, "_computePremiumSplit(): too few decimals will underflow");
uint platformFeeDoubleScaled = premium.mul(platformFee * (10 ** (decimals - 3)));
uint platformFeeCollected = platformFeeDoubleScaled.div(10 ** (decimals));
uint redeemable = premium.sub(platformFeeCollected);
return (redeemable, platformFeeCollected);
}
/**
* @notice Allows Seller to redeem their premium after the option has been accepted by the buyer
*/
function redeemPremium(uint optionUID) public {
Option storage option = options[optionUID];
// Can only redeem premium once
require(!option.premiumInfo.premiumRedeemed, "redeemPremium(): premium already redeemed");
if(option.cancelled || proposalExpired(optionUID)){
bool isBuyer = option.buyer == msg.sender;
require(isBuyer, "redeemPremium(): only buyer can redeem when proposal expired");
// Track premium redeemed
option.premiumInfo.premiumRedeemed = true;
// Transfer buyer's premium back to themself
EIP20Interface token = EIP20Interface(option.premiumInfo.premiumToken);
bool success = token.transfer(option.buyer, option.premiumInfo.premiumAmt);
require(success, "redeemPremium(): premium transfer failed");
emit BuyerPremiumRefunded(optionUID, msg.sender);
return;
}
// Only the seller may redeem the premium
bool isSeller = option.seller == msg.sender;
require(isSeller, "redeemPremium(): only option seller can redeem");
// Cannot redeem an option that hasn't been accepted
require(option.buyerAccepted && option.sellerAccepted, "redeemPremium(): option hasn't been accepted");
// Track premium redeemed
option.premiumInfo.premiumRedeemed = true;
// Update platform fee balances to include their split of the premium
platformFeeBalances[option.premiumInfo.premiumToken] = platformFeeBalances[option.premiumInfo.premiumToken].add(option.premiumInfo.premiumPlatformFee);
// Transfer seller's premium earned to themself
EIP20Interface token = EIP20Interface(option.premiumInfo.premiumToken);
bool success = token.transfer(option.seller, option.premiumInfo.sellerPremium);
require(success, "redeemPremium(): premium transfer failed");
emit SellerRedeemedPremium(optionUID, msg.sender);
}
/**
* @notice Status for whether time has expired for the option to be executed
*/
function optionExpired(uint optionUID) public view returns(bool) {
Option memory option = options[optionUID];
if (option.optionExpiresAt > now)
return false;
else
return true;
}
/**
* @notice Status for whether time has expired for the option proposal to be accepted
*/
function proposalExpired(uint optionUID) public view returns (bool) {
Option memory option = options[optionUID];
if (option.sellerAccepted && option.buyerAccepted)
return false;
if (option.proposalExpiresAt > now)
return false;
else
return true;
}
/**
* @notice Allow the seller to redeem their underlying if option goes unused (cancelled, proposal expired, option expired)
*/
function redeemUnderlying(uint optionUID) public {
Option storage option = options[optionUID];
// Must be seller to redeem underlying
bool isSeller = option.seller == msg.sender;
require(isSeller, "redeemUnderlying(): only seller may redeem");
require(!option.underlyingInfo.redeemed, "redeemUnderlying(): redeemed, nothing remaining to redeem");
require(!option.executed, "redeemUnderlying(): executed, nothing to redeem");
require(option.cancelled || optionExpired(optionUID) || proposalExpired(optionUID), "redeemUnderlying(): must be cancelled or expired to redeem");
// Mark as redeemed to ensure only gets redeemed once
option.underlyingInfo.redeemed = true;
emit SellerUnderlyingRedeemed(optionUID, msg.sender);
// Transfer underlying back to the seller
EIP20Interface token = EIP20Interface(option.underlyingInfo.underlyingCurrency);
bool success = token.transfer(option.seller, option.underlyingInfo.underlyingAmt);
require(success, "redeemUnderlying(): premium transfer failed");
}
/**
* @notice Allows buyer to transfer ownership of option to another user
*/
function transferSeller(uint optionUID, address newSeller) public {
Option storage option = options[optionUID];
// Only the seller may transfer an option
bool isSeller = option.seller == msg.sender;
require(isSeller, "transferSeller(): must be seller");
// Update option buyer
option.seller = newSeller;
userOptions[newSeller].push(optionUID);
emit TransferSeller(optionUID, msg.sender, newSeller);
}
/**
* @notice Buyer supplies strike amount from strike currency to receive underlying
*/
function execute(uint optionUID) public {
Option storage option = options[optionUID];
// Only the buyer may execute the option
bool isBuyer = option.buyer == msg.sender;
require(isBuyer, "execute(): Must be option owner");
// Nothing to execute w/o both accepting the option
require(option.buyerAccepted && option.sellerAccepted, "execute(): must be a fully accepted option");
// Cannot execute once expired
require(!optionExpired(optionUID), "execute(): option expired");
// Cannot execute more than once
require(!option.executed, "execute(): already executed");
// Mark as executed
option.executed = true;
// 1st Transfer the strike amount from the option buyer
EIP20Interface token = EIP20Interface(option.strikeCurrency);
bool success = token.transferFrom(option.buyer, address(this), option.strikeAmt);
require(success, "execute(): strike transfer failed");
// 2nd Transfer the strike amount to the option seller
success = token.transfer(option.seller, option.strikeAmt);
require(success, "execute(): strike transfer failed");
// 3rd Transfer the underlying to the option buyer
EIP20Interface tokenUnderlying = EIP20Interface(option.underlyingInfo.underlyingCurrency);
success = tokenUnderlying.transfer(option.buyer, option.underlyingInfo.underlyingAmt);
emit OptionExecuted(optionUID);
require(success, "execute(): underlying transfer failed");
}
/**
* @notice If buyer or seller sets status fields and transfers either the premium or underlying
*/
function accept(uint optionUID) public {
Option memory option = options[optionUID];
bool isSeller = option.seller == msg.sender || option.seller == address(0);
bool isBuyer = option.buyer == msg.sender || option.buyer == address(0);
require(isSeller || isBuyer, "accept(): Must either buyer or seller");
if (isBuyer){
_acceptBuyer(optionUID);
}
else if (isSeller) {
_acceptSeller(optionUID);
}
}
/**
* @notice If buyer or seller sets status fields and transfers either the premium or underlying
*/
function cancel(uint optionUID) public {
Option memory option = options[optionUID];
bool isSeller = option.seller == msg.sender;
bool isBuyer = option.buyer == msg.sender;
require(isSeller || isBuyer, "cancel(): only sellers and buyers can cancel");
if (isSeller) {
_cancelSeller(optionUID);
}
else if (isBuyer) {
_cancelBuyer(optionUID);
}
}
/**
* @notice Seller calls cancel before buyer accepts, returns underlying
*/
function _cancelSeller(uint optionUID) internal {
Option memory option = options[optionUID];
require(option.sellerAccepted, "_cancelSeller(): cannot cancel before accepting");
require(!option.buyerAccepted, "_cancelSeller(): already accepted");
require(!option.cancelled, "_cancelSeller(): already cancelled");
// Cancel the option
options[optionUID].cancelled = true;
emit SellerCancelled(optionUID, msg.sender);
// Redeem the underlying
redeemUnderlying(optionUID);
}
/**
* @notice Buyer calls cancel before buyer accepts, returns full premium no fees deducted
*/
function _cancelBuyer(uint optionUID) internal {
Option memory option = options[optionUID];
require(option.buyerAccepted, "_cancelBuyer(): cannot cancel before accepting");
require(!option.sellerAccepted, "_cancelBuyer(): already accepted");
require(!option.cancelled, "already cancelled");
// Cancel the option
options[optionUID].cancelled = true;
emit BuyerCancelled(optionUID, msg.sender);
// Return the buyers premium
redeemPremium(optionUID);
}
/**
* @notice Seller accepts option, transfers underlying amount, if buyer paid premium redeem it
*/
function _acceptSeller(uint optionUID) internal {
Option storage option = options[optionUID];
require(!option.sellerAccepted, "seller already accepted");
// Mark as seller accepted
option.sellerAccepted = true;
// transfer specified tokens
EIP20Interface token = EIP20Interface(option.underlyingInfo.underlyingCurrency);
bool success = token.transferFrom(msg.sender, address(this), option.underlyingInfo.underlyingAmt);
require(success, "_acceptSeller(): Failed to transfer underlying");
// Emit event
emit UnderlyingDeposited(optionUID, msg.sender, option.underlyingInfo.underlyingCurrency, option.underlyingInfo.underlyingAmt);
// If option seller was universal, set it to the sender
if (option.seller == address(0)) {
options[optionUID].seller = msg.sender;
}
userOptions[msg.sender].push(optionUID);
// If buyer already accepted, redeem premium
if (option.buyerAccepted) {
redeemPremium(optionUID);
}
emit SellerAccepted(optionUID, msg.sender);
}
/**
* @notice Buyer accepts option, transfers premium
*/
function _acceptBuyer(uint optionUID) internal {
Option storage option = options[optionUID];
require(!option.buyerAccepted, "buyer already accepted");
// Mark as buyer accepted
option.buyerAccepted = true;
// transfer specified premium
EIP20Interface token = EIP20Interface(option.premiumInfo.premiumToken);
bool success = token.transferFrom(msg.sender, address(this), option.premiumInfo.premiumAmt);
require(success, "Failed to transfer premium");
// If option buyer was universal, set it to the sender
if (option.buyer == address(0)) {
options[optionUID].buyer = msg.sender;
}
userOptions[msg.sender].push(optionUID);
emit PremiumDeposited(optionUID, msg.sender, option.premiumInfo.premiumToken, option.premiumInfo.premiumAmt);
emit BuyerAccepted(optionUID, msg.sender);
}
//------------------------
// Status functions
//------------------------
function canAccept(uint optionUID) public view returns(bool) {
Option memory option = options[optionUID];
return (!option.buyerAccepted || !option.sellerAccepted) && !proposalExpired(optionUID);
}
function canCancel(uint optionUID) public view returns(bool) {
Option memory option = options[optionUID];
return (!option.buyerAccepted || !option.sellerAccepted) && !proposalExpired(optionUID);
}
function canExecute(uint optionUID) public view returns(bool) {
Option memory option = options[optionUID];
return !option.executed && (option.buyerAccepted && option.sellerAccepted) && !optionExpired(optionUID);
}
function canRedeemPremium(uint optionUID) public view returns(bool) {
Option memory option = options[optionUID];
return (option.buyerAccepted && option.sellerAccepted) && !option.premiumInfo.premiumRedeemed;
}
function canRedeemUnderlying(uint optionUID) public view returns(bool) {
Option memory option = options[optionUID];
if (option.cancelled || optionExpired(optionUID) || proposalExpired(optionUID))
return !option.underlyingInfo.redeemed && !option.executed;
else
return false;
}
//------------------------
// NFT Functions
//------------------------
function balanceOf(address _owner) external view returns (uint256) {
uint count = 0;
for(uint i; i< options.length; i++) {
if(options[i].seller == _owner || options[i].buyer == _owner) {
if(options[i].sellerAccepted && options[i].buyerAccepted) {
count += 1;
}
}
}
return count;
}
function totalSupply() public view returns (uint256) {
uint count = 0;
for(uint i; i< options.length; i++) {
if(options[i].sellerAccepted && options[i].buyerAccepted) {
count += 1;
}
}
return count;
}
function baseTokenURI() public view returns (string memory) {
return "https://metadata.optionswap.finance/";
}
function tokenURI(uint256 tokenId) external view returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
// If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI.
return string(abi.encodePacked(baseTokenURI(), tokenId.toString()));
}
function ownerOf(uint256 _tokenId) public view returns (address) {
Option memory option = options[_tokenId];
return option.buyer;
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public {
address owner = ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(msg.sender == owner || isApprovedForAll(owner, msg.sender),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view 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 {
require(operator != msg.sender, "ERC721: approve to caller");
_operatorApprovals[msg.sender][operator] = approved;
emit ApprovalForAll(msg.sender, operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(address from, address to, uint256 tokenId) public {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(msg.sender, 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 {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public {
require(_isApprovedOrOwner(msg.sender, 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 {
_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 returns (bool) {
return options[tokenId].buyer != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev 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 {
require(ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
Option storage option = options[tokenId];
option.buyer = to;
userOptions[to].push(tokenId);
emit Transfer(from, 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
*/
function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data)
private returns (bool)
{
bytes4 _ERC721_RECEIVED = 0x150b7a02;
if (to.isContract()) {
return true;
}
bytes memory returndata = to.functionCall(abi.encodeWithSelector(
IERC721Receiver(to).onERC721Received.selector,
msg.sender,
from,
tokenId,
_data
), "ERC721: transfer to non ERC721Receiver implementer");
bytes4 retval = abi.decode(returndata, (bytes4));
return (retval == _ERC721_RECEIVED);
}
function _approve(address to, uint256 tokenId) private {
_tokenApprovals[tokenId] = to;
emit Approval(ownerOf(tokenId), to, tokenId);
}
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal {}
//------------------------
// Lens functions
//------------------------
// Returns the options data for a given account
function optionsForAccount(address account) public view returns(uint[] memory) {
if (userOptions[account].length == 0) {
uint[] memory blank;
return blank;
}
return userOptions[account];
}
// Returns all the options
function getOptions() public view returns(Option[] memory) {
return options;
}
//------------------------
// Admin functions
//------------------------
// Updates the platform fee, only affects new options created
function __updateFee(uint newPlatformFee) public {
require(msg.sender == admin, "__updateFee(): must be admin");
platformFee = newPlatformFee;
}
function __redeemPlatformFee(uint amount, address tokenAddress) public {
require(msg.sender == admin, "__redeemPlatformFee(): must be admin");
require(platformFeeBalances[tokenAddress] >= amount, "__redeemPlatformFee(): requested redemption too large");
// Update total balance
platformFeeBalances[tokenAddress] = platformFeeBalances[tokenAddress].sub(amount);
// Perform transfer
EIP20Interface token = EIP20Interface(tokenAddress);
bool success = token.transfer(msg.sender, amount);
require(success, "Failed to transfer premium");
}
} | * @notice Compute how much of the premium goes to the seller and how much to the platform/ | function _computePremiumSplit(uint premium, uint decimals) public view returns(uint, uint) {
require(decimals <= 78, "_computePremiumSplit(): too many decimals will overflow");
require(decimals >= 3, "_computePremiumSplit(): too few decimals will underflow");
uint platformFeeDoubleScaled = premium.mul(platformFee * (10 ** (decimals - 3)));
uint platformFeeCollected = platformFeeDoubleScaled.div(10 ** (decimals));
uint redeemable = premium.sub(platformFeeCollected);
return (redeemable, platformFeeCollected);
}
| 6,756,043 | [
1,
7018,
3661,
9816,
434,
326,
23020,
5077,
13998,
358,
326,
29804,
471,
3661,
9816,
358,
326,
4072,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
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,
225,
445,
389,
9200,
23890,
5077,
5521,
12,
11890,
23020,
5077,
16,
2254,
15105,
13,
1071,
1476,
1135,
12,
11890,
16,
2254,
13,
288,
203,
565,
2583,
12,
31734,
1648,
22860,
16,
4192,
9200,
23890,
5077,
5521,
13332,
4885,
4906,
15105,
903,
9391,
8863,
7010,
565,
2583,
12,
31734,
1545,
890,
16,
4192,
9200,
23890,
5077,
5521,
13332,
4885,
11315,
15105,
903,
3613,
2426,
8863,
7010,
565,
2254,
4072,
14667,
5265,
55,
12825,
273,
23020,
5077,
18,
16411,
12,
9898,
14667,
380,
261,
2163,
2826,
261,
31734,
300,
890,
3719,
1769,
203,
377,
203,
565,
2254,
4072,
14667,
10808,
329,
273,
4072,
14667,
5265,
55,
12825,
18,
2892,
12,
2163,
2826,
261,
31734,
10019,
203,
203,
565,
2254,
283,
24903,
429,
273,
23020,
5077,
18,
1717,
12,
9898,
14667,
10808,
329,
1769,
203,
565,
327,
261,
266,
24903,
429,
16,
4072,
14667,
10808,
329,
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
] |
pragma solidity ^0.4.24;
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract Erc20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
* @dev (from OpenZeppelin)
*/
library LibSafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
/**
* @dev Safe a * b / c
*/
function mulDiv(uint256 a, uint256 b, uint256 c) internal pure returns (uint256) {
uint256 d = mul(a, b);
return div(d, c);
}
}
contract OwnedToken {
using LibSafeMath for uint256;
/**
* ERC20 info
*/
string public name = 'Altty';
string public symbol = 'LTT';
uint8 public decimals = 18;
/**
* Allowence list
*/
mapping (address => mapping (address => uint256)) private allowed;
/**
* Count of token at each account
*/
mapping(address => uint256) private shares;
/**
* Total amount
*/
uint256 private shareCount_;
/**
* Owner (main admin)
*/
address public owner = msg.sender;
/**
* List of admins
*/
mapping(address => bool) public isAdmin;
/**
* List of address on hold
*/
mapping(address => bool) public holded;
/**
* Events
*/
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
event Burn(address indexed owner, uint256 amount);
event Mint(address indexed to, uint256 amount);
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Throws if not admin
*/
modifier onlyAdmin() {
require(isAdmin[msg.sender]);
_;
}
/**
* @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)); // if omittet addres, default is 0
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
/**
* Empower/fire admin
*/
function empowerAdmin(address _user) onlyOwner public {
isAdmin[_user] = true;
}
function fireAdmin(address _user) onlyOwner public {
isAdmin[_user] = false;
}
/**
* Hold account
*/
function hold(address _user) onlyOwner public {
holded[_user] = true;
}
/**
* Unhold account
*/
function unhold(address _user) onlyOwner public {
holded[_user] = false;
}
/**
* Edit token info
*/
function setName(string _name) onlyOwner public {
name = _name;
}
function setSymbol(string _symbol) onlyOwner public {
symbol = _symbol;
}
function setDecimals(uint8 _decimals) onlyOwner public {
decimals = _decimals;
}
/**
* @dev total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return shareCount_;
}
/**
* @dev Gets the balance of the specified address
* @param _owner The address to query the the balance of
* @return An uint256 representing the amount owned by the passed address
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return shares[_owner];
}
/**
* @dev Internal transfer tokens from one address to another
* @dev if adress is zero - mint or destroy tokens
* @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 shareTransfer(address _from, address _to, uint256 _value) internal returns (bool) {
require(!holded[_from]);
if(_from == address(0)) {
emit Mint(_to, _value);
shareCount_ =shareCount_.add(_value);
} else {
require(_value <= shares[_from]);
shares[_from] = shares[_from].sub(_value);
}
if(_to == address(0)) {
emit Burn(msg.sender, _value);
shareCount_ =shareCount_.sub(_value);
} else {
shares[_to] =shares[_to].add(_value);
}
emit Transfer(_from, _to, _value);
return true;
}
/**
* @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) {
return shareTransfer(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) public returns (bool) {
require(_value <= allowed[_from][msg.sender]);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
return shareTransfer(_from, _to, _value);
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Withdraw ethereum for a specified address
* @param _to The address to transfer to
* @param _value The amount to be transferred
*/
function withdraw(address _to, uint256 _value) onlyOwner public returns (bool) {
require(_to != address(0));
require(_value <= address(this).balance);
_to.transfer(_value);
return true;
}
/**
* @dev Withdraw token (assets of our contract) for a specified address
* @param token The address of token for transfer
* @param _to The address to transfer to
* @param amount The amount to be transferred
*/
function withdrawToken(address token, address _to, uint256 amount) onlyOwner public returns (bool) {
require(token != address(0));
require(Erc20Basic(token).balanceOf(address(this)) >= amount);
bool transferOk = Erc20Basic(token).transfer(_to, amount);
require(transferOk);
return true;
}
}
contract TenderToken is OwnedToken {
// dividends
uint256 public price = 3 ether / 1000000;
uint256 public sellComission = 2900; // 2.9%
uint256 public buyComission = 2900; // 2.9%
// dividers
uint256 public priceUnits = 1 ether;
uint256 public sellComissionUnits = 100000;
uint256 public buyComissionUnits = 100000;
/**
* Orders structs
*/
struct SellOrder {
address user;
uint256 shareNumber;
}
struct BuyOrder {
address user;
uint256 amountWei;
}
/**
* Current orders list and total amounts in order
*/
SellOrder[] public sellOrder;
BuyOrder[] public buyOrder;
uint256 public sellOrderTotal;
uint256 public buyOrderTotal;
/**
* Magic buy-order create
* NB!!! big gas cost (non standart), see docs
*/
function() public payable {
if(!isAdmin[msg.sender]) {
buyOrder.push(BuyOrder(msg.sender, msg.value));
buyOrderTotal += msg.value;
}
}
/**
* Magic sell-order create
*/
function shareTransfer(address _from, address _to, uint256 _value) internal returns (bool) {
if(_to == address(this)) {
sellOrder.push(SellOrder(msg.sender, _value));
sellOrderTotal += _value;
}
return super.shareTransfer(_from, _to, _value);
}
/**
* Configurate current price/comissions
*/
function setPrice(uint256 _price) onlyAdmin public {
price = _price;
}
function setSellComission(uint _sellComission) onlyOwner public {
sellComission = _sellComission;
}
function setBuyComission(uint _buyComission) onlyOwner public {
buyComission = _buyComission;
}
function setPriceUnits(uint256 _priceUnits) onlyOwner public {
priceUnits = _priceUnits;
}
function setSellComissionUnits(uint _sellComissionUnits) onlyOwner public {
sellComissionUnits = _sellComissionUnits;
}
function setBuyComissionUnits(uint _buyComissionUnits) onlyOwner public {
buyComissionUnits = _buyComissionUnits;
}
/**
* @dev Calculate default price for selected number of shares
* @param shareNumber number of shares
* @return amount
*/
function shareToWei(uint256 shareNumber) public view returns (uint256) {
uint256 amountWei = shareNumber.mulDiv(price, priceUnits);
uint256 comissionWei = amountWei.mulDiv(sellComission, sellComissionUnits);
return amountWei.sub(comissionWei);
}
/**
* @dev Calculate count of shares what can buy with selected amount for default price
* @param amountWei amount for buy share
* @return number of shares
*/
function weiToShare(uint256 amountWei) public view returns (uint256) {
uint256 shareNumber = amountWei.mulDiv(priceUnits, price);
uint256 comissionShare = shareNumber.mulDiv(buyComission, buyComissionUnits);
return shareNumber.sub(comissionShare);
}
/**
* Confirm all buys/sells
*/
function confirmAllBuys() external onlyAdmin {
while(buyOrder.length > 0) {
_confirmOneBuy();
}
}
function confirmAllSells() external onlyAdmin {
while(sellOrder.length > 0) {
_confirmOneSell();
}
}
/**
* Confirm one sell/buy (for problems fix)
*/
function confirmOneBuy() external onlyAdmin {
if(buyOrder.length > 0) {
_confirmOneBuy();
}
}
function confirmOneSell() external onlyAdmin {
_confirmOneSell();
}
/**
* Cancel one sell (for problem fix)
*/
function cancelOneSell() internal {
uint256 i = sellOrder.length-1;
shareTransfer(address(this), sellOrder[i].user, sellOrder[i].shareNumber);
sellOrderTotal -= sellOrder[i].shareNumber;
delete sellOrder[sellOrder.length-1];
sellOrder.length--;
}
/**
* Internal buy/sell
*/
function _confirmOneBuy() internal {
uint256 i = buyOrder.length-1;
uint256 amountWei = buyOrder[i].amountWei;
uint256 shareNumber = weiToShare(amountWei);
address user = buyOrder[i].user;
shareTransfer(address(0), user, shareNumber);
buyOrderTotal -= amountWei;
delete buyOrder[buyOrder.length-1];
buyOrder.length--;
}
function _confirmOneSell() internal {
uint256 i = sellOrder.length-1;
uint256 shareNumber = sellOrder[i].shareNumber;
uint256 amountWei = shareToWei(shareNumber);
address user = sellOrder[i].user;
shareTransfer(address(this), address(0), shareNumber);
sellOrderTotal -= shareNumber;
user.transfer(amountWei);
delete sellOrder[sellOrder.length-1];
sellOrder.length--;
}
} | * @dev Calculate default price for selected number of shares @param shareNumber number of shares @return amount/ | function shareToWei(uint256 shareNumber) public view returns (uint256) {
uint256 amountWei = shareNumber.mulDiv(price, priceUnits);
uint256 comissionWei = amountWei.mulDiv(sellComission, sellComissionUnits);
return amountWei.sub(comissionWei);
}
| 10,301,106 | [
1,
8695,
805,
6205,
364,
3170,
1300,
434,
24123,
225,
7433,
1854,
1300,
434,
24123,
327,
3844,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
7433,
774,
3218,
77,
12,
11890,
5034,
7433,
1854,
13,
1071,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
2254,
5034,
3844,
3218,
77,
273,
7433,
1854,
18,
16411,
7244,
12,
8694,
16,
6205,
7537,
1769,
203,
3639,
2254,
5034,
532,
19710,
3218,
77,
273,
3844,
3218,
77,
18,
16411,
7244,
12,
87,
1165,
799,
19710,
16,
357,
80,
799,
19710,
7537,
1769,
203,
3639,
327,
3844,
3218,
77,
18,
1717,
12,
832,
19710,
3218,
77,
1769,
203,
565,
289,
203,
7010,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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-02-07
*/
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.7;
contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
}
contract ERC20Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor() {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
function owner() public view virtual returns (address) {
return _owner;
}
modifier onlyOwner() {
require(owner() == _msgSender(), "ERC20Ownable: caller is not the owner");
_;
}
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "ERC20Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// 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.
library SafeMath {
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);
}
}
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
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);
}
}
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
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 IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
interface IUniswapV2Router02 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
interface IUniswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
contract SHINIGAMI is Context, IERC20, ERC20Ownable {
using SafeMath for uint256;
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;
mapping(address => bool) private _isMaxWalletExclude;
mapping (address => bool) private _isBot;
mapping(address => bool) public boughtEarly;
address dead = 0x000000000000000000000000000000000000dEaD;
address[] private _excluded;
address payable public marketingAddress;
address payable public giveAwayAddress;
IUniswapV2Router02 private uniV2Router;
address private uniV2Pair;
bool inSwapAndLiquify;
bool private swapAndLiquifyEnabled = true;
bool private _initLaunch = true;
bool private _antiSnipe = false;
bool private _buyLimits = false;
bool private _maxWalletOn = false;
uint256 public tradingActiveBlock = 0;
uint256 public earlyBuyPenaltyEnd;
uint256 private constant MAX = ~uint256(0);
uint256 private constant _tTotal = 1e14 * 10**18;
uint256 private _rTotal = (MAX - (MAX % _tTotal));
uint256 private _tFeeTotal;
uint256 private _maxWalletSize = 2000000000000 * 10**18;
uint256 private minTokensBeforeSwap;
uint256 private tokensForLiquidityToSwap;
uint256 private tokensForMarketingToSwap;
uint256 private tokensForGiveAwayToSwap;
string private constant _nomen = "SHINIGAMI";
string private constant _symbo = "SHINIGAMI";
uint8 private constant _decim = 18;
//DEFAULT PLACE HOLDERS | OVERRIDDEN EACH TXN
uint private _marTax = 6; // tax for marketing
uint private _previousMarTax = _marTax;
uint private _giveAwayTax = 2; // tax for GiveAways
uint private _previousGiveAwayTax = _giveAwayTax;
uint private _liqTax = 3; // tax for liquidity
uint private _previousLiqTax = _liqTax;
uint private _refTax = 0; //tax for reflections
uint private _previousRefTax = _refTax;
uint private _liqDiv = _marTax + _giveAwayTax + _liqTax;
//MAIN TAX VALUES FOR BUY | CHANGEBLE WITH functon setBuyF()
uint private _buyMarTax = 6;
uint private _preBuyMarTax = _buyMarTax;
uint private _buyGiveAwayTax = 2;
uint private _preBuyGiveAwayTax = _buyGiveAwayTax;
uint private _buyLiqTax = 3;
uint private _preBuyLiqTax = _buyLiqTax;
uint private _buyRefTax = 0;
uint private _preBuyRefTax = _buyRefTax;
//MAIN TAX VALUES FOR SELL | CHANGEBLE WITH functon setSellF()
uint private _sellMarTax = 6;
uint private _preSellMarTax = _sellMarTax;
uint private _sellGiveAwayTax = 2;
uint private _preSellGiveAwayTax = _sellGiveAwayTax;
uint private _sellLiqTax = 3;
uint private _preSellLiqTax = _sellLiqTax;
uint private _sellRefTax = 0;
uint private _preSellRefTax = _sellRefTax;
event SwapAndLiquifyEnabledUpdated(bool enabled);
event SwapAndLiquify(uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiqudity);
event UpdatedMarketingAddress(address marketing);
event UpdatedGiveAwayAddress(address giveAwayAddress);
event BoughtEarly(address indexed sniper);
event RemovedSniper(address indexed notsniper);
modifier lockTheSwap() {
inSwapAndLiquify = true;
_;
inSwapAndLiquify = false;
}
constructor() {
_rOwned[_msgSender()] = _rTotal;
marketingAddress = payable(0xAd32B5c3aaA19e6c42FDFF2832Cb47978a4b03CD);
giveAwayAddress = payable(0x625Eee4A87C9743fB94D299eaAa68Fa918b5bf11);
minTokensBeforeSwap = _tTotal.mul(5).div(10000);
_isExcludedFromFee[_msgSender()] = true;
_isExcludedFromFee[address(this)] = true;
_isExcludedFromFee[address(marketingAddress)] = true;
_isExcludedFromFee[address(giveAwayAddress)] = true;
_isMaxWalletExclude[address(this)] = true;
_isMaxWalletExclude[_msgSender()] = true;
_isMaxWalletExclude[address(dead)] = true;
_isMaxWalletExclude[address(marketingAddress)] = true;
_isMaxWalletExclude[address(giveAwayAddress)] = true;
addBot(0x41B0320bEb1563A048e2431c8C1cC155A0DFA967);
addBot(0x91B305F0890Fd0534B66D8d479da6529C35A3eeC);
addBot(0x7F5622afb5CEfbA39f96CA3b2814eCF0E383AAA4);
addBot(0xfcf6a3d7eb8c62a5256a020e48f153c6D5Dd6909);
addBot(0x74BC89a9e831ab5f33b90607Dd9eB5E01452A064);
addBot(0x1F53592C3aA6b827C64C4a3174523182c52Ece84);
addBot(0x460545C01c4246194C2e511F166D84bbC8a07608);
addBot(0x2E5d67a1d15ccCF65152B3A8ec5315E73461fBcd);
addBot(0xb5aF12B837aAf602298B3385640F61a0fF0F4E0d);
addBot(0xEd3e444A30Bd440FBab5933dCCC652959DfCB5Ba);
addBot(0xEC366bbA6266ac8960198075B14FC1D38ea7de88);
addBot(0x10Bf6836600D7cFE1c06b145A8Ac774F8Ba91FDD);
addBot(0x44ae54e28d082C98D53eF5593CE54bB231e565E7);
addBot(0xa3e820006F8553d5AC9F64A2d2B581501eE24FcF);
addBot(0x2228476AC5242e38d5864068B8c6aB61d6bA2222);
addBot(0xcC7e3c4a8208172CA4c4aB8E1b8B4AE775Ebd5a8);
addBot(0x5b3EE79BbBDb5B032eEAA65C689C119748a7192A);
addBot(0x4ddA45d3E9BF453dc95fcD7c783Fe6ff9192d1BA);
addBot(0x0160A15f0f13608F041376a59882Bdd44909b59E);
addBot(0x859E94401bA176A7ab9AAFE5f5dEb52f8D2C76Dc);
addBot(0xD49e21e8380220252D6138790d403af81ADf11F5);
addBot(0xAF00960b562769b5826eFD8D37F2016b5b154FF7);
emit Transfer(address(0), _msgSender(), _tTotal);
}
receive() external payable {}
function name() public pure override returns (string memory) {
return _nomen;
}
function symbol() public pure override returns (string memory) {
return _symbo;
}
function decimals() public pure override returns (uint8) {
return _decim;
}
function totalSupply() public pure override returns (uint256) {
return _tTotal;
}
function balanceOf(address account) public view override returns (uint256) {
if (_isExcluded[account]) return _tOwned[account];
return tokenFromReflection(_rOwned[account]);
}
function transfer(address recipient, uint256 amount) public override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender,address recipient,uint256 amount) public override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender,_msgSender(),
_allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")
);
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(
_msgSender(),
spender,
_allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")
);
return true;
}
function isExcludedFromReward(address account) public view returns (bool) {
return _isExcluded[account];
}
function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns (uint256) {
require(tAmount <= _tTotal, "Amt must be less than supply");
if (!deductTransferFee) {
(uint256 rAmount, , , , , ) = _getValues(tAmount);
return rAmount;
} else {
(, uint256 rTransferAmount, , , , ) = _getValues(tAmount);
return rTransferAmount;
}
}
function tokenFromReflection(uint256 rAmount) public view returns (uint256) {
require(rAmount <= _rTotal, "Amt must be less than tot refl");
uint256 currentRate = _getRate();
return rAmount.div(currentRate);
}
function _reflectFee(uint256 rFee, uint256 tFee) private {
_rTotal = _rTotal.sub(rFee);
_tFeeTotal = _tFeeTotal.add(tFee);
}
function _getValues(uint256 tAmount) private view returns (uint256,uint256,uint256,uint256,uint256,uint256) {
(uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getTValues(tAmount);
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tLiquidity, _getRate());
return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tLiquidity);
}
function _getTValues(uint256 tAmount)private view returns (uint256,uint256,uint256) {
uint256 tFee = calculateTaxFee(tAmount);
uint256 tLiquidity = calculateLiquidityFee(tAmount);
uint256 tTransferAmount = tAmount.sub(tFee).sub(tLiquidity);
return (tTransferAmount, tFee, tLiquidity);
}
function _getRValues(uint256 tAmount,uint256 tFee,uint256 tLiquidity,uint256 currentRate) private pure returns (uint256,uint256,uint256) {
uint256 rAmount = tAmount.mul(currentRate);
uint256 rFee = tFee.mul(currentRate);
uint256 rLiquidity = tLiquidity.mul(currentRate);
uint256 rTransferAmount = rAmount.sub(rFee).sub(rLiquidity);
return (rAmount, rTransferAmount, rFee);
}
function _getRate() private view returns (uint256) {
(uint256 rSupply, uint256 tSupply) = _getCurrentSupply();
return rSupply.div(tSupply);
}
function _getCurrentSupply() private view returns (uint256, uint256) {
uint256 rSupply = _rTotal;
uint256 tSupply = _tTotal;
for (uint256 i = 0; i < _excluded.length; i++) {
if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal);
rSupply = rSupply.sub(_rOwned[_excluded[i]]);
tSupply = tSupply.sub(_tOwned[_excluded[i]]);
}
if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal);
return (rSupply, tSupply);
}
function _takeLiquidity(uint256 tLiquidity) private {
tokensForMarketingToSwap += tLiquidity * _marTax / _liqDiv;
tokensForLiquidityToSwap += tLiquidity * _liqTax / _liqDiv;
tokensForGiveAwayToSwap += tLiquidity * _giveAwayTax / _liqDiv;
uint256 currentRate = _getRate();
uint256 rLiquidity = tLiquidity.mul(currentRate);
_rOwned[address(this)] = _rOwned[address(this)].add(rLiquidity);
if (_isExcluded[address(this)]) _tOwned[address(this)] = _tOwned[address(this)].add(tLiquidity);
}
function calculateTaxFee(uint256 _amount) private view returns (uint256) {
return _amount.mul(_refTax).div(10**2);
}
function calculateLiquidityFee(uint256 _amount) private view returns (uint256) {
return _amount.mul(_marTax + _giveAwayTax + _liqTax).div(10**2);
}
function removeAllFee() private {
if (_refTax == 0 && _liqTax == 0 && _marTax == 0 && _giveAwayTax == 0) return;
_previousRefTax = _refTax;
_previousLiqTax = _liqTax;
_previousMarTax = _marTax;
_previousGiveAwayTax = _giveAwayTax;
_refTax = 0;
_liqTax = 0;
_marTax = 0;
_giveAwayTax = 0;
}
function restoreAllFee() private {
_refTax = _previousRefTax;
_liqTax = _previousLiqTax;
_marTax = _previousMarTax;
_giveAwayTax = _previousGiveAwayTax;
}
function excludeFromFee(address account) public onlyOwner {
_isExcludedFromFee[account] = true;
}
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 zero address");
require(spender != address(0), "ERC20: approve to 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 zero address");
require(to != address(0), "ERC20: transfer to zero address");
require(amount > 0, "Transfer amount must be greater than zero");
require(!_isBot[from]);
require(!boughtEarly[from] || earlyBuyPenaltyEnd <= block.timestamp, "Snipers can't transfer tokens to sell cheaper DM a Mod.");
if (_maxWalletOn == true && ! _isMaxWalletExclude[to]) {
require(balanceOf(to) + amount <= _maxWalletSize, "Max amount of tokens for wallet reached");
}
if (_buyLimits == true && from == uniV2Pair) {
require(amount <= 500000000000 * 10**18, "Limits are in place, please lower buying amount");
}
if(_initLaunch == true) {
IUniswapV2Router02 _uniV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
uniV2Router = _uniV2Router;
uniV2Pair = IUniswapV2Factory(_uniV2Router.factory()).getPair(address(this), _uniV2Router.WETH());
tradingActiveBlock = block.number;
earlyBuyPenaltyEnd = block.timestamp + 72 hours;
_isMaxWalletExclude[address(uniV2Pair)] = true;
_isMaxWalletExclude[address(uniV2Router)] = true;
_buyLimits = true;
_maxWalletOn = true;
_antiSnipe = true;
_initLaunch = false;
}
if(_antiSnipe == true && from != owner() && to != uniV2Pair) {
for (uint x = 0; x < 2; x++) {
if(block.number == tradingActiveBlock + x) {
boughtEarly[to] = true;
emit BoughtEarly(to);
}
if(x >= 2){
_antiSnipe = false;
}
}
}
if (to == uniV2Pair) {
_marTax = _sellMarTax;
_giveAwayTax = _sellGiveAwayTax;
_liqTax = _sellLiqTax;
_refTax = _sellRefTax;
} else if (from == uniV2Pair) {
_marTax = _buyMarTax;
_giveAwayTax = _buyGiveAwayTax;
_liqTax = _buyLiqTax;
_refTax = _buyRefTax;
}
uint256 contractTokenBalance = balanceOf(address(this));
if (!inSwapAndLiquify && to == uniV2Pair && swapAndLiquifyEnabled) {
if (contractTokenBalance >= minTokensBeforeSwap) {
swapTokens();
}
}
bool takeFee = true;
if (_isExcludedFromFee[from] || _isExcludedFromFee[to]) {
takeFee = false;
}
if(boughtEarly[from] && earlyBuyPenaltyEnd > block.timestamp){
_liqTax = 0;
_marTax = 95;
_giveAwayTax = 0;
_refTax = 0;
}
_tokenTransfer(from, to, amount, takeFee);
}
function swapETHForTokens(uint256 amount) private {
// generate the uniswap pair path of token -> weth
address[] memory path = new address[](2);
path[0] = uniV2Router.WETH();
path[1] = address(this);
// make the swap
uniV2Router.swapExactETHForTokensSupportingFeeOnTransferTokens{value: amount}(
0, // accept any amount of Tokens
path,
dead, // Burn address
block.timestamp.add(300)
);
}
function addBot(address _user) public onlyOwner {
require(_user != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
require(!_isBot[_user]);
_isBot[_user] = true;
}
function removeBot(address _user) public onlyOwner {
require(_isBot[_user]);
_isBot[_user] = false;
}
function removeSniper(address account) external onlyOwner {
boughtEarly[account] = false;
emit RemovedSniper(account);
}
function swapTokens() private lockTheSwap {
uint256 contractBalance = balanceOf(address(this));
uint256 totalTokensToSwap = tokensForLiquidityToSwap + tokensForMarketingToSwap + tokensForGiveAwayToSwap;
uint256 tokensForLiquidity = tokensForLiquidityToSwap.div(2); //Halve the amount of liquidity tokens
uint256 amountToSwapForETH = contractBalance.sub(tokensForLiquidity);
uint256 initialETHBalance = address(this).balance;
swapTokensForETH(amountToSwapForETH);
uint256 ethBalance = address(this).balance.sub(initialETHBalance);
uint256 ethForMarketing = ethBalance.mul(tokensForMarketingToSwap).div(totalTokensToSwap);
uint256 ethForGiveAway = ethBalance.mul(tokensForGiveAwayToSwap).div(totalTokensToSwap);
uint256 ethForLiquidity = ethBalance.sub(ethForMarketing).sub(ethForGiveAway);
tokensForLiquidityToSwap = 0;
tokensForMarketingToSwap = 0;
tokensForGiveAwayToSwap = 0;
(bool success,) = address(marketingAddress).call{value: ethForMarketing}("");
(success,) = address(giveAwayAddress).call{value: ethForGiveAway}("");
addLiquidity(tokensForLiquidity, ethForLiquidity);
emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, tokensForLiquidity);
//If any eth left over transfer out of contract as to not get stuck
if(address(this).balance > 0 * 10**18){
(success,) = address(marketingAddress).call{value: address(this).balance}("");
}
}
function swapTokensForETH(uint256 tokenAmount) private {
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniV2Router.WETH();
_approve(address(this), address(uniV2Router), tokenAmount);
uniV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0, // accept any amount of ETH
path,
address(this),
block.timestamp.add(300)
);
}
function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private {
_approve(address(this), address(uniV2Router), tokenAmount);
uniV2Router.addLiquidityETH{value: ethAmount}(
address(this),
tokenAmount,
0, // slippage is unavoidable
0, // slippage is unavoidable
dead,
block.timestamp.add(300)
);
}
function setMarketingAddress(address _marketingAddress) external onlyOwner {
require(_marketingAddress != address(0));
_isExcludedFromFee[marketingAddress] = false;
marketingAddress = payable(_marketingAddress);
_isExcludedFromFee[marketingAddress] = true;
emit UpdatedMarketingAddress(_marketingAddress);
}
function setGiveAwayAddress(address _giveAwayAddress) public onlyOwner {
require(_giveAwayAddress != address(0));
giveAwayAddress = payable(_giveAwayAddress);
emit UpdatedGiveAwayAddress(_giveAwayAddress);
}
function StartLaunchInit() external onlyOwner {
_initLaunch = true;
}
function StopLaunchInit() external onlyOwner {
_initLaunch = false;
}
function TaxSwapEnable() external onlyOwner {
swapAndLiquifyEnabled = true;
}
function TaxSwapDisable() external onlyOwner {
swapAndLiquifyEnabled = false;
}
function ResumeLimits() external onlyOwner {
_buyLimits = true;
}
function RemoveLimits() external onlyOwner {
_buyLimits = false;
}
function MaxWalletOn() external onlyOwner {
_maxWalletOn = true;
}
function MaxWalletOff() external onlyOwner {
_maxWalletOn = false;
}
function setBuyF(uint buyMarTax, uint buyGiveAwayTax, uint buyLiqTax, uint buyRefTax) external onlyOwner {
_buyMarTax = buyMarTax;
_buyGiveAwayTax = buyGiveAwayTax;
_buyLiqTax = buyLiqTax;
_buyRefTax = buyRefTax;
}
function setSellF(uint sellMarTax, uint sellGiveAwayTax, uint sellLiqTax, uint sellRefTax) external onlyOwner {
_sellMarTax = sellMarTax;
_sellGiveAwayTax = sellGiveAwayTax;
_sellLiqTax = sellLiqTax;
_sellRefTax = sellRefTax;
}
function startAntiSniper() external onlyOwner {
_antiSnipe = true;
}
function stopAntiSniper() external onlyOwner {
_antiSnipe = false;
}
function HappyHour() external onlyOwner {
_preBuyMarTax = _buyMarTax;
_preBuyGiveAwayTax = _buyGiveAwayTax;
_preBuyLiqTax = _buyLiqTax;
_preBuyRefTax = _buyRefTax;
_preSellMarTax = _sellMarTax;
_preSellGiveAwayTax = _sellGiveAwayTax;
_preSellLiqTax = _sellLiqTax;
_preSellRefTax = _sellRefTax;
_buyMarTax = 0;
_buyGiveAwayTax = 0;
_buyLiqTax = 0;
_buyRefTax = 0;
_sellMarTax = 0;
_sellGiveAwayTax = 0;
_sellLiqTax = 0;
_sellRefTax = 0;
}
function HappyHourOff() external onlyOwner {
_buyMarTax = _preBuyMarTax;
_buyGiveAwayTax = _preBuyGiveAwayTax;
_buyLiqTax = _preBuyLiqTax;
_buyRefTax = _preBuyRefTax;
_sellMarTax = _preSellMarTax;
_sellGiveAwayTax = _preSellGiveAwayTax;
_sellLiqTax = _preSellLiqTax;
_sellRefTax = _preSellRefTax;
}
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);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(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);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(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);
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeLiquidity(tLiquidity);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferBothExcluded(address sender,address recipient,uint256 tAmount) private {
(
uint256 rAmount,
uint256 rTransferAmount,
uint256 rFee,
uint256 tTransferAmount,
uint256 tFee,
uint256 tLiquidity
) = _getValues(tAmount);
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeLiquidity(tLiquidity);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _tokenTransferNoFee(address sender,address recipient,uint256 amount) private {
_rOwned[sender] = _rOwned[sender].sub(amount);
_rOwned[recipient] = _rOwned[recipient].add(amount);
if (_isExcluded[sender]) {
_tOwned[sender] = _tOwned[sender].sub(amount);
}
if (_isExcluded[recipient]) {
_tOwned[recipient] = _tOwned[recipient].add(amount);
}
emit Transfer(sender, recipient, amount);
}
} | DEFAULT PLACE HOLDERS | OVERRIDDEN EACH TXNMAIN TAX VALUES FOR BUY | CHANGEBLE WITH functon setBuyF()MAIN TAX VALUES FOR SELL | CHANGEBLE WITH functon setSellF() | contract SHINIGAMI is Context, IERC20, ERC20Ownable {
using SafeMath for uint256;
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;
mapping(address => bool) private _isMaxWalletExclude;
mapping (address => bool) private _isBot;
mapping(address => bool) public boughtEarly;
address dead = 0x000000000000000000000000000000000000dEaD;
address[] private _excluded;
address payable public marketingAddress;
address payable public giveAwayAddress;
IUniswapV2Router02 private uniV2Router;
address private uniV2Pair;
bool inSwapAndLiquify;
bool private swapAndLiquifyEnabled = true;
bool private _initLaunch = true;
bool private _antiSnipe = false;
bool private _buyLimits = false;
bool private _maxWalletOn = false;
uint256 public tradingActiveBlock = 0;
uint256 public earlyBuyPenaltyEnd;
uint256 private constant MAX = ~uint256(0);
uint256 private constant _tTotal = 1e14 * 10**18;
uint256 private _rTotal = (MAX - (MAX % _tTotal));
uint256 private _tFeeTotal;
uint256 private _maxWalletSize = 2000000000000 * 10**18;
uint256 private minTokensBeforeSwap;
uint256 private tokensForLiquidityToSwap;
uint256 private tokensForMarketingToSwap;
uint256 private tokensForGiveAwayToSwap;
string private constant _nomen = "SHINIGAMI";
string private constant _symbo = "SHINIGAMI";
uint8 private constant _decim = 18;
uint private _previousMarTax = _marTax;
uint private _previousGiveAwayTax = _giveAwayTax;
uint private _previousLiqTax = _liqTax;
uint private _previousRefTax = _refTax;
uint private _liqDiv = _marTax + _giveAwayTax + _liqTax;
uint private _buyMarTax = 6;
uint private _preBuyMarTax = _buyMarTax;
uint private _buyGiveAwayTax = 2;
uint private _preBuyGiveAwayTax = _buyGiveAwayTax;
uint private _buyLiqTax = 3;
uint private _preBuyLiqTax = _buyLiqTax;
uint private _buyRefTax = 0;
uint private _preBuyRefTax = _buyRefTax;
uint private _sellMarTax = 6;
uint private _preSellMarTax = _sellMarTax;
uint private _sellGiveAwayTax = 2;
uint private _preSellGiveAwayTax = _sellGiveAwayTax;
uint private _sellLiqTax = 3;
uint private _preSellLiqTax = _sellLiqTax;
uint private _sellRefTax = 0;
uint private _preSellRefTax = _sellRefTax;
event SwapAndLiquifyEnabledUpdated(bool enabled);
event SwapAndLiquify(uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiqudity);
event UpdatedMarketingAddress(address marketing);
event UpdatedGiveAwayAddress(address giveAwayAddress);
event BoughtEarly(address indexed sniper);
event RemovedSniper(address indexed notsniper);
modifier lockTheSwap() {
inSwapAndLiquify = true;
_;
inSwapAndLiquify = false;
}
constructor() {
_rOwned[_msgSender()] = _rTotal;
marketingAddress = payable(0xAd32B5c3aaA19e6c42FDFF2832Cb47978a4b03CD);
giveAwayAddress = payable(0x625Eee4A87C9743fB94D299eaAa68Fa918b5bf11);
minTokensBeforeSwap = _tTotal.mul(5).div(10000);
_isExcludedFromFee[_msgSender()] = true;
_isExcludedFromFee[address(this)] = true;
_isExcludedFromFee[address(marketingAddress)] = true;
_isExcludedFromFee[address(giveAwayAddress)] = true;
_isMaxWalletExclude[address(this)] = true;
_isMaxWalletExclude[_msgSender()] = true;
_isMaxWalletExclude[address(dead)] = true;
_isMaxWalletExclude[address(marketingAddress)] = true;
_isMaxWalletExclude[address(giveAwayAddress)] = true;
addBot(0x41B0320bEb1563A048e2431c8C1cC155A0DFA967);
addBot(0x91B305F0890Fd0534B66D8d479da6529C35A3eeC);
addBot(0x7F5622afb5CEfbA39f96CA3b2814eCF0E383AAA4);
addBot(0xfcf6a3d7eb8c62a5256a020e48f153c6D5Dd6909);
addBot(0x74BC89a9e831ab5f33b90607Dd9eB5E01452A064);
addBot(0x1F53592C3aA6b827C64C4a3174523182c52Ece84);
addBot(0x460545C01c4246194C2e511F166D84bbC8a07608);
addBot(0x2E5d67a1d15ccCF65152B3A8ec5315E73461fBcd);
addBot(0xb5aF12B837aAf602298B3385640F61a0fF0F4E0d);
addBot(0xEd3e444A30Bd440FBab5933dCCC652959DfCB5Ba);
addBot(0xEC366bbA6266ac8960198075B14FC1D38ea7de88);
addBot(0x10Bf6836600D7cFE1c06b145A8Ac774F8Ba91FDD);
addBot(0x44ae54e28d082C98D53eF5593CE54bB231e565E7);
addBot(0xa3e820006F8553d5AC9F64A2d2B581501eE24FcF);
addBot(0x2228476AC5242e38d5864068B8c6aB61d6bA2222);
addBot(0xcC7e3c4a8208172CA4c4aB8E1b8B4AE775Ebd5a8);
addBot(0x5b3EE79BbBDb5B032eEAA65C689C119748a7192A);
addBot(0x4ddA45d3E9BF453dc95fcD7c783Fe6ff9192d1BA);
addBot(0x0160A15f0f13608F041376a59882Bdd44909b59E);
addBot(0x859E94401bA176A7ab9AAFE5f5dEb52f8D2C76Dc);
addBot(0xD49e21e8380220252D6138790d403af81ADf11F5);
addBot(0xAF00960b562769b5826eFD8D37F2016b5b154FF7);
emit Transfer(address(0), _msgSender(), _tTotal);
}
receive() external payable {}
function name() public pure override returns (string memory) {
return _nomen;
}
function symbol() public pure override returns (string memory) {
return _symbo;
}
function decimals() public pure override returns (uint8) {
return _decim;
}
function totalSupply() public pure override returns (uint256) {
return _tTotal;
}
function balanceOf(address account) public view override returns (uint256) {
if (_isExcluded[account]) return _tOwned[account];
return tokenFromReflection(_rOwned[account]);
}
function transfer(address recipient, uint256 amount) public override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender,address recipient,uint256 amount) public override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender,_msgSender(),
_allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")
);
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(
_msgSender(),
spender,
_allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")
);
return true;
}
function isExcludedFromReward(address account) public view returns (bool) {
return _isExcluded[account];
}
function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns (uint256) {
require(tAmount <= _tTotal, "Amt must be less than supply");
if (!deductTransferFee) {
(uint256 rAmount, , , , , ) = _getValues(tAmount);
return rAmount;
(, uint256 rTransferAmount, , , , ) = _getValues(tAmount);
return rTransferAmount;
}
}
function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns (uint256) {
require(tAmount <= _tTotal, "Amt must be less than supply");
if (!deductTransferFee) {
(uint256 rAmount, , , , , ) = _getValues(tAmount);
return rAmount;
(, uint256 rTransferAmount, , , , ) = _getValues(tAmount);
return rTransferAmount;
}
}
} else {
function tokenFromReflection(uint256 rAmount) public view returns (uint256) {
require(rAmount <= _rTotal, "Amt must be less than tot refl");
uint256 currentRate = _getRate();
return rAmount.div(currentRate);
}
function _reflectFee(uint256 rFee, uint256 tFee) private {
_rTotal = _rTotal.sub(rFee);
_tFeeTotal = _tFeeTotal.add(tFee);
}
function _getValues(uint256 tAmount) private view returns (uint256,uint256,uint256,uint256,uint256,uint256) {
(uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getTValues(tAmount);
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tLiquidity, _getRate());
return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tLiquidity);
}
function _getTValues(uint256 tAmount)private view returns (uint256,uint256,uint256) {
uint256 tFee = calculateTaxFee(tAmount);
uint256 tLiquidity = calculateLiquidityFee(tAmount);
uint256 tTransferAmount = tAmount.sub(tFee).sub(tLiquidity);
return (tTransferAmount, tFee, tLiquidity);
}
function _getRValues(uint256 tAmount,uint256 tFee,uint256 tLiquidity,uint256 currentRate) private pure returns (uint256,uint256,uint256) {
uint256 rAmount = tAmount.mul(currentRate);
uint256 rFee = tFee.mul(currentRate);
uint256 rLiquidity = tLiquidity.mul(currentRate);
uint256 rTransferAmount = rAmount.sub(rFee).sub(rLiquidity);
return (rAmount, rTransferAmount, rFee);
}
function _getRate() private view returns (uint256) {
(uint256 rSupply, uint256 tSupply) = _getCurrentSupply();
return rSupply.div(tSupply);
}
function _getCurrentSupply() private view returns (uint256, uint256) {
uint256 rSupply = _rTotal;
uint256 tSupply = _tTotal;
for (uint256 i = 0; i < _excluded.length; i++) {
if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal);
rSupply = rSupply.sub(_rOwned[_excluded[i]]);
tSupply = tSupply.sub(_tOwned[_excluded[i]]);
}
if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal);
return (rSupply, tSupply);
}
function _getCurrentSupply() private view returns (uint256, uint256) {
uint256 rSupply = _rTotal;
uint256 tSupply = _tTotal;
for (uint256 i = 0; i < _excluded.length; i++) {
if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal);
rSupply = rSupply.sub(_rOwned[_excluded[i]]);
tSupply = tSupply.sub(_tOwned[_excluded[i]]);
}
if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal);
return (rSupply, tSupply);
}
function _takeLiquidity(uint256 tLiquidity) private {
tokensForMarketingToSwap += tLiquidity * _marTax / _liqDiv;
tokensForLiquidityToSwap += tLiquidity * _liqTax / _liqDiv;
tokensForGiveAwayToSwap += tLiquidity * _giveAwayTax / _liqDiv;
uint256 currentRate = _getRate();
uint256 rLiquidity = tLiquidity.mul(currentRate);
_rOwned[address(this)] = _rOwned[address(this)].add(rLiquidity);
if (_isExcluded[address(this)]) _tOwned[address(this)] = _tOwned[address(this)].add(tLiquidity);
}
function calculateTaxFee(uint256 _amount) private view returns (uint256) {
return _amount.mul(_refTax).div(10**2);
}
function calculateLiquidityFee(uint256 _amount) private view returns (uint256) {
return _amount.mul(_marTax + _giveAwayTax + _liqTax).div(10**2);
}
function removeAllFee() private {
if (_refTax == 0 && _liqTax == 0 && _marTax == 0 && _giveAwayTax == 0) return;
_previousRefTax = _refTax;
_previousLiqTax = _liqTax;
_previousMarTax = _marTax;
_previousGiveAwayTax = _giveAwayTax;
_refTax = 0;
_liqTax = 0;
_marTax = 0;
_giveAwayTax = 0;
}
function restoreAllFee() private {
_refTax = _previousRefTax;
_liqTax = _previousLiqTax;
_marTax = _previousMarTax;
_giveAwayTax = _previousGiveAwayTax;
}
function excludeFromFee(address account) public onlyOwner {
_isExcludedFromFee[account] = true;
}
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 zero address");
require(spender != address(0), "ERC20: approve to 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 zero address");
require(to != address(0), "ERC20: transfer to zero address");
require(amount > 0, "Transfer amount must be greater than zero");
require(!_isBot[from]);
require(!boughtEarly[from] || earlyBuyPenaltyEnd <= block.timestamp, "Snipers can't transfer tokens to sell cheaper DM a Mod.");
if (_maxWalletOn == true && ! _isMaxWalletExclude[to]) {
require(balanceOf(to) + amount <= _maxWalletSize, "Max amount of tokens for wallet reached");
}
if (_buyLimits == true && from == uniV2Pair) {
require(amount <= 500000000000 * 10**18, "Limits are in place, please lower buying amount");
}
if(_initLaunch == true) {
IUniswapV2Router02 _uniV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
uniV2Router = _uniV2Router;
uniV2Pair = IUniswapV2Factory(_uniV2Router.factory()).getPair(address(this), _uniV2Router.WETH());
tradingActiveBlock = block.number;
earlyBuyPenaltyEnd = block.timestamp + 72 hours;
_isMaxWalletExclude[address(uniV2Pair)] = true;
_isMaxWalletExclude[address(uniV2Router)] = true;
_buyLimits = true;
_maxWalletOn = true;
_antiSnipe = true;
_initLaunch = false;
}
if(_antiSnipe == true && from != owner() && to != uniV2Pair) {
for (uint x = 0; x < 2; x++) {
if(block.number == tradingActiveBlock + x) {
boughtEarly[to] = true;
emit BoughtEarly(to);
}
if(x >= 2){
_antiSnipe = false;
}
}
}
if (to == uniV2Pair) {
_marTax = _sellMarTax;
_giveAwayTax = _sellGiveAwayTax;
_liqTax = _sellLiqTax;
_refTax = _sellRefTax;
_marTax = _buyMarTax;
_giveAwayTax = _buyGiveAwayTax;
_liqTax = _buyLiqTax;
_refTax = _buyRefTax;
}
uint256 contractTokenBalance = balanceOf(address(this));
if (!inSwapAndLiquify && to == uniV2Pair && swapAndLiquifyEnabled) {
if (contractTokenBalance >= minTokensBeforeSwap) {
swapTokens();
}
}
bool takeFee = true;
if (_isExcludedFromFee[from] || _isExcludedFromFee[to]) {
takeFee = false;
}
if(boughtEarly[from] && earlyBuyPenaltyEnd > block.timestamp){
_liqTax = 0;
_marTax = 95;
_giveAwayTax = 0;
_refTax = 0;
}
_tokenTransfer(from, to, amount, takeFee);
}
function _transfer(address from,address to,uint256 amount) private {
require(from != address(0), "ERC20: transfer from zero address");
require(to != address(0), "ERC20: transfer to zero address");
require(amount > 0, "Transfer amount must be greater than zero");
require(!_isBot[from]);
require(!boughtEarly[from] || earlyBuyPenaltyEnd <= block.timestamp, "Snipers can't transfer tokens to sell cheaper DM a Mod.");
if (_maxWalletOn == true && ! _isMaxWalletExclude[to]) {
require(balanceOf(to) + amount <= _maxWalletSize, "Max amount of tokens for wallet reached");
}
if (_buyLimits == true && from == uniV2Pair) {
require(amount <= 500000000000 * 10**18, "Limits are in place, please lower buying amount");
}
if(_initLaunch == true) {
IUniswapV2Router02 _uniV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
uniV2Router = _uniV2Router;
uniV2Pair = IUniswapV2Factory(_uniV2Router.factory()).getPair(address(this), _uniV2Router.WETH());
tradingActiveBlock = block.number;
earlyBuyPenaltyEnd = block.timestamp + 72 hours;
_isMaxWalletExclude[address(uniV2Pair)] = true;
_isMaxWalletExclude[address(uniV2Router)] = true;
_buyLimits = true;
_maxWalletOn = true;
_antiSnipe = true;
_initLaunch = false;
}
if(_antiSnipe == true && from != owner() && to != uniV2Pair) {
for (uint x = 0; x < 2; x++) {
if(block.number == tradingActiveBlock + x) {
boughtEarly[to] = true;
emit BoughtEarly(to);
}
if(x >= 2){
_antiSnipe = false;
}
}
}
if (to == uniV2Pair) {
_marTax = _sellMarTax;
_giveAwayTax = _sellGiveAwayTax;
_liqTax = _sellLiqTax;
_refTax = _sellRefTax;
_marTax = _buyMarTax;
_giveAwayTax = _buyGiveAwayTax;
_liqTax = _buyLiqTax;
_refTax = _buyRefTax;
}
uint256 contractTokenBalance = balanceOf(address(this));
if (!inSwapAndLiquify && to == uniV2Pair && swapAndLiquifyEnabled) {
if (contractTokenBalance >= minTokensBeforeSwap) {
swapTokens();
}
}
bool takeFee = true;
if (_isExcludedFromFee[from] || _isExcludedFromFee[to]) {
takeFee = false;
}
if(boughtEarly[from] && earlyBuyPenaltyEnd > block.timestamp){
_liqTax = 0;
_marTax = 95;
_giveAwayTax = 0;
_refTax = 0;
}
_tokenTransfer(from, to, amount, takeFee);
}
function _transfer(address from,address to,uint256 amount) private {
require(from != address(0), "ERC20: transfer from zero address");
require(to != address(0), "ERC20: transfer to zero address");
require(amount > 0, "Transfer amount must be greater than zero");
require(!_isBot[from]);
require(!boughtEarly[from] || earlyBuyPenaltyEnd <= block.timestamp, "Snipers can't transfer tokens to sell cheaper DM a Mod.");
if (_maxWalletOn == true && ! _isMaxWalletExclude[to]) {
require(balanceOf(to) + amount <= _maxWalletSize, "Max amount of tokens for wallet reached");
}
if (_buyLimits == true && from == uniV2Pair) {
require(amount <= 500000000000 * 10**18, "Limits are in place, please lower buying amount");
}
if(_initLaunch == true) {
IUniswapV2Router02 _uniV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
uniV2Router = _uniV2Router;
uniV2Pair = IUniswapV2Factory(_uniV2Router.factory()).getPair(address(this), _uniV2Router.WETH());
tradingActiveBlock = block.number;
earlyBuyPenaltyEnd = block.timestamp + 72 hours;
_isMaxWalletExclude[address(uniV2Pair)] = true;
_isMaxWalletExclude[address(uniV2Router)] = true;
_buyLimits = true;
_maxWalletOn = true;
_antiSnipe = true;
_initLaunch = false;
}
if(_antiSnipe == true && from != owner() && to != uniV2Pair) {
for (uint x = 0; x < 2; x++) {
if(block.number == tradingActiveBlock + x) {
boughtEarly[to] = true;
emit BoughtEarly(to);
}
if(x >= 2){
_antiSnipe = false;
}
}
}
if (to == uniV2Pair) {
_marTax = _sellMarTax;
_giveAwayTax = _sellGiveAwayTax;
_liqTax = _sellLiqTax;
_refTax = _sellRefTax;
_marTax = _buyMarTax;
_giveAwayTax = _buyGiveAwayTax;
_liqTax = _buyLiqTax;
_refTax = _buyRefTax;
}
uint256 contractTokenBalance = balanceOf(address(this));
if (!inSwapAndLiquify && to == uniV2Pair && swapAndLiquifyEnabled) {
if (contractTokenBalance >= minTokensBeforeSwap) {
swapTokens();
}
}
bool takeFee = true;
if (_isExcludedFromFee[from] || _isExcludedFromFee[to]) {
takeFee = false;
}
if(boughtEarly[from] && earlyBuyPenaltyEnd > block.timestamp){
_liqTax = 0;
_marTax = 95;
_giveAwayTax = 0;
_refTax = 0;
}
_tokenTransfer(from, to, amount, takeFee);
}
function _transfer(address from,address to,uint256 amount) private {
require(from != address(0), "ERC20: transfer from zero address");
require(to != address(0), "ERC20: transfer to zero address");
require(amount > 0, "Transfer amount must be greater than zero");
require(!_isBot[from]);
require(!boughtEarly[from] || earlyBuyPenaltyEnd <= block.timestamp, "Snipers can't transfer tokens to sell cheaper DM a Mod.");
if (_maxWalletOn == true && ! _isMaxWalletExclude[to]) {
require(balanceOf(to) + amount <= _maxWalletSize, "Max amount of tokens for wallet reached");
}
if (_buyLimits == true && from == uniV2Pair) {
require(amount <= 500000000000 * 10**18, "Limits are in place, please lower buying amount");
}
if(_initLaunch == true) {
IUniswapV2Router02 _uniV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
uniV2Router = _uniV2Router;
uniV2Pair = IUniswapV2Factory(_uniV2Router.factory()).getPair(address(this), _uniV2Router.WETH());
tradingActiveBlock = block.number;
earlyBuyPenaltyEnd = block.timestamp + 72 hours;
_isMaxWalletExclude[address(uniV2Pair)] = true;
_isMaxWalletExclude[address(uniV2Router)] = true;
_buyLimits = true;
_maxWalletOn = true;
_antiSnipe = true;
_initLaunch = false;
}
if(_antiSnipe == true && from != owner() && to != uniV2Pair) {
for (uint x = 0; x < 2; x++) {
if(block.number == tradingActiveBlock + x) {
boughtEarly[to] = true;
emit BoughtEarly(to);
}
if(x >= 2){
_antiSnipe = false;
}
}
}
if (to == uniV2Pair) {
_marTax = _sellMarTax;
_giveAwayTax = _sellGiveAwayTax;
_liqTax = _sellLiqTax;
_refTax = _sellRefTax;
_marTax = _buyMarTax;
_giveAwayTax = _buyGiveAwayTax;
_liqTax = _buyLiqTax;
_refTax = _buyRefTax;
}
uint256 contractTokenBalance = balanceOf(address(this));
if (!inSwapAndLiquify && to == uniV2Pair && swapAndLiquifyEnabled) {
if (contractTokenBalance >= minTokensBeforeSwap) {
swapTokens();
}
}
bool takeFee = true;
if (_isExcludedFromFee[from] || _isExcludedFromFee[to]) {
takeFee = false;
}
if(boughtEarly[from] && earlyBuyPenaltyEnd > block.timestamp){
_liqTax = 0;
_marTax = 95;
_giveAwayTax = 0;
_refTax = 0;
}
_tokenTransfer(from, to, amount, takeFee);
}
function _transfer(address from,address to,uint256 amount) private {
require(from != address(0), "ERC20: transfer from zero address");
require(to != address(0), "ERC20: transfer to zero address");
require(amount > 0, "Transfer amount must be greater than zero");
require(!_isBot[from]);
require(!boughtEarly[from] || earlyBuyPenaltyEnd <= block.timestamp, "Snipers can't transfer tokens to sell cheaper DM a Mod.");
if (_maxWalletOn == true && ! _isMaxWalletExclude[to]) {
require(balanceOf(to) + amount <= _maxWalletSize, "Max amount of tokens for wallet reached");
}
if (_buyLimits == true && from == uniV2Pair) {
require(amount <= 500000000000 * 10**18, "Limits are in place, please lower buying amount");
}
if(_initLaunch == true) {
IUniswapV2Router02 _uniV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
uniV2Router = _uniV2Router;
uniV2Pair = IUniswapV2Factory(_uniV2Router.factory()).getPair(address(this), _uniV2Router.WETH());
tradingActiveBlock = block.number;
earlyBuyPenaltyEnd = block.timestamp + 72 hours;
_isMaxWalletExclude[address(uniV2Pair)] = true;
_isMaxWalletExclude[address(uniV2Router)] = true;
_buyLimits = true;
_maxWalletOn = true;
_antiSnipe = true;
_initLaunch = false;
}
if(_antiSnipe == true && from != owner() && to != uniV2Pair) {
for (uint x = 0; x < 2; x++) {
if(block.number == tradingActiveBlock + x) {
boughtEarly[to] = true;
emit BoughtEarly(to);
}
if(x >= 2){
_antiSnipe = false;
}
}
}
if (to == uniV2Pair) {
_marTax = _sellMarTax;
_giveAwayTax = _sellGiveAwayTax;
_liqTax = _sellLiqTax;
_refTax = _sellRefTax;
_marTax = _buyMarTax;
_giveAwayTax = _buyGiveAwayTax;
_liqTax = _buyLiqTax;
_refTax = _buyRefTax;
}
uint256 contractTokenBalance = balanceOf(address(this));
if (!inSwapAndLiquify && to == uniV2Pair && swapAndLiquifyEnabled) {
if (contractTokenBalance >= minTokensBeforeSwap) {
swapTokens();
}
}
bool takeFee = true;
if (_isExcludedFromFee[from] || _isExcludedFromFee[to]) {
takeFee = false;
}
if(boughtEarly[from] && earlyBuyPenaltyEnd > block.timestamp){
_liqTax = 0;
_marTax = 95;
_giveAwayTax = 0;
_refTax = 0;
}
_tokenTransfer(from, to, amount, takeFee);
}
function _transfer(address from,address to,uint256 amount) private {
require(from != address(0), "ERC20: transfer from zero address");
require(to != address(0), "ERC20: transfer to zero address");
require(amount > 0, "Transfer amount must be greater than zero");
require(!_isBot[from]);
require(!boughtEarly[from] || earlyBuyPenaltyEnd <= block.timestamp, "Snipers can't transfer tokens to sell cheaper DM a Mod.");
if (_maxWalletOn == true && ! _isMaxWalletExclude[to]) {
require(balanceOf(to) + amount <= _maxWalletSize, "Max amount of tokens for wallet reached");
}
if (_buyLimits == true && from == uniV2Pair) {
require(amount <= 500000000000 * 10**18, "Limits are in place, please lower buying amount");
}
if(_initLaunch == true) {
IUniswapV2Router02 _uniV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
uniV2Router = _uniV2Router;
uniV2Pair = IUniswapV2Factory(_uniV2Router.factory()).getPair(address(this), _uniV2Router.WETH());
tradingActiveBlock = block.number;
earlyBuyPenaltyEnd = block.timestamp + 72 hours;
_isMaxWalletExclude[address(uniV2Pair)] = true;
_isMaxWalletExclude[address(uniV2Router)] = true;
_buyLimits = true;
_maxWalletOn = true;
_antiSnipe = true;
_initLaunch = false;
}
if(_antiSnipe == true && from != owner() && to != uniV2Pair) {
for (uint x = 0; x < 2; x++) {
if(block.number == tradingActiveBlock + x) {
boughtEarly[to] = true;
emit BoughtEarly(to);
}
if(x >= 2){
_antiSnipe = false;
}
}
}
if (to == uniV2Pair) {
_marTax = _sellMarTax;
_giveAwayTax = _sellGiveAwayTax;
_liqTax = _sellLiqTax;
_refTax = _sellRefTax;
_marTax = _buyMarTax;
_giveAwayTax = _buyGiveAwayTax;
_liqTax = _buyLiqTax;
_refTax = _buyRefTax;
}
uint256 contractTokenBalance = balanceOf(address(this));
if (!inSwapAndLiquify && to == uniV2Pair && swapAndLiquifyEnabled) {
if (contractTokenBalance >= minTokensBeforeSwap) {
swapTokens();
}
}
bool takeFee = true;
if (_isExcludedFromFee[from] || _isExcludedFromFee[to]) {
takeFee = false;
}
if(boughtEarly[from] && earlyBuyPenaltyEnd > block.timestamp){
_liqTax = 0;
_marTax = 95;
_giveAwayTax = 0;
_refTax = 0;
}
_tokenTransfer(from, to, amount, takeFee);
}
function _transfer(address from,address to,uint256 amount) private {
require(from != address(0), "ERC20: transfer from zero address");
require(to != address(0), "ERC20: transfer to zero address");
require(amount > 0, "Transfer amount must be greater than zero");
require(!_isBot[from]);
require(!boughtEarly[from] || earlyBuyPenaltyEnd <= block.timestamp, "Snipers can't transfer tokens to sell cheaper DM a Mod.");
if (_maxWalletOn == true && ! _isMaxWalletExclude[to]) {
require(balanceOf(to) + amount <= _maxWalletSize, "Max amount of tokens for wallet reached");
}
if (_buyLimits == true && from == uniV2Pair) {
require(amount <= 500000000000 * 10**18, "Limits are in place, please lower buying amount");
}
if(_initLaunch == true) {
IUniswapV2Router02 _uniV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
uniV2Router = _uniV2Router;
uniV2Pair = IUniswapV2Factory(_uniV2Router.factory()).getPair(address(this), _uniV2Router.WETH());
tradingActiveBlock = block.number;
earlyBuyPenaltyEnd = block.timestamp + 72 hours;
_isMaxWalletExclude[address(uniV2Pair)] = true;
_isMaxWalletExclude[address(uniV2Router)] = true;
_buyLimits = true;
_maxWalletOn = true;
_antiSnipe = true;
_initLaunch = false;
}
if(_antiSnipe == true && from != owner() && to != uniV2Pair) {
for (uint x = 0; x < 2; x++) {
if(block.number == tradingActiveBlock + x) {
boughtEarly[to] = true;
emit BoughtEarly(to);
}
if(x >= 2){
_antiSnipe = false;
}
}
}
if (to == uniV2Pair) {
_marTax = _sellMarTax;
_giveAwayTax = _sellGiveAwayTax;
_liqTax = _sellLiqTax;
_refTax = _sellRefTax;
_marTax = _buyMarTax;
_giveAwayTax = _buyGiveAwayTax;
_liqTax = _buyLiqTax;
_refTax = _buyRefTax;
}
uint256 contractTokenBalance = balanceOf(address(this));
if (!inSwapAndLiquify && to == uniV2Pair && swapAndLiquifyEnabled) {
if (contractTokenBalance >= minTokensBeforeSwap) {
swapTokens();
}
}
bool takeFee = true;
if (_isExcludedFromFee[from] || _isExcludedFromFee[to]) {
takeFee = false;
}
if(boughtEarly[from] && earlyBuyPenaltyEnd > block.timestamp){
_liqTax = 0;
_marTax = 95;
_giveAwayTax = 0;
_refTax = 0;
}
_tokenTransfer(from, to, amount, takeFee);
}
function _transfer(address from,address to,uint256 amount) private {
require(from != address(0), "ERC20: transfer from zero address");
require(to != address(0), "ERC20: transfer to zero address");
require(amount > 0, "Transfer amount must be greater than zero");
require(!_isBot[from]);
require(!boughtEarly[from] || earlyBuyPenaltyEnd <= block.timestamp, "Snipers can't transfer tokens to sell cheaper DM a Mod.");
if (_maxWalletOn == true && ! _isMaxWalletExclude[to]) {
require(balanceOf(to) + amount <= _maxWalletSize, "Max amount of tokens for wallet reached");
}
if (_buyLimits == true && from == uniV2Pair) {
require(amount <= 500000000000 * 10**18, "Limits are in place, please lower buying amount");
}
if(_initLaunch == true) {
IUniswapV2Router02 _uniV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
uniV2Router = _uniV2Router;
uniV2Pair = IUniswapV2Factory(_uniV2Router.factory()).getPair(address(this), _uniV2Router.WETH());
tradingActiveBlock = block.number;
earlyBuyPenaltyEnd = block.timestamp + 72 hours;
_isMaxWalletExclude[address(uniV2Pair)] = true;
_isMaxWalletExclude[address(uniV2Router)] = true;
_buyLimits = true;
_maxWalletOn = true;
_antiSnipe = true;
_initLaunch = false;
}
if(_antiSnipe == true && from != owner() && to != uniV2Pair) {
for (uint x = 0; x < 2; x++) {
if(block.number == tradingActiveBlock + x) {
boughtEarly[to] = true;
emit BoughtEarly(to);
}
if(x >= 2){
_antiSnipe = false;
}
}
}
if (to == uniV2Pair) {
_marTax = _sellMarTax;
_giveAwayTax = _sellGiveAwayTax;
_liqTax = _sellLiqTax;
_refTax = _sellRefTax;
_marTax = _buyMarTax;
_giveAwayTax = _buyGiveAwayTax;
_liqTax = _buyLiqTax;
_refTax = _buyRefTax;
}
uint256 contractTokenBalance = balanceOf(address(this));
if (!inSwapAndLiquify && to == uniV2Pair && swapAndLiquifyEnabled) {
if (contractTokenBalance >= minTokensBeforeSwap) {
swapTokens();
}
}
bool takeFee = true;
if (_isExcludedFromFee[from] || _isExcludedFromFee[to]) {
takeFee = false;
}
if(boughtEarly[from] && earlyBuyPenaltyEnd > block.timestamp){
_liqTax = 0;
_marTax = 95;
_giveAwayTax = 0;
_refTax = 0;
}
_tokenTransfer(from, to, amount, takeFee);
}
function _transfer(address from,address to,uint256 amount) private {
require(from != address(0), "ERC20: transfer from zero address");
require(to != address(0), "ERC20: transfer to zero address");
require(amount > 0, "Transfer amount must be greater than zero");
require(!_isBot[from]);
require(!boughtEarly[from] || earlyBuyPenaltyEnd <= block.timestamp, "Snipers can't transfer tokens to sell cheaper DM a Mod.");
if (_maxWalletOn == true && ! _isMaxWalletExclude[to]) {
require(balanceOf(to) + amount <= _maxWalletSize, "Max amount of tokens for wallet reached");
}
if (_buyLimits == true && from == uniV2Pair) {
require(amount <= 500000000000 * 10**18, "Limits are in place, please lower buying amount");
}
if(_initLaunch == true) {
IUniswapV2Router02 _uniV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
uniV2Router = _uniV2Router;
uniV2Pair = IUniswapV2Factory(_uniV2Router.factory()).getPair(address(this), _uniV2Router.WETH());
tradingActiveBlock = block.number;
earlyBuyPenaltyEnd = block.timestamp + 72 hours;
_isMaxWalletExclude[address(uniV2Pair)] = true;
_isMaxWalletExclude[address(uniV2Router)] = true;
_buyLimits = true;
_maxWalletOn = true;
_antiSnipe = true;
_initLaunch = false;
}
if(_antiSnipe == true && from != owner() && to != uniV2Pair) {
for (uint x = 0; x < 2; x++) {
if(block.number == tradingActiveBlock + x) {
boughtEarly[to] = true;
emit BoughtEarly(to);
}
if(x >= 2){
_antiSnipe = false;
}
}
}
if (to == uniV2Pair) {
_marTax = _sellMarTax;
_giveAwayTax = _sellGiveAwayTax;
_liqTax = _sellLiqTax;
_refTax = _sellRefTax;
_marTax = _buyMarTax;
_giveAwayTax = _buyGiveAwayTax;
_liqTax = _buyLiqTax;
_refTax = _buyRefTax;
}
uint256 contractTokenBalance = balanceOf(address(this));
if (!inSwapAndLiquify && to == uniV2Pair && swapAndLiquifyEnabled) {
if (contractTokenBalance >= minTokensBeforeSwap) {
swapTokens();
}
}
bool takeFee = true;
if (_isExcludedFromFee[from] || _isExcludedFromFee[to]) {
takeFee = false;
}
if(boughtEarly[from] && earlyBuyPenaltyEnd > block.timestamp){
_liqTax = 0;
_marTax = 95;
_giveAwayTax = 0;
_refTax = 0;
}
_tokenTransfer(from, to, amount, takeFee);
}
} else if (from == uniV2Pair) {
function _transfer(address from,address to,uint256 amount) private {
require(from != address(0), "ERC20: transfer from zero address");
require(to != address(0), "ERC20: transfer to zero address");
require(amount > 0, "Transfer amount must be greater than zero");
require(!_isBot[from]);
require(!boughtEarly[from] || earlyBuyPenaltyEnd <= block.timestamp, "Snipers can't transfer tokens to sell cheaper DM a Mod.");
if (_maxWalletOn == true && ! _isMaxWalletExclude[to]) {
require(balanceOf(to) + amount <= _maxWalletSize, "Max amount of tokens for wallet reached");
}
if (_buyLimits == true && from == uniV2Pair) {
require(amount <= 500000000000 * 10**18, "Limits are in place, please lower buying amount");
}
if(_initLaunch == true) {
IUniswapV2Router02 _uniV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
uniV2Router = _uniV2Router;
uniV2Pair = IUniswapV2Factory(_uniV2Router.factory()).getPair(address(this), _uniV2Router.WETH());
tradingActiveBlock = block.number;
earlyBuyPenaltyEnd = block.timestamp + 72 hours;
_isMaxWalletExclude[address(uniV2Pair)] = true;
_isMaxWalletExclude[address(uniV2Router)] = true;
_buyLimits = true;
_maxWalletOn = true;
_antiSnipe = true;
_initLaunch = false;
}
if(_antiSnipe == true && from != owner() && to != uniV2Pair) {
for (uint x = 0; x < 2; x++) {
if(block.number == tradingActiveBlock + x) {
boughtEarly[to] = true;
emit BoughtEarly(to);
}
if(x >= 2){
_antiSnipe = false;
}
}
}
if (to == uniV2Pair) {
_marTax = _sellMarTax;
_giveAwayTax = _sellGiveAwayTax;
_liqTax = _sellLiqTax;
_refTax = _sellRefTax;
_marTax = _buyMarTax;
_giveAwayTax = _buyGiveAwayTax;
_liqTax = _buyLiqTax;
_refTax = _buyRefTax;
}
uint256 contractTokenBalance = balanceOf(address(this));
if (!inSwapAndLiquify && to == uniV2Pair && swapAndLiquifyEnabled) {
if (contractTokenBalance >= minTokensBeforeSwap) {
swapTokens();
}
}
bool takeFee = true;
if (_isExcludedFromFee[from] || _isExcludedFromFee[to]) {
takeFee = false;
}
if(boughtEarly[from] && earlyBuyPenaltyEnd > block.timestamp){
_liqTax = 0;
_marTax = 95;
_giveAwayTax = 0;
_refTax = 0;
}
_tokenTransfer(from, to, amount, takeFee);
}
function _transfer(address from,address to,uint256 amount) private {
require(from != address(0), "ERC20: transfer from zero address");
require(to != address(0), "ERC20: transfer to zero address");
require(amount > 0, "Transfer amount must be greater than zero");
require(!_isBot[from]);
require(!boughtEarly[from] || earlyBuyPenaltyEnd <= block.timestamp, "Snipers can't transfer tokens to sell cheaper DM a Mod.");
if (_maxWalletOn == true && ! _isMaxWalletExclude[to]) {
require(balanceOf(to) + amount <= _maxWalletSize, "Max amount of tokens for wallet reached");
}
if (_buyLimits == true && from == uniV2Pair) {
require(amount <= 500000000000 * 10**18, "Limits are in place, please lower buying amount");
}
if(_initLaunch == true) {
IUniswapV2Router02 _uniV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
uniV2Router = _uniV2Router;
uniV2Pair = IUniswapV2Factory(_uniV2Router.factory()).getPair(address(this), _uniV2Router.WETH());
tradingActiveBlock = block.number;
earlyBuyPenaltyEnd = block.timestamp + 72 hours;
_isMaxWalletExclude[address(uniV2Pair)] = true;
_isMaxWalletExclude[address(uniV2Router)] = true;
_buyLimits = true;
_maxWalletOn = true;
_antiSnipe = true;
_initLaunch = false;
}
if(_antiSnipe == true && from != owner() && to != uniV2Pair) {
for (uint x = 0; x < 2; x++) {
if(block.number == tradingActiveBlock + x) {
boughtEarly[to] = true;
emit BoughtEarly(to);
}
if(x >= 2){
_antiSnipe = false;
}
}
}
if (to == uniV2Pair) {
_marTax = _sellMarTax;
_giveAwayTax = _sellGiveAwayTax;
_liqTax = _sellLiqTax;
_refTax = _sellRefTax;
_marTax = _buyMarTax;
_giveAwayTax = _buyGiveAwayTax;
_liqTax = _buyLiqTax;
_refTax = _buyRefTax;
}
uint256 contractTokenBalance = balanceOf(address(this));
if (!inSwapAndLiquify && to == uniV2Pair && swapAndLiquifyEnabled) {
if (contractTokenBalance >= minTokensBeforeSwap) {
swapTokens();
}
}
bool takeFee = true;
if (_isExcludedFromFee[from] || _isExcludedFromFee[to]) {
takeFee = false;
}
if(boughtEarly[from] && earlyBuyPenaltyEnd > block.timestamp){
_liqTax = 0;
_marTax = 95;
_giveAwayTax = 0;
_refTax = 0;
}
_tokenTransfer(from, to, amount, takeFee);
}
function _transfer(address from,address to,uint256 amount) private {
require(from != address(0), "ERC20: transfer from zero address");
require(to != address(0), "ERC20: transfer to zero address");
require(amount > 0, "Transfer amount must be greater than zero");
require(!_isBot[from]);
require(!boughtEarly[from] || earlyBuyPenaltyEnd <= block.timestamp, "Snipers can't transfer tokens to sell cheaper DM a Mod.");
if (_maxWalletOn == true && ! _isMaxWalletExclude[to]) {
require(balanceOf(to) + amount <= _maxWalletSize, "Max amount of tokens for wallet reached");
}
if (_buyLimits == true && from == uniV2Pair) {
require(amount <= 500000000000 * 10**18, "Limits are in place, please lower buying amount");
}
if(_initLaunch == true) {
IUniswapV2Router02 _uniV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
uniV2Router = _uniV2Router;
uniV2Pair = IUniswapV2Factory(_uniV2Router.factory()).getPair(address(this), _uniV2Router.WETH());
tradingActiveBlock = block.number;
earlyBuyPenaltyEnd = block.timestamp + 72 hours;
_isMaxWalletExclude[address(uniV2Pair)] = true;
_isMaxWalletExclude[address(uniV2Router)] = true;
_buyLimits = true;
_maxWalletOn = true;
_antiSnipe = true;
_initLaunch = false;
}
if(_antiSnipe == true && from != owner() && to != uniV2Pair) {
for (uint x = 0; x < 2; x++) {
if(block.number == tradingActiveBlock + x) {
boughtEarly[to] = true;
emit BoughtEarly(to);
}
if(x >= 2){
_antiSnipe = false;
}
}
}
if (to == uniV2Pair) {
_marTax = _sellMarTax;
_giveAwayTax = _sellGiveAwayTax;
_liqTax = _sellLiqTax;
_refTax = _sellRefTax;
_marTax = _buyMarTax;
_giveAwayTax = _buyGiveAwayTax;
_liqTax = _buyLiqTax;
_refTax = _buyRefTax;
}
uint256 contractTokenBalance = balanceOf(address(this));
if (!inSwapAndLiquify && to == uniV2Pair && swapAndLiquifyEnabled) {
if (contractTokenBalance >= minTokensBeforeSwap) {
swapTokens();
}
}
bool takeFee = true;
if (_isExcludedFromFee[from] || _isExcludedFromFee[to]) {
takeFee = false;
}
if(boughtEarly[from] && earlyBuyPenaltyEnd > block.timestamp){
_liqTax = 0;
_marTax = 95;
_giveAwayTax = 0;
_refTax = 0;
}
_tokenTransfer(from, to, amount, takeFee);
}
function _transfer(address from,address to,uint256 amount) private {
require(from != address(0), "ERC20: transfer from zero address");
require(to != address(0), "ERC20: transfer to zero address");
require(amount > 0, "Transfer amount must be greater than zero");
require(!_isBot[from]);
require(!boughtEarly[from] || earlyBuyPenaltyEnd <= block.timestamp, "Snipers can't transfer tokens to sell cheaper DM a Mod.");
if (_maxWalletOn == true && ! _isMaxWalletExclude[to]) {
require(balanceOf(to) + amount <= _maxWalletSize, "Max amount of tokens for wallet reached");
}
if (_buyLimits == true && from == uniV2Pair) {
require(amount <= 500000000000 * 10**18, "Limits are in place, please lower buying amount");
}
if(_initLaunch == true) {
IUniswapV2Router02 _uniV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
uniV2Router = _uniV2Router;
uniV2Pair = IUniswapV2Factory(_uniV2Router.factory()).getPair(address(this), _uniV2Router.WETH());
tradingActiveBlock = block.number;
earlyBuyPenaltyEnd = block.timestamp + 72 hours;
_isMaxWalletExclude[address(uniV2Pair)] = true;
_isMaxWalletExclude[address(uniV2Router)] = true;
_buyLimits = true;
_maxWalletOn = true;
_antiSnipe = true;
_initLaunch = false;
}
if(_antiSnipe == true && from != owner() && to != uniV2Pair) {
for (uint x = 0; x < 2; x++) {
if(block.number == tradingActiveBlock + x) {
boughtEarly[to] = true;
emit BoughtEarly(to);
}
if(x >= 2){
_antiSnipe = false;
}
}
}
if (to == uniV2Pair) {
_marTax = _sellMarTax;
_giveAwayTax = _sellGiveAwayTax;
_liqTax = _sellLiqTax;
_refTax = _sellRefTax;
_marTax = _buyMarTax;
_giveAwayTax = _buyGiveAwayTax;
_liqTax = _buyLiqTax;
_refTax = _buyRefTax;
}
uint256 contractTokenBalance = balanceOf(address(this));
if (!inSwapAndLiquify && to == uniV2Pair && swapAndLiquifyEnabled) {
if (contractTokenBalance >= minTokensBeforeSwap) {
swapTokens();
}
}
bool takeFee = true;
if (_isExcludedFromFee[from] || _isExcludedFromFee[to]) {
takeFee = false;
}
if(boughtEarly[from] && earlyBuyPenaltyEnd > block.timestamp){
_liqTax = 0;
_marTax = 95;
_giveAwayTax = 0;
_refTax = 0;
}
_tokenTransfer(from, to, amount, takeFee);
}
function swapETHForTokens(uint256 amount) private {
address[] memory path = new address[](2);
path[0] = uniV2Router.WETH();
path[1] = address(this);
path,
block.timestamp.add(300)
);
}
uniV2Router.swapExactETHForTokensSupportingFeeOnTransferTokens{value: amount}(
function addBot(address _user) public onlyOwner {
require(_user != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
require(!_isBot[_user]);
_isBot[_user] = true;
}
function removeBot(address _user) public onlyOwner {
require(_isBot[_user]);
_isBot[_user] = false;
}
function removeSniper(address account) external onlyOwner {
boughtEarly[account] = false;
emit RemovedSniper(account);
}
function swapTokens() private lockTheSwap {
uint256 contractBalance = balanceOf(address(this));
uint256 totalTokensToSwap = tokensForLiquidityToSwap + tokensForMarketingToSwap + tokensForGiveAwayToSwap;
uint256 amountToSwapForETH = contractBalance.sub(tokensForLiquidity);
uint256 initialETHBalance = address(this).balance;
swapTokensForETH(amountToSwapForETH);
uint256 ethBalance = address(this).balance.sub(initialETHBalance);
uint256 ethForMarketing = ethBalance.mul(tokensForMarketingToSwap).div(totalTokensToSwap);
uint256 ethForGiveAway = ethBalance.mul(tokensForGiveAwayToSwap).div(totalTokensToSwap);
uint256 ethForLiquidity = ethBalance.sub(ethForMarketing).sub(ethForGiveAway);
tokensForLiquidityToSwap = 0;
tokensForMarketingToSwap = 0;
tokensForGiveAwayToSwap = 0;
addLiquidity(tokensForLiquidity, ethForLiquidity);
emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, tokensForLiquidity);
if(address(this).balance > 0 * 10**18){
}
}
(bool success,) = address(marketingAddress).call{value: ethForMarketing}("");
(success,) = address(giveAwayAddress).call{value: ethForGiveAway}("");
function swapTokens() private lockTheSwap {
uint256 contractBalance = balanceOf(address(this));
uint256 totalTokensToSwap = tokensForLiquidityToSwap + tokensForMarketingToSwap + tokensForGiveAwayToSwap;
uint256 amountToSwapForETH = contractBalance.sub(tokensForLiquidity);
uint256 initialETHBalance = address(this).balance;
swapTokensForETH(amountToSwapForETH);
uint256 ethBalance = address(this).balance.sub(initialETHBalance);
uint256 ethForMarketing = ethBalance.mul(tokensForMarketingToSwap).div(totalTokensToSwap);
uint256 ethForGiveAway = ethBalance.mul(tokensForGiveAwayToSwap).div(totalTokensToSwap);
uint256 ethForLiquidity = ethBalance.sub(ethForMarketing).sub(ethForGiveAway);
tokensForLiquidityToSwap = 0;
tokensForMarketingToSwap = 0;
tokensForGiveAwayToSwap = 0;
addLiquidity(tokensForLiquidity, ethForLiquidity);
emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, tokensForLiquidity);
if(address(this).balance > 0 * 10**18){
}
}
(success,) = address(marketingAddress).call{value: address(this).balance}("");
function swapTokensForETH(uint256 tokenAmount) private {
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniV2Router.WETH();
_approve(address(this), address(uniV2Router), tokenAmount);
uniV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
path,
address(this),
block.timestamp.add(300)
);
}
function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private {
_approve(address(this), address(uniV2Router), tokenAmount);
address(this),
tokenAmount,
dead,
block.timestamp.add(300)
);
}
uniV2Router.addLiquidityETH{value: ethAmount}(
function setMarketingAddress(address _marketingAddress) external onlyOwner {
require(_marketingAddress != address(0));
_isExcludedFromFee[marketingAddress] = false;
marketingAddress = payable(_marketingAddress);
_isExcludedFromFee[marketingAddress] = true;
emit UpdatedMarketingAddress(_marketingAddress);
}
function setGiveAwayAddress(address _giveAwayAddress) public onlyOwner {
require(_giveAwayAddress != address(0));
giveAwayAddress = payable(_giveAwayAddress);
emit UpdatedGiveAwayAddress(_giveAwayAddress);
}
function StartLaunchInit() external onlyOwner {
_initLaunch = true;
}
function StopLaunchInit() external onlyOwner {
_initLaunch = false;
}
function TaxSwapEnable() external onlyOwner {
swapAndLiquifyEnabled = true;
}
function TaxSwapDisable() external onlyOwner {
swapAndLiquifyEnabled = false;
}
function ResumeLimits() external onlyOwner {
_buyLimits = true;
}
function RemoveLimits() external onlyOwner {
_buyLimits = false;
}
function MaxWalletOn() external onlyOwner {
_maxWalletOn = true;
}
function MaxWalletOff() external onlyOwner {
_maxWalletOn = false;
}
function setBuyF(uint buyMarTax, uint buyGiveAwayTax, uint buyLiqTax, uint buyRefTax) external onlyOwner {
_buyMarTax = buyMarTax;
_buyGiveAwayTax = buyGiveAwayTax;
_buyLiqTax = buyLiqTax;
_buyRefTax = buyRefTax;
}
function setSellF(uint sellMarTax, uint sellGiveAwayTax, uint sellLiqTax, uint sellRefTax) external onlyOwner {
_sellMarTax = sellMarTax;
_sellGiveAwayTax = sellGiveAwayTax;
_sellLiqTax = sellLiqTax;
_sellRefTax = sellRefTax;
}
function startAntiSniper() external onlyOwner {
_antiSnipe = true;
}
function stopAntiSniper() external onlyOwner {
_antiSnipe = false;
}
function HappyHour() external onlyOwner {
_preBuyMarTax = _buyMarTax;
_preBuyGiveAwayTax = _buyGiveAwayTax;
_preBuyLiqTax = _buyLiqTax;
_preBuyRefTax = _buyRefTax;
_preSellMarTax = _sellMarTax;
_preSellGiveAwayTax = _sellGiveAwayTax;
_preSellLiqTax = _sellLiqTax;
_preSellRefTax = _sellRefTax;
_buyMarTax = 0;
_buyGiveAwayTax = 0;
_buyLiqTax = 0;
_buyRefTax = 0;
_sellMarTax = 0;
_sellGiveAwayTax = 0;
_sellLiqTax = 0;
_sellRefTax = 0;
}
function HappyHourOff() external onlyOwner {
_buyMarTax = _preBuyMarTax;
_buyGiveAwayTax = _preBuyGiveAwayTax;
_buyLiqTax = _preBuyLiqTax;
_buyRefTax = _preBuyRefTax;
_sellMarTax = _preSellMarTax;
_sellGiveAwayTax = _preSellGiveAwayTax;
_sellLiqTax = _preSellLiqTax;
_sellRefTax = _preSellRefTax;
}
function _tokenTransfer(address sender,address recipient,uint256 amount,bool takeFee) private {
if (!takeFee) removeAllFee();
if (_isExcluded[sender] && !_isExcluded[recipient]) {
_transferFromExcluded(sender, recipient, amount);
_transferToExcluded(sender, recipient, amount);
_transferStandard(sender, recipient, amount);
_transferBothExcluded(sender, recipient, amount);
_transferStandard(sender, recipient, amount);
}
if (!takeFee) restoreAllFee();
}
function _tokenTransfer(address sender,address recipient,uint256 amount,bool takeFee) private {
if (!takeFee) removeAllFee();
if (_isExcluded[sender] && !_isExcluded[recipient]) {
_transferFromExcluded(sender, recipient, amount);
_transferToExcluded(sender, recipient, amount);
_transferStandard(sender, recipient, amount);
_transferBothExcluded(sender, recipient, amount);
_transferStandard(sender, recipient, amount);
}
if (!takeFee) restoreAllFee();
}
} else if (!_isExcluded[sender] && _isExcluded[recipient]) {
} else if (!_isExcluded[sender] && !_isExcluded[recipient]) {
} else if (_isExcluded[sender] && _isExcluded[recipient]) {
} else {
function _transferStandard(address sender,address recipient,uint256 tAmount) private {
(
uint256 rAmount,
uint256 rTransferAmount,
uint256 rFee,
uint256 tTransferAmount,
uint256 tFee,
uint256 tLiquidity
) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(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);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(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);
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeLiquidity(tLiquidity);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferBothExcluded(address sender,address recipient,uint256 tAmount) private {
(
uint256 rAmount,
uint256 rTransferAmount,
uint256 rFee,
uint256 tTransferAmount,
uint256 tFee,
uint256 tLiquidity
) = _getValues(tAmount);
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeLiquidity(tLiquidity);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _tokenTransferNoFee(address sender,address recipient,uint256 amount) private {
_rOwned[sender] = _rOwned[sender].sub(amount);
_rOwned[recipient] = _rOwned[recipient].add(amount);
if (_isExcluded[sender]) {
_tOwned[sender] = _tOwned[sender].sub(amount);
}
if (_isExcluded[recipient]) {
_tOwned[recipient] = _tOwned[recipient].add(amount);
}
emit Transfer(sender, recipient, amount);
}
function _tokenTransferNoFee(address sender,address recipient,uint256 amount) private {
_rOwned[sender] = _rOwned[sender].sub(amount);
_rOwned[recipient] = _rOwned[recipient].add(amount);
if (_isExcluded[sender]) {
_tOwned[sender] = _tOwned[sender].sub(amount);
}
if (_isExcluded[recipient]) {
_tOwned[recipient] = _tOwned[recipient].add(amount);
}
emit Transfer(sender, recipient, amount);
}
function _tokenTransferNoFee(address sender,address recipient,uint256 amount) private {
_rOwned[sender] = _rOwned[sender].sub(amount);
_rOwned[recipient] = _rOwned[recipient].add(amount);
if (_isExcluded[sender]) {
_tOwned[sender] = _tOwned[sender].sub(amount);
}
if (_isExcluded[recipient]) {
_tOwned[recipient] = _tOwned[recipient].add(amount);
}
emit Transfer(sender, recipient, amount);
}
} | 15,439,621 | [
1,
5280,
25564,
1441,
670,
11753,
55,
571,
22577,
54,
18216,
512,
18133,
23211,
50,
19803,
399,
2501,
13477,
12108,
10937,
61,
571,
26267,
38,
900,
13601,
12882,
265,
15268,
9835,
42,
1435,
19803,
399,
2501,
13477,
12108,
20853,
48,
571,
26267,
38,
900,
13601,
12882,
265,
13928,
1165,
42,
1435,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
6122,
706,
3047,
2192,
45,
353,
1772,
16,
467,
654,
39,
3462,
16,
4232,
39,
3462,
5460,
429,
288,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
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,
2874,
12,
2867,
516,
1426,
13,
3238,
389,
291,
16461,
31,
203,
565,
2874,
12,
2867,
516,
1426,
13,
3238,
389,
291,
2747,
16936,
12689,
31,
203,
565,
2874,
261,
2867,
516,
1426,
13,
3238,
389,
291,
6522,
31,
203,
202,
6770,
12,
2867,
516,
1426,
13,
1071,
800,
9540,
41,
20279,
31,
203,
565,
1758,
8363,
273,
374,
92,
12648,
12648,
12648,
12648,
2787,
72,
41,
69,
40,
31,
203,
565,
1758,
8526,
3238,
389,
24602,
31,
203,
565,
1758,
8843,
429,
1071,
13667,
310,
1887,
31,
203,
565,
1758,
8843,
429,
1071,
8492,
37,
1888,
1887,
31,
203,
565,
467,
984,
291,
91,
438,
58,
22,
8259,
3103,
3238,
7738,
58,
22,
8259,
31,
203,
565,
1758,
3238,
7738,
58,
22,
4154,
31,
203,
565,
1426,
316,
12521,
1876,
48,
18988,
1164,
31,
203,
565,
1426,
3238,
7720,
1876,
48,
18988,
1164,
1526,
273,
638,
31,
203,
565,
1426,
3238,
389,
2738,
9569,
273,
638,
31,
203,
565,
2
] |
pragma solidity ^0.5.0;
import "./KarmaCoin.sol";
contract GyanCoin {
using SafeMath for uint256;
string public name = "GYAN";
string public symbol = "GYN";
uint8 public decimals = 18;
uint256 _yesterdayMint;
uint256 _todayMint;
uint256 _dailyStartTime;
uint256 _weeklyStartTime;
uint256 _currentDayNumber;
mapping(uint256 => mapping(address => uint256)) dailyPeerBucket;
mapping(uint256 => address[]) dailyPeerArray;
KarmaCoin public karmaCoin;
uint256 totalSupply_;
struct Gyan {
uint256 fixedBalance;
uint256 floatingBalance;
uint256[] timestampIndex;
uint256 timestamp;
}
mapping(address => Gyan) gyanCoins;
event NewFloatingBalance(address _owner, uint256 _amount, address pbNode);
event NewFixedBalance(address _owner, uint256 _amount, address pbNode);
constructor(
KarmaCoin _karma
) public {
require(_karma != KarmaCoin(0));
karmaCoin = _karma;
_dailyStartTime = now;
_weeklyStartTime = now;
_currentDayNumber = 1;
_yesterdayMint = 1000; // Default starting Gyan mint rate on day 1
}
/**
* @dev current rate of daily minted gyan coin
*/
function yesterdayMint() public view returns (uint256) {
return _yesterdayMint;
}
/**
* @dev total supply of Gyan
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
function mintFor(address _to, uint256 _amount) public {
if (dailyPeerBucket[_currentDayNumber][_to] == 0) {
// User learning for the first time on this day of the current week
// Added him to the day's bucket
dailyPeerBucket[_currentDayNumber][_to] = _amount;
dailyPeerArray[_currentDayNumber].push(_to);
} else {
// User learning again on the same day
// Adding to his floating Gyan value of the day
dailyPeerBucket[_currentDayNumber][_to] = dailyPeerBucket[_currentDayNumber][_to].add(_amount);
}
totalSupply_ = totalSupply_.add(_amount);
gyanCoins[_to].floatingBalance = gyanCoins[_to].floatingBalance.add(_amount);
gyanCoins[_to].timestampIndex.push(now);
_todayMint = _todayMint.add(_amount);
// Send Event
emit NewFloatingBalance(_to, _amount, msg.sender);
}
function mintRewards() public returns (bool) {
require(now >= _dailyStartTime + 1 days);
// On Day Change
_dailyStartTime = now;
// Save the total mint count for yesterday (only if it was greater than 0) and reset today's count
if (_todayMint > 0) {
_yesterdayMint = _todayMint;
}
_todayMint = 0;
// Change the day number of the week
_currentDayNumber = _currentDayNumber.add(1);
// On week change, reset day number to 1
if (now >= _weeklyStartTime + 7 days) {
_weeklyStartTime = now;
_currentDayNumber = 1;
}
// Send out rewards to every peer who learnt last week
// TODO: Currently rewarding everyone equally. Change to reward based on elliptic curve.
for (uint i = 0; i < dailyPeerArray[_currentDayNumber].length; i++) {
uint256 percentGyanEarnedToday = dailyFloatingBalanceOf(dailyPeerArray[_currentDayNumber][i], _currentDayNumber).mul(100).div(_yesterdayMint);
// Reward user with Karma
karmaCoin.mintFor(dailyPeerArray[_currentDayNumber][i], dailyKarmaMint().mul(65).div(100).mul(percentGyanEarnedToday).div(100));
// Move Gyan from floating to fixed balance
gyanCoins[dailyPeerArray[_currentDayNumber][i]].fixedBalance = gyanCoins[dailyPeerArray[_currentDayNumber][i]].fixedBalance.add(dailyFloatingBalanceOf(dailyPeerArray[_currentDayNumber][i], _currentDayNumber));
gyanCoins[dailyPeerArray[_currentDayNumber][i]].floatingBalance = gyanCoins[dailyPeerArray[_currentDayNumber][i]].floatingBalance.sub(dailyFloatingBalanceOf(dailyPeerArray[_currentDayNumber][i], _currentDayNumber));
// Send events
emit NewFloatingBalance(dailyPeerArray[_currentDayNumber][i], gyanCoins[dailyPeerArray[_currentDayNumber][i]].floatingBalance, msg.sender);
emit NewFixedBalance(dailyPeerArray[_currentDayNumber][i], gyanCoins[dailyPeerArray[_currentDayNumber][i]].fixedBalance, msg.sender);
delete dailyPeerBucket[_currentDayNumber][dailyPeerArray[_currentDayNumber][i]];
}
// Empty the buckets of the day
delete dailyPeerArray[_currentDayNumber];
return true;
}
function dailyFloatingBalanceOf(address _owner, uint256 _currentDayNum) internal returns (uint256) {
return dailyPeerBucket[_currentDayNum][_owner];
}
/**
* @dev Gets the daily karma minting value of the protocol.
* @return An uint256 representing the amount of karma minted everyday.
*/
function dailyKarmaMint() public view returns (uint256 dailyMint) {
return (karmaCoin.totalSupply().mul(5).div(100)).div(365);
}
/**
* @dev Gets the average number of peers who are eligible for karma rewards every day over the last 7 days
* @return An uint256 representing the average number of peers who earn Gyan everyday
*/
function averageDailyPeers() public view returns (uint256 averagePeers) {
return (dailyPeerArray[1].length + dailyPeerArray[2].length + dailyPeerArray[3].length + dailyPeerArray[4].length + dailyPeerArray[5].length + dailyPeerArray[6].length + dailyPeerArray[7].length).div(7);
}
/**
* @dev Gets the daily karma minting value of the protocol.
* @return An uint256 representing the amount of karma minted everyday.
*/
function potentialKarmaReward(address owner) public view returns (uint256) {
uint256 karmaRewards = 0;
for (uint i = 1; i <= 7; i++) {
uint256 percentGyanEarnedToday = dailyPeerBucket[i][owner].mul(100).div(_yesterdayMint);
karmaRewards = karmaRewards.add(dailyKarmaMint().mul(65).div(100).mul(percentGyanEarnedToday).div(100));
}
return karmaRewards;
}
/**
* @dev Gets the floating 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 floatingBalanceOf(address _owner) public view returns (uint256 balance) {
return gyanCoins[_owner].floatingBalance;
}
/**
* @dev Gets the fixed 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 fixedBalanceOf(address _owner) public view returns (uint256 balance) {
return gyanCoins[_owner].fixedBalance;
}
} | On Day Change Save the total mint count for yesterday (only if it was greater than 0) and reset today's count On week change, reset day number to 1 Send out rewards to every peer who learnt last week TODO: Currently rewarding everyone equally. Change to reward based on elliptic curve. Reward user with Karma Move Gyan from floating to fixed balance Send events | function mintRewards() public returns (bool) {
require(now >= _dailyStartTime + 1 days);
_dailyStartTime = now;
if (_todayMint > 0) {
_yesterdayMint = _todayMint;
}
_todayMint = 0;
if (now >= _weeklyStartTime + 7 days) {
_weeklyStartTime = now;
_currentDayNumber = 1;
}
for (uint i = 0; i < dailyPeerArray[_currentDayNumber].length; i++) {
uint256 percentGyanEarnedToday = dailyFloatingBalanceOf(dailyPeerArray[_currentDayNumber][i], _currentDayNumber).mul(100).div(_yesterdayMint);
karmaCoin.mintFor(dailyPeerArray[_currentDayNumber][i], dailyKarmaMint().mul(65).div(100).mul(percentGyanEarnedToday).div(100));
gyanCoins[dailyPeerArray[_currentDayNumber][i]].fixedBalance = gyanCoins[dailyPeerArray[_currentDayNumber][i]].fixedBalance.add(dailyFloatingBalanceOf(dailyPeerArray[_currentDayNumber][i], _currentDayNumber));
gyanCoins[dailyPeerArray[_currentDayNumber][i]].floatingBalance = gyanCoins[dailyPeerArray[_currentDayNumber][i]].floatingBalance.sub(dailyFloatingBalanceOf(dailyPeerArray[_currentDayNumber][i], _currentDayNumber));
emit NewFloatingBalance(dailyPeerArray[_currentDayNumber][i], gyanCoins[dailyPeerArray[_currentDayNumber][i]].floatingBalance, msg.sender);
emit NewFixedBalance(dailyPeerArray[_currentDayNumber][i], gyanCoins[dailyPeerArray[_currentDayNumber][i]].fixedBalance, msg.sender);
delete dailyPeerBucket[_currentDayNumber][dailyPeerArray[_currentDayNumber][i]];
}
return true;
}
| 12,562,724 | [
1,
1398,
13735,
7576,
7074,
326,
2078,
312,
474,
1056,
364,
677,
26309,
261,
3700,
309,
518,
1703,
6802,
2353,
374,
13,
471,
2715,
10074,
1807,
1056,
2755,
4860,
2549,
16,
2715,
2548,
1300,
358,
404,
2479,
596,
283,
6397,
358,
3614,
4261,
10354,
884,
297,
496,
1142,
4860,
2660,
30,
15212,
19890,
310,
3614,
476,
1298,
1230,
18,
7576,
358,
19890,
2511,
603,
415,
549,
21507,
8882,
18,
534,
359,
1060,
729,
598,
1475,
297,
2540,
9933,
611,
93,
304,
628,
13861,
358,
5499,
11013,
2479,
2641,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] | [
1,
202,
915,
312,
474,
17631,
14727,
1435,
1071,
1135,
261,
6430,
13,
288,
203,
202,
202,
6528,
12,
3338,
1545,
389,
26790,
13649,
397,
404,
4681,
1769,
203,
202,
202,
67,
26790,
13649,
273,
2037,
31,
203,
202,
202,
430,
261,
67,
30064,
49,
474,
405,
374,
13,
288,
203,
1082,
202,
67,
93,
26309,
49,
474,
273,
389,
30064,
49,
474,
31,
203,
202,
202,
97,
203,
202,
202,
67,
30064,
49,
474,
273,
374,
31,
203,
202,
202,
430,
261,
3338,
1545,
389,
10741,
715,
13649,
397,
2371,
4681,
13,
288,
203,
1082,
202,
67,
10741,
715,
13649,
273,
2037,
31,
203,
1082,
202,
67,
2972,
4245,
1854,
273,
404,
31,
203,
202,
202,
97,
203,
202,
202,
1884,
261,
11890,
277,
273,
374,
31,
277,
411,
18872,
6813,
1076,
63,
67,
2972,
4245,
1854,
8009,
2469,
31,
277,
27245,
288,
203,
1082,
202,
11890,
5034,
5551,
43,
93,
304,
41,
1303,
329,
56,
20136,
273,
18872,
28344,
13937,
951,
12,
26790,
6813,
1076,
63,
67,
2972,
4245,
1854,
6362,
77,
6487,
389,
2972,
4245,
1854,
2934,
16411,
12,
6625,
2934,
2892,
24899,
93,
26309,
49,
474,
1769,
203,
1082,
202,
79,
297,
2540,
27055,
18,
81,
474,
1290,
12,
26790,
6813,
1076,
63,
67,
2972,
4245,
1854,
6362,
77,
6487,
18872,
47,
297,
2540,
49,
474,
7675,
16411,
12,
9222,
2934,
2892,
12,
6625,
2934,
16411,
12,
8849,
43,
93,
304,
41,
1303,
329,
56,
20136,
2934,
2892,
12,
6625,
10019,
203,
1082,
202,
7797,
304,
39,
9896,
63,
26790,
6813,
2
] |
./partial_match/1/0xd075875c6C3718c40e0F0eBbBeA46a6e09ec14D1/sources/Yukidzaki.sol | File: contracts/Yukidzaki.sol | contract Yukidzaki is ERC721A, Ownable {
string private _customBaseURI;
uint256 public publicMintPrice;
uint256 public allowListMintPrice;
uint256 public maxMintPerUser;
uint256 public maxMintSupply;
bool public publicMintOpen;
bool public allowListMintOpen;
mapping(address => bool) public allowList;
function _beforeTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
function _afterTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
}
pragma solidity ^0.8.9;
constructor(string memory customBaseURI) ERC721A("Yukidzaki", "YD") {
_customBaseURI = customBaseURI;
}
function _baseURI() internal view virtual override returns (string memory) {
return _customBaseURI;
}
function editMintWindows(
bool _publicMintOpen,
bool _allowListMintOpen,
uint256 _maxMintSupply,
uint256 _maxMintPerUser,
uint256 _allowListMintPrice,
uint256 _publicMintPrice
) external onlyOwner{
publicMintOpen = _publicMintOpen;
allowListMintOpen = _allowListMintOpen;
maxMintSupply = _maxMintSupply;
maxMintPerUser = _maxMintPerUser;
allowListMintPrice = _allowListMintPrice;
publicMintPrice = _publicMintPrice;
}
function setBaseURI(string memory customBaseURI) public {
_customBaseURI = customBaseURI;
}
function safeMint(uint256 quantity) public payable{
require(publicMintOpen, "Safe Mint Closed");
require(msg.value >= quantity * publicMintPrice, "Not enough funds");
require(_numberMinted(msg.sender) + quantity <= maxMintPerUser, "Mint Limit for you");
require(_totalMinted() + quantity <= maxMintSupply, "Sold out!");
_safeMint(msg.sender, quantity);
}
function safeMintForWhitelist(uint256 quantity) public payable{
require(allowListMintOpen, "Safe Mint for White List Closed");
require(allowList[msg.sender], "You are not on the allow list");
require(msg.value >= quantity * publicMintPrice, "Not enough funds");
require(_numberMinted(msg.sender) + quantity <= maxMintPerUser, "Mint Limit for you");
require(_totalMinted() + quantity <= maxMintSupply, "Sold out!");
_safeMint(msg.sender, quantity);
}
function withDraw() external onlyOwner{
uint256 balance = address(this).balance;
Address.sendValue(payable(msg.sender), balance);
}
function setAllowList(address[] calldata addresses) external onlyOwner{
for(uint256 i = 0; i < addresses.length; i++){
allowList[addresses[i]] = true;
}
}
function setAllowList(address[] calldata addresses) external onlyOwner{
for(uint256 i = 0; i < addresses.length; i++){
allowList[addresses[i]] = true;
}
}
function delAllowList(address[] calldata addresses) external onlyOwner{
for(uint256 i = 0; i < addresses.length; i++){
allowList[addresses[i]] = false;
}
}
function delAllowList(address[] calldata addresses) external onlyOwner{
for(uint256 i = 0; i < addresses.length; i++){
allowList[addresses[i]] = false;
}
}
} | 15,468,272 | [
1,
812,
30,
20092,
19,
61,
19445,
350,
94,
581,
77,
18,
18281,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
1624,
19445,
350,
94,
581,
77,
353,
4232,
39,
27,
5340,
37,
16,
14223,
6914,
288,
203,
565,
533,
3238,
389,
3662,
2171,
3098,
31,
203,
565,
2254,
5034,
1071,
1071,
49,
474,
5147,
31,
7010,
565,
2254,
5034,
1071,
1699,
682,
49,
474,
5147,
31,
203,
565,
2254,
5034,
1071,
943,
49,
474,
2173,
1299,
31,
203,
565,
2254,
5034,
1071,
943,
49,
474,
3088,
1283,
31,
203,
565,
1426,
1071,
1071,
49,
474,
3678,
31,
203,
565,
1426,
1071,
1699,
682,
49,
474,
3678,
31,
203,
203,
565,
2874,
12,
2867,
516,
1426,
13,
1071,
1699,
682,
31,
203,
203,
565,
445,
389,
5771,
1345,
1429,
18881,
12,
203,
3639,
1758,
628,
16,
203,
3639,
1758,
358,
16,
203,
3639,
2254,
5034,
787,
1345,
548,
16,
203,
3639,
2254,
5034,
10457,
203,
203,
565,
445,
389,
5205,
1345,
1429,
18881,
12,
203,
3639,
1758,
628,
16,
203,
3639,
1758,
358,
16,
203,
3639,
2254,
5034,
787,
1345,
548,
16,
203,
3639,
2254,
5034,
10457,
203,
97,
203,
203,
203,
203,
683,
9454,
18035,
560,
3602,
20,
18,
28,
18,
29,
31,
203,
203,
203,
203,
203,
565,
3885,
12,
1080,
3778,
1679,
2171,
3098,
13,
4232,
39,
27,
5340,
37,
2932,
61,
19445,
350,
94,
581,
77,
3113,
315,
61,
40,
7923,
288,
203,
3639,
389,
3662,
2171,
3098,
273,
1679,
2171,
3098,
31,
203,
565,
289,
203,
203,
565,
445,
389,
1969,
3098,
1435,
2713,
1476,
5024,
3849,
1135,
261,
1080,
3778,
13,
288,
203,
3639,
327,
389,
3662,
2171,
2
] |
pragma solidity ^0.4.25;
pragma experimental ABIEncoderV2;
import "../utils/Ownable.sol";
import "../utils/LibString.sol";
import "../utils/Table.sol";
contract MapStorage is Ownable {
using LibString for string;
event PutResult(int count);
TableFactory tf;
string constant TABLE_NAME = "tx_map";
/**
* @notice map表
* +----------------------+------------------------+-------------------------+
* | Field | Type | Desc |
* +----------------------+------------------------+-------------------------+
* | key | string | key |
* | value | string | value |
* +----------------------+------------------------+-------------------------+
*/
constructor() public {
tf = TableFactory(0x1001);
tf.createTable(TABLE_NAME, "key", "value");
}
/**
* @notice 插入数据,已有数据不添加
*/
function put(string memory _key, string memory _value) public onlyOwner returns(int) {
int count = int(0);
Table table = tf.openTable(TABLE_NAME);
if(!_key.empty() && !_value.empty() && !_isExist(table, _key, _value)){
Entry entry = table.newEntry();
entry.set("value", _value);
count = table.insert(_key, entry);
}
emit PutResult(count);
return count;
}
/**
* @notice 通过key获取value,可以存在多个value
*/
function get(string memory _key) public view returns(string[] memory){
Table table = tf.openTable(TABLE_NAME);
Condition condition = table.newCondition();
Entries entries = table.select(_key, condition);
string[] memory value_list = new string[](uint256(entries.size()));
for (int256 i = 0; i < entries.size(); ++i) {
Entry entry = entries.get(i);
value_list[uint256(i)] = entry.getString("value");
}
return value_list;
}
function _isExist(Table _table, string memory _key, string memory _value) internal view returns(bool) {
Condition condition = _table.newCondition();
condition.EQ("value", _value);
return _table.select(_key, condition).size() > int(0);
}
} | * @notice map表 +----------------------+------------------------+-------------------------+ | Field | Type | Desc | +----------------------+------------------------+-------------------------+ | key | string | key | | value | string | value | +----------------------+------------------------+-------------------------+/ | constructor() public {
tf = TableFactory(0x1001);
tf.createTable(TABLE_NAME, "key", "value");
}
| 15,781,901 | [
1,
1458,
169,
99,
106,
397,
1271,
13093,
15,
1271,
788,
15,
1271,
8567,
15,
571,
2286,
7734,
571,
1412,
10402,
571,
13913,
10792,
571,
397,
1271,
13093,
15,
1271,
788,
15,
1271,
8567,
15,
571,
498,
5375,
571,
533,
1171,
571,
498,
5397,
571,
571,
460,
7734,
571,
533,
1171,
571,
460,
10402,
571,
397,
1271,
13093,
15,
1271,
788,
15,
1271,
8567,
31298,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
3885,
1435,
1071,
288,
203,
3639,
3253,
273,
3555,
1733,
12,
20,
92,
6625,
21,
1769,
203,
3639,
3253,
18,
2640,
1388,
12,
7775,
67,
1985,
16,
315,
856,
3113,
315,
1132,
8863,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity 0.5.0;
contract Bet {
//bet status
uint constant STATUS_WIN = 1;
uint constant STATUS_LOSE = 2;
uint constant STATUS_TIE = 3;
uint constant STATUS_PENDING = 4;
//game status
uint constant STATUS_NOT_STARTED = 1;
uint constant STATUS_STARTED = 2;
uint constant STATUS_COMPLETE = 3;
//general status
uint constant STATUS_ERROR = 4;
//the 'better' structure
struct Bet {
uint guess;
address payable addr;
uint status;
}
//the 'game' structure
struct Game {
uint256 betAmount;
uint outcome;
uint status;
Bet originator;
Bet taker;
}
//the game
Game game;
//fallback function
function() external payable {}
function createBet(uint _guess) public payable {
game = Game(msg.value, 0, STATUS_STARTED, Bet(_guess, msg.sender, STATUS_PENDING), Bet(0, address(0), STATUS_NOT_STARTED));
game.originator = Bet(_guess, msg.sender, STATUS_PENDING);
}
function takeBet(uint _guess) public payable {
//requires the taker to make the same bet amount
require(msg.value == game.betAmount);
game.taker = Bet(_guess, msg.sender, STATUS_PENDING);
generateBetOutcome();
}
function payout() public payable {
checkPermissions(msg.sender);
if (game.originator.status == STATUS_TIE && game.taker.status == STATUS_TIE) {
game.originator.addr.transfer(game.betAmount);
game.taker.addr.transfer(game.betAmount);
} else {
if (game.originator.status == STATUS_WIN) {
game.originator.addr.transfer(game.betAmount*2);
} else if (game.taker.status == STATUS_WIN) {
game.taker.addr.transfer(game.betAmount*2);
} else {
game.originator.addr.transfer(game.betAmount);
game.taker.addr.transfer(game.betAmount);
}
}
}
function checkPermissions(address sender) view private {
//only the originator or taker can call this function
require(sender == game.originator.addr || sender == game.taker.addr);
}
function getBetAmount() public view returns (uint) {
checkPermissions(msg.sender);
return game.betAmount;
}
function getOriginatorGuess() public view returns (uint) {
checkPermissions(msg.sender);
return game.originator.guess;
}
function getTakerGuess() public view returns (uint) {
checkPermissions(msg.sender);
return game.taker.guess;
}
function getPot() public view returns (uint256) {
checkPermissions(msg.sender);
return address(this).balance;
}
function generateBetOutcome() private {
//todo - not a great way to generate a random number but ok for now
game.outcome = uint(blockhash(block.number-1))%10 + 1;
game.status = STATUS_COMPLETE;
if (game.originator.guess == game.taker.guess) {
game.originator.status = STATUS_TIE;
game.taker.status = STATUS_TIE;
} else if (game.originator.guess > game.outcome && game.taker.guess > game.outcome) {
game.originator.status = STATUS_TIE;
game.taker.status = STATUS_TIE;
} else {
if ((game.outcome - game.originator.guess) < (game.outcome - game.taker.guess)) {
game.originator.status = STATUS_WIN;
game.taker.status = STATUS_LOSE;
} else if ((game.outcome - game.taker.guess) < (game.outcome - game.originator.guess)) {
game.originator.status = STATUS_LOSE;
game.taker.status = STATUS_WIN;
} else {
game.originator.status = STATUS_ERROR;
game.taker.status = STATUS_ERROR;
game.status = STATUS_ERROR;
}
}
}
//returns - [<description>, 'originator', <originator status>, 'taker', <taker status>]
function getBetOutcome() public view returns
(string memory description, string memory originatorKey, uint originatorStatus, string memory takerKey, uint takerStatus)
{
if (game.originator.status == STATUS_TIE || game.taker.status == STATUS_TIE) {
description = "Both bets were the same or were over the number, the pot will be split";
} else {
if (game.originator.status == STATUS_WIN) {
description = "Bet originator guess was closer to the number and will receive the pot";
} else if (game.taker.status == STATUS_WIN) {
description = "Bet taker guess was closer to the number and will receive the pot";
} else {
description = "Unknown Bet Outcome";
}
}
originatorKey = "originator";
originatorStatus = game.originator.status;
takerKey = "taker";
takerStatus = game.taker.status;
}
} | bet statusgame statusgeneral statusthe 'better' structure | contract Bet {
uint constant STATUS_WIN = 1;
uint constant STATUS_LOSE = 2;
uint constant STATUS_TIE = 3;
uint constant STATUS_PENDING = 4;
uint constant STATUS_NOT_STARTED = 1;
uint constant STATUS_STARTED = 2;
uint constant STATUS_COMPLETE = 3;
uint constant STATUS_ERROR = 4;
struct Bet {
uint guess;
address payable addr;
uint status;
}
struct Game {
uint256 betAmount;
uint outcome;
uint status;
Bet originator;
Bet taker;
}
Game game;
function() external payable {}
function createBet(uint _guess) public payable {
game = Game(msg.value, 0, STATUS_STARTED, Bet(_guess, msg.sender, STATUS_PENDING), Bet(0, address(0), STATUS_NOT_STARTED));
game.originator = Bet(_guess, msg.sender, STATUS_PENDING);
}
function takeBet(uint _guess) public payable {
require(msg.value == game.betAmount);
game.taker = Bet(_guess, msg.sender, STATUS_PENDING);
generateBetOutcome();
}
function payout() public payable {
checkPermissions(msg.sender);
if (game.originator.status == STATUS_TIE && game.taker.status == STATUS_TIE) {
game.originator.addr.transfer(game.betAmount);
game.taker.addr.transfer(game.betAmount);
if (game.originator.status == STATUS_WIN) {
game.originator.addr.transfer(game.betAmount*2);
game.taker.addr.transfer(game.betAmount*2);
game.originator.addr.transfer(game.betAmount);
game.taker.addr.transfer(game.betAmount);
}
}
}
function payout() public payable {
checkPermissions(msg.sender);
if (game.originator.status == STATUS_TIE && game.taker.status == STATUS_TIE) {
game.originator.addr.transfer(game.betAmount);
game.taker.addr.transfer(game.betAmount);
if (game.originator.status == STATUS_WIN) {
game.originator.addr.transfer(game.betAmount*2);
game.taker.addr.transfer(game.betAmount*2);
game.originator.addr.transfer(game.betAmount);
game.taker.addr.transfer(game.betAmount);
}
}
}
} else {
function payout() public payable {
checkPermissions(msg.sender);
if (game.originator.status == STATUS_TIE && game.taker.status == STATUS_TIE) {
game.originator.addr.transfer(game.betAmount);
game.taker.addr.transfer(game.betAmount);
if (game.originator.status == STATUS_WIN) {
game.originator.addr.transfer(game.betAmount*2);
game.taker.addr.transfer(game.betAmount*2);
game.originator.addr.transfer(game.betAmount);
game.taker.addr.transfer(game.betAmount);
}
}
}
} else if (game.taker.status == STATUS_WIN) {
} else {
function checkPermissions(address sender) view private {
require(sender == game.originator.addr || sender == game.taker.addr);
}
function getBetAmount() public view returns (uint) {
checkPermissions(msg.sender);
return game.betAmount;
}
function getOriginatorGuess() public view returns (uint) {
checkPermissions(msg.sender);
return game.originator.guess;
}
function getTakerGuess() public view returns (uint) {
checkPermissions(msg.sender);
return game.taker.guess;
}
function getPot() public view returns (uint256) {
checkPermissions(msg.sender);
return address(this).balance;
}
function generateBetOutcome() private {
game.outcome = uint(blockhash(block.number-1))%10 + 1;
game.status = STATUS_COMPLETE;
if (game.originator.guess == game.taker.guess) {
game.originator.status = STATUS_TIE;
game.taker.status = STATUS_TIE;
game.originator.status = STATUS_TIE;
game.taker.status = STATUS_TIE;
if ((game.outcome - game.originator.guess) < (game.outcome - game.taker.guess)) {
game.originator.status = STATUS_WIN;
game.taker.status = STATUS_LOSE;
game.originator.status = STATUS_LOSE;
game.taker.status = STATUS_WIN;
game.originator.status = STATUS_ERROR;
game.taker.status = STATUS_ERROR;
game.status = STATUS_ERROR;
}
}
}
function generateBetOutcome() private {
game.outcome = uint(blockhash(block.number-1))%10 + 1;
game.status = STATUS_COMPLETE;
if (game.originator.guess == game.taker.guess) {
game.originator.status = STATUS_TIE;
game.taker.status = STATUS_TIE;
game.originator.status = STATUS_TIE;
game.taker.status = STATUS_TIE;
if ((game.outcome - game.originator.guess) < (game.outcome - game.taker.guess)) {
game.originator.status = STATUS_WIN;
game.taker.status = STATUS_LOSE;
game.originator.status = STATUS_LOSE;
game.taker.status = STATUS_WIN;
game.originator.status = STATUS_ERROR;
game.taker.status = STATUS_ERROR;
game.status = STATUS_ERROR;
}
}
}
} else if (game.originator.guess > game.outcome && game.taker.guess > game.outcome) {
} else {
function generateBetOutcome() private {
game.outcome = uint(blockhash(block.number-1))%10 + 1;
game.status = STATUS_COMPLETE;
if (game.originator.guess == game.taker.guess) {
game.originator.status = STATUS_TIE;
game.taker.status = STATUS_TIE;
game.originator.status = STATUS_TIE;
game.taker.status = STATUS_TIE;
if ((game.outcome - game.originator.guess) < (game.outcome - game.taker.guess)) {
game.originator.status = STATUS_WIN;
game.taker.status = STATUS_LOSE;
game.originator.status = STATUS_LOSE;
game.taker.status = STATUS_WIN;
game.originator.status = STATUS_ERROR;
game.taker.status = STATUS_ERROR;
game.status = STATUS_ERROR;
}
}
}
} else if ((game.outcome - game.taker.guess) < (game.outcome - game.originator.guess)) {
} else {
function getBetOutcome() public view returns
(string memory description, string memory originatorKey, uint originatorStatus, string memory takerKey, uint takerStatus)
{
if (game.originator.status == STATUS_TIE || game.taker.status == STATUS_TIE) {
description = "Both bets were the same or were over the number, the pot will be split";
if (game.originator.status == STATUS_WIN) {
description = "Bet originator guess was closer to the number and will receive the pot";
description = "Bet taker guess was closer to the number and will receive the pot";
description = "Unknown Bet Outcome";
}
}
originatorKey = "originator";
originatorStatus = game.originator.status;
takerKey = "taker";
takerStatus = game.taker.status;
}
function getBetOutcome() public view returns
(string memory description, string memory originatorKey, uint originatorStatus, string memory takerKey, uint takerStatus)
{
if (game.originator.status == STATUS_TIE || game.taker.status == STATUS_TIE) {
description = "Both bets were the same or were over the number, the pot will be split";
if (game.originator.status == STATUS_WIN) {
description = "Bet originator guess was closer to the number and will receive the pot";
description = "Bet taker guess was closer to the number and will receive the pot";
description = "Unknown Bet Outcome";
}
}
originatorKey = "originator";
originatorStatus = game.originator.status;
takerKey = "taker";
takerStatus = game.taker.status;
}
} else {
function getBetOutcome() public view returns
(string memory description, string memory originatorKey, uint originatorStatus, string memory takerKey, uint takerStatus)
{
if (game.originator.status == STATUS_TIE || game.taker.status == STATUS_TIE) {
description = "Both bets were the same or were over the number, the pot will be split";
if (game.originator.status == STATUS_WIN) {
description = "Bet originator guess was closer to the number and will receive the pot";
description = "Bet taker guess was closer to the number and will receive the pot";
description = "Unknown Bet Outcome";
}
}
originatorKey = "originator";
originatorStatus = game.originator.status;
takerKey = "taker";
takerStatus = game.taker.status;
}
} else if (game.taker.status == STATUS_WIN) {
} else {
} | 6,441,996 | [
1,
70,
278,
1267,
13957,
1267,
12259,
610,
641,
580,
296,
70,
11214,
11,
3695,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
605,
278,
288,
203,
202,
11890,
5381,
7136,
67,
24572,
273,
404,
31,
203,
202,
11890,
5381,
7136,
67,
9320,
273,
576,
31,
203,
202,
11890,
5381,
7136,
67,
56,
8732,
273,
890,
31,
203,
202,
11890,
5381,
7136,
67,
25691,
273,
1059,
31,
203,
203,
202,
11890,
5381,
7136,
67,
4400,
67,
20943,
6404,
273,
404,
31,
203,
202,
11890,
5381,
7136,
67,
20943,
6404,
273,
576,
31,
203,
202,
11890,
5381,
7136,
67,
15795,
273,
890,
31,
203,
203,
202,
11890,
5381,
7136,
67,
3589,
273,
1059,
31,
203,
203,
202,
1697,
605,
278,
288,
203,
202,
202,
11890,
7274,
31,
203,
202,
202,
2867,
8843,
429,
3091,
31,
203,
202,
202,
11890,
1267,
31,
203,
202,
97,
203,
203,
202,
1697,
14121,
288,
203,
202,
202,
11890,
5034,
2701,
6275,
31,
203,
202,
202,
11890,
12884,
31,
203,
202,
202,
11890,
1267,
31,
203,
202,
202,
38,
278,
4026,
639,
31,
203,
202,
202,
38,
278,
268,
6388,
31,
203,
202,
97,
203,
203,
203,
203,
202,
12496,
7920,
31,
203,
202,
915,
1435,
3903,
8843,
429,
2618,
203,
202,
915,
752,
38,
278,
12,
11890,
389,
20885,
13,
1071,
8843,
429,
288,
203,
202,
202,
13957,
273,
14121,
12,
3576,
18,
1132,
16,
374,
16,
7136,
67,
20943,
6404,
16,
605,
278,
24899,
20885,
16,
1234,
18,
15330,
16,
7136,
67,
25691,
3631,
605,
278,
12,
20,
16,
1758,
12,
20,
3631,
7136,
67,
4400,
67,
20943,
6404,
10019,
203,
202,
202,
13957,
18,
4949,
4240,
273,
605,
278,
2
] |
pragma solidity ^0.5.11;
pragma experimental ABIEncoderV2;
import "./EternalStorage.sol";
import "./Consortium.sol";
import './StorageDefinition.sol';
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) {
require(b <= a, "SafeMath: subtraction overflow");
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-solidity/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) {
// 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;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, "SafeMath: modulo by zero");
return a % b;
}
}
library Counters {
using SafeMath for uint256;
struct Counter {
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
counter._value += 1;
}
function decrement(Counter storage counter) internal {
counter._value = counter._value.sub(1);
}
}
library Roles {
struct Role {
mapping (address => bool) bearer;
}
/**
* @dev Give an account access to this role.
*/
function add(Role storage role, address account) internal {
require(!has(role, account), "Roles: account already has role");
role.bearer[account] = true;
}
/**
* @dev Remove an account's access to this role.
*/
function remove(Role storage role, address account) internal {
require(has(role, account), "Roles: account does not have role");
role.bearer[account] = false;
}
/**
* @dev Check if an account has this role.
* @return bool
*/
function has(Role storage role, address account) internal view returns (bool) {
require(account != address(0), "Roles: account is the zero address");
return role.bearer[account];
}
}
library Address {
/**
* @dev Converts an `address` into `address payable`. Note that this is
* simply a type cast: the actual underlying value is not changed.
*/
function toPayable(address account) internal pure returns (address payable) {
return address(uint160(account));
}
}
contract Ownable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
_owner = msg.sender;
emit OwnershipTransferred(address(0), _owner);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Returns true if the caller is the current owner.
*/
function isOwner() public view returns (bool) {
return msg.sender == _owner;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
contract ERC721 {
using SafeMath for uint256;
using Address for address;
using Counters for Counters.Counter;
event ReviewersAdded(bytes32 indexed _tokenId,bytes32 indexed _projectId, address indexed _address);
event ReviewAdded(bytes32 indexed _tokenId, address indexed _reviewer);
EternalStorage s;
Consortium registerContract;
// Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
// which can be also obtained as `IERC721Receiver(0).onERC721Received.selector`
bytes4 private constant _ERC721_RECEIVED = 0x150b7a02;
enum reviewStatus {notInitiated, pending ,approved, rejected}
// Mapping from token ID to owner
mapping (bytes32 => address) private _tokenOwner;
//mapping from token id to other parties
mapping (bytes32 => address[]) private _reviewer;
//mapping from token id to other parties
mapping (bytes32 => mapping (address => reviewStatus)) private _reviewerStatus;
//Mapping from owner to number of owned token
mapping (address => Counters.Counter) private _ownedTokensCount;
constructor (address storageAddress) public {
s = EternalStorage(storageAddress);
// registerContract = Consortium(s.getRegisteredContractAddress("Consortium"));
}
modifier onlyRegistrant() {
require(s.getUserDetails().role == StorageDefinition.roles.admin || s.getUserDetails().role == StorageDefinition.roles.registrant);
_;
}
function addReview(bytes32 tokenId, uint256 status) public{
for (uint i=0; i< _reviewer[tokenId].length; i++){
if(_reviewer[tokenId][i] == msg.sender){
_reviewerStatus[tokenId][msg.sender] = reviewStatus(status);
}
}
emit ReviewAdded(tokenId, msg.sender );
}
function getReviewStatusForIndividual(bytes32 tokenId) public view returns(reviewStatus){
return _reviewerStatus[tokenId][msg.sender];
}
function getReviewStatus(bytes32 tokenId)public view returns(bool){
// address[] storage approvedReviwer;
// address[] storage notApprovedReviwer;
for (uint i=0; i< _reviewer[tokenId].length; i++){
if(_reviewerStatus[tokenId][_reviewer[tokenId][i]] != reviewStatus.approved ){
// approvedReviwer.push(_reviewer[tokenId][i]);
return false;
}
// else {
// notApprovedReviwer.push(_reviewer[tokenId][i]);
// return true;
// }
}
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param owner address to query the balance of
* @return uint256 representing the amount owned by the passed address
*/
function balanceOf(address owner) public view returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _ownedTokensCount[owner].current();
}
function addReviewers(bytes32 tokenId, address reviewer) public returns(bool){
require(ownerOf(tokenId) == msg.sender, "Roles: account does not have access");
_reviewer[tokenId].push(reviewer);
_reviewerStatus[tokenId][reviewer] = reviewStatus.pending;
}
function getReviewersList(bytes32 tokenId) public view returns(address[] memory reviewer){
return _reviewer[tokenId];
}
/**
* @dev Gets the owner of the specified token ID.
* @param tokenId uint256 ID of the token to query the owner of
* @return address currently marked as the owner of the given token ID
*/
function ownerOf(bytes32 tokenId) public view returns (address) {
address owner = _tokenOwner[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev Returns whether the specified token exists.
* @param tokenId uint256 ID of the token to query the existence of
* @return bool whether the token exists
*/
function _exists(bytes32 tokenId) internal view returns (bool) {
address owner = _tokenOwner[tokenId];
return owner != address(0);
}
/**
* @dev Internal function to mint a new token.
* Reverts if the given token ID already exists.
* @param to The address that will own the minted token
* @param tokenId uint256 ID of the token to be minted
*/
function _mint(address to, bytes32 tokenId) internal {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_tokenOwner[tokenId] = to;
_ownedTokensCount[to].increment();
// emit Transfer(address(0), to, tokenId);
}
/**
* @dev Internal function to burn a specific token.
* Reverts if the token does not exist.
* Deprecated, use {_burn} instead.
* @param owner owner of the token to burn
* @param tokenId uint256 ID of the token being burned
*/
function _burn(address owner, bytes32 tokenId) internal {
require(ownerOf(tokenId) == owner, "ERC721: burn of token that is not own");
_ownedTokensCount[owner].decrement();
_tokenOwner[tokenId] = address(0);
// emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Internal function to burn a specific token.
* Reverts if the token does not exist.
* @param tokenId uint256 ID of the token being burned
*/
function _burn(bytes32 tokenId) internal {
_burn(ownerOf(tokenId), tokenId);
}
}
/**
* @title ERC721Mintable
* @dev ERC721 minting logic.
*/
contract ERC721Mintable is ERC721 {
/**
* @dev Function to mint tokens.
* @param to The address that will receive the minted tokens.
* @param tokenId The token id to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address to, bytes32 tokenId) internal returns (bool) {
_mint(to, tokenId);
return true;
}
}
contract ERC721Metadata is ERC721 {
struct docDetails {
string encryptedData;
string encryptedPassword;
bytes32 projectId;
uint256 timeStamp;
}
event DetailsUpdated(bytes32 tokenId, uint256 indexed timeStamp, string indexed remark );
// Optional mapping for token URIs
mapping(bytes32 => string) private _tokenURIs;
// mapping for token deviceDetails
mapping(bytes32 => docDetails) private _tokenDetails;
/*
* bytes4(keccak256('name()')) == 0x06fdde03
* bytes4(keccak256('symbol()')) == 0x95d89b41
* bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd
*
* => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f
*/
bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f;
/**
* @dev Returns an URI for a given token ID.
* Throws if the token ID does not exist. May return an empty string.
* @param tokenId uint256 ID of the token to query
*/
function tokenURI(bytes32 tokenId) external view returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
return _tokenURIs[tokenId];
}
function getDocumentDetails(bytes32 tokenId) external view returns (docDetails memory,string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
return (_tokenDetails[tokenId],_tokenURIs[tokenId]);
}
/**
* @dev Internal function to set the token URI for a given token.
* Reverts if the token ID does not exist.
* @param tokenId uint256 ID of the token to set its URI
* @param uri string URI to assign
*/
function _setTokenURI(bytes32 tokenId, string memory uri) internal {
require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token");
_tokenURIs[tokenId] = uri;
}
function _setProjectId (bytes32 tokenId, bytes32 projectId) internal{
require(_tokenDetails[tokenId].projectId == 0x0, "Project Id reassign denied!");
docDetails memory temp = _tokenDetails[tokenId];
temp.projectId = projectId;
_tokenDetails[tokenId] = temp;
}
function _setDocumentDetails(bytes32 tokenId,string memory encryptedData, string memory encryptedPassword ) internal {
docDetails memory temp;
temp.encryptedData = encryptedData;
temp.encryptedPassword = encryptedPassword;
temp.timeStamp = block.timestamp;
_tokenDetails[tokenId] = temp;
}
function _updateDocumentDetails(bytes32 tokenId,string memory remark, string memory encryptedData) internal {
_tokenDetails[tokenId].encryptedData = encryptedData;
emit DetailsUpdated(tokenId, block.timestamp, remark);
}
/**
* @dev Internal function to burn a specific token.
* Reverts if the token does not exist.
* Deprecated, use _burn(uint256) instead.
* @param owner owner of the token to burn
* @param tokenId uint256 ID of the token being burned by the msg.sender
*/
function _burn(address owner, bytes32 tokenId) internal {
super._burn(owner, tokenId);
// Clear metadata (if any)
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
}
function addReviewers(bytes32 tokenId, address reviewer) public returns(bool){
require(ownerOf(tokenId) == msg.sender, "Roles: account does not have access");
super.addReviewers(tokenId,reviewer);
emit ReviewersAdded(tokenId,_tokenDetails[tokenId].projectId ,reviewer);
}
}
// contract ERC721MetadataMintable is ERC721, ERC721Metadata {
// /**
// * @dev Function to mint tokens.
// * @param to The address that will receive the minted tokens.
// * @param tokenId The token id to mint.
// * @param tokenURI The token URI of the minted token.
// * @return A boolean that indicates if the operation was successful.
// */
// function mintWithTokenURI(address to, string memory tokenId, string memory tokenURI) public returns (bool) {
// _mint(to, tokenId);
// _setTokenURI(tokenId, tokenURI);
// return true;
// }
// }
contract ERC721Enumerable is ERC721 , ERC721Metadata {
// Mapping from owner to list of owned token IDs
mapping(address => bytes32[]) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(bytes32 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
bytes32[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(bytes32 => uint256) private _allTokensIndex;
// Mapping from project to list of owned token IDs
mapping(bytes32 => bytes32[]) private _ownedTokensByProject;
// Mapping from token ID to index of the project tokens list
mapping(bytes32 => uint256) private _ownedTokensByProjectIndex;
/**
* @dev Internal function to mint a new token.
* Reverts if the given token ID already exists.
* @param to address the beneficiary that will own the minted token
* @param tokenId uint256 ID of the token to be minted
*/
function _mint(address to, bytes32 tokenId) internal {
super._mint(to, tokenId);
_addTokenToOwnerEnumeration(to, tokenId);
_addTokenToAllTokensEnumeration(tokenId);
}
/**
* @dev Internal function to burn a specific token.
* Reverts if the token does not exist.
* Deprecated, use {ERC721-_burn} instead.
* @param owner owner of the token to burn
* @param tokenId uint256 ID of the token being burned
*/
function _burn(address owner, bytes32 tokenId) internal {
super._burn(owner, tokenId);
_removeTokenFromOwnerEnumeration(owner, tokenId);
// Since tokenId will be deleted, we can clear its slot in _ownedTokensIndex to trigger a gas refund
_ownedTokensIndex[tokenId] = 0;
_removeTokenFromAllTokensEnumeration(tokenId);
}
/**
* @dev Gets the list of token IDs of the requested owner.
* @param owner address owning the tokens
* @return uint256[] List of token IDs owned by the requested address
*/
function _tokensOfOwner(address owner) public view returns (bytes32[] memory) {
return _ownedTokens[owner];
}
function _tokensOfProject(bytes32 projectId) public view returns (bytes32[] memory) {
return _ownedTokensByProject[projectId];
}
function _setProjectId (bytes32 tokenId, bytes32 projectId) internal{
super._setProjectId(tokenId,projectId);
_addTokenToProjectEnumeration(projectId, tokenId);
}
function _addTokenToProjectEnumeration(bytes32 projectId , bytes32 tokenId) private {
_ownedTokensIndex[tokenId] = _ownedTokensByProject[projectId].length;
_ownedTokensByProject[projectId].push(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, bytes32 tokenId) private {
_ownedTokensIndex[tokenId] = _ownedTokens[to].length;
_ownedTokens[to].push(tokenId);
}
/**
* @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(bytes32 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, bytes32 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 = _ownedTokens[from].length.sub(1);
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
bytes32 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
_ownedTokens[from].length--;
// Note that _ownedTokensIndex[tokenId] hasn't been cleared: it still points to the old slot (now occupied by
// lastTokenId, or just over the end of the array if the token was the last one).
}
/**
* @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(bytes32 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.sub(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)
bytes32 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
_allTokens.length--;
_allTokensIndex[tokenId] = 0;
}
}
contract ERC721Burnable is ERC721 {
/**
* @dev Burns a specific ERC721 token.
* @param tokenId uint256 id of the ERC721 token to be burned.
*/
function burn(bytes32 tokenId) public {
//solhint-disable-next-line max-line-length
_burn(tokenId);
}
}
contract DocContract is ERC721, ERC721Enumerable,ERC721Burnable,ERC721Mintable {
constructor(address storageAddress) ERC721(storageAddress) public {
}
event MetadataChanged(bytes32 indexed tokenId , string indexed metadata);
function setMetadata(bytes32 tokenId, string memory metadata ) public onlyRegistrant returns (bool) {
require(ownerOf(tokenId) == msg.sender, "ERC721: can not set metadata of token that is not own");
_setTokenURI(tokenId , metadata);
emit MetadataChanged(tokenId,metadata);
return true;
}
function setProjectId(bytes32 tokenId, bytes32 projectId ) public onlyRegistrant returns (bool) {
registerContract = Consortium(s.getRegisteredContractAddress("Consortium"));
require(ownerOf(tokenId) == msg.sender, "ERC721: can not set metadata of token that is not own");
_setProjectId(tokenId , projectId);
registerContract.addDocumentToProject(tokenId,projectId);
return true;
}
function MintWithDetailsAndProjectId (address to, bytes32 tokenId,string memory encryptedData, string memory encryptedPassword, bytes32 projectId) public onlyRegistrant returns (bool){
_setDocumentDetails(tokenId, encryptedData, encryptedPassword);
mint(to, tokenId);
registerContract = Consortium(s.getRegisteredContractAddress("Consortium"));
require(ownerOf(tokenId) == msg.sender, "ERC721: can not set metadata of token that is not own");
_setProjectId(tokenId , projectId);
registerContract.addDocumentToProject(tokenId,projectId);
return true;
}
function updateDetails(bytes32 tokenId,string memory encryptedData, string memory encryptedPassword ) public onlyRegistrant returns (bool) {
require(ownerOf(tokenId) == msg.sender, "ERC721: can not set metadata of token that is not own");
_updateDocumentDetails(tokenId, encryptedData, encryptedPassword);
return true;
}
function MintWithDetails(address to, bytes32 tokenId,string memory encryptedData, string memory encryptedPassword ) public onlyRegistrant returns (bool) {
_setDocumentDetails(tokenId, encryptedData, encryptedPassword);
mint(to, tokenId);
// registerContract.addDeviceToProject(tokenId, (projectId));
return true;
}
} | * @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(bytes32 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
| 6,405,888 | [
1,
6014,
445,
358,
527,
279,
1147,
358,
333,
2710,
1807,
1147,
11093,
501,
12597,
18,
225,
1147,
548,
2254,
5034,
1599,
434,
326,
1147,
358,
506,
3096,
358,
326,
2430,
666,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
389,
1289,
1345,
774,
1595,
5157,
21847,
12,
3890,
1578,
1147,
548,
13,
3238,
288,
203,
3639,
389,
454,
5157,
1016,
63,
2316,
548,
65,
273,
389,
454,
5157,
18,
2469,
31,
203,
3639,
389,
454,
5157,
18,
6206,
12,
2316,
548,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/8453/0x000000000031163395F67E424F5B0082609709a7/sources/signed-zone/SignedZoneCaptain.sol | * @notice This will remove all active signers of the given zone and clear the rotator address on the captain. Only callable by the owner or the sanitizer of the zone. @param zone The zone to revoke./ Ensure caller is the owner or the sanitizer. Call to the signed zone controller to sanitize the signed zone. Loop through the signers and deactivate them. | function sanitizeSignedZone(address zone) external override {
_assertCallerIsOwnerOrSanitizer();
address[] memory signers = _SIGNED_ZONE_CONTROLLER.getActiveSigners(
zone
);
for (uint256 i = 0; i < signers.length; i++) {
_SIGNED_ZONE_CONTROLLER.updateSigner(zone, signers[i], false);
}
}
| 16,789,147 | [
1,
2503,
903,
1206,
777,
2695,
1573,
414,
434,
326,
864,
4157,
471,
2424,
540,
326,
4168,
639,
1758,
603,
326,
9656,
530,
18,
5098,
4140,
635,
326,
3410,
540,
578,
326,
6764,
1824,
434,
326,
4157,
18,
225,
4157,
1021,
4157,
358,
18007,
18,
19,
7693,
4894,
353,
326,
3410,
578,
326,
6764,
1824,
18,
3049,
358,
326,
6726,
4157,
2596,
358,
8881,
326,
6726,
4157,
18,
9720,
3059,
326,
1573,
414,
471,
18790,
2182,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
8881,
12294,
4226,
12,
2867,
4157,
13,
3903,
3849,
288,
203,
3639,
389,
11231,
11095,
2520,
5541,
1162,
26131,
1824,
5621,
203,
203,
3639,
1758,
8526,
3778,
1573,
414,
273,
389,
21049,
67,
20725,
67,
6067,
25353,
18,
588,
3896,
2766,
414,
12,
203,
5411,
4157,
203,
3639,
11272,
203,
203,
3639,
364,
261,
11890,
5034,
277,
273,
374,
31,
277,
411,
1573,
414,
18,
2469,
31,
277,
27245,
288,
203,
5411,
389,
21049,
67,
20725,
67,
6067,
25353,
18,
2725,
15647,
12,
3486,
16,
1573,
414,
63,
77,
6487,
629,
1769,
203,
3639,
289,
203,
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
] |
./partial_match/1/0xfF8E178aE420CF450921523b90F1Be1453C31757/sources/QLCTokenV2.sol | * @dev Emitted Mint Info Parameters: - `user`: index, user address - `nep5Hash`: neo transaction hash - `amount`: mint amount/ | event Mint(address indexed user, bytes32 nep5Hash, uint256 amount);
| 3,638,726 | [
1,
1514,
11541,
490,
474,
3807,
7012,
30,
300,
1375,
1355,
68,
30,
770,
16,
729,
1758,
300,
1375,
82,
881,
25,
2310,
68,
30,
1073,
83,
2492,
1651,
300,
1375,
8949,
68,
30,
312,
474,
3844,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
871,
490,
474,
12,
2867,
8808,
729,
16,
1731,
1578,
290,
881,
25,
2310,
16,
2254,
5034,
3844,
1769,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0x6E910C8Dc96d084dFf41785BBE4646Fa946B90B7/sources/Slezisatoshi.sol | SPDX-License-Identifier: UNLICENSED | abstract contract Context {
pragma solidity ^0.8.15;
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
}
| 3,909,466 | [
1,
3118,
28826,
17,
13211,
17,
3004,
30,
5019,
6065,
1157,
18204,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
17801,
6835,
1772,
288,
203,
1377,
203,
683,
9454,
18035,
560,
3602,
20,
18,
28,
18,
3600,
31,
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,
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
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.